0

Consider the code :

public class Strings {

    public static void createStr()
    {
        String s1 = new String("one");
        String s2 = "one";

        System.out.println(s1);
        System.out.println(s2);
    }

    public static void main(String args[])
    {
        createStr();
    }

}

What's the difference between String s1 = new String("one"); and String s2 = "one"; ?

Charles
  • 50,010
  • 13
  • 100
  • 141
JAN
  • 20,056
  • 54
  • 170
  • 290

2 Answers2

7
  String s1 = new String("one"); // will be created on the heap and not interned unless .intern() is called explicityly. 
  String s2 = "one";  // will be created in the String pool and interned automatically by the compiler.
TheLostMind
  • 35,468
  • 12
  • 66
  • 99
0

String s1 = new String("one"); create a new string object in memory, while String s2 = "one"; use the string pool.

It is not a good practice to use new keyword when dealing with string in java.

fluminis
  • 3,325
  • 4
  • 30
  • 45