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,943
  • 13
  • 104
  • 142
JAN
  • 21,236
  • 66
  • 181
  • 318

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,966
  • 12
  • 68
  • 104
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,575
  • 4
  • 34
  • 47