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.le ngth());
And
String Str1="Welcome to Tutorialspoint.com";
System.out.println(Str1.le ngth());
What is the difference between the following 2 statements:
String Str1 = new String("Welcome to Tutorialspoint.com");
System.out.println(Str1.le
And
String Str1="Welcome to Tutorialspoint.com";
System.out.println(Str1.le
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.