Link to home
Start Free TrialLog in
Avatar of JRawabi
JRawabi

asked on

String in Java

Hi

What is the difference between the following 2 statements:


      String Str1 = new String("Welcome to Tutorialspoint.com");

      System.out.println(Str1.length());

And

String Str1="Welcome to Tutorialspoint.com";

      System.out.println(Str1.length());
ASKER CERTIFIED SOLUTION
Avatar of Sharon Seth
Sharon Seth
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
When it comes to Strings , Java has a concept of string internalizing , or in short string interns.
The JVM maintains a pool of strings . Whenever you assign a string literal(as in the second case) the string gets pooled . Next time someone wants to create another string with the same value , then the String object from the pool is used. It means new memory is not allocated , but the existing reference is used.

But when you use the new() operator , new memory is allocated to the string , instead of using an already existing reference from the pool

For this reason , String class has an intern() method , which  will send a string to the pool . All this is for optimizing string memory due to the fact that strings are immutable.