When a String literal is encountered, the pool is checked to see if an identical String already exists. If it’s there, no new String literal object is created, we’ll simply have an additional reference to the same existing object.
Now, if several reference variables refer to the same String object without even knowing it. It would be very bad if anyone could change the String’s value. So Strings have been made immutable and java.lang.String has been declared final.
Understanding the different ways to create String Objects
String s1 = “Noida”;
Noida s1 String Pool
String s2 = new String(“Delhi”);
String s3 = new String(“Noida”);
Heap Delhi s3 s2 Delhi Noida
Note that String literal “Delhi” has been placed in the pool.
+ & += have been overloaded to work on Strings.
String s1 =“ is “;
String s2 = new String(“ whole no.”);
6 a a c String Pool is whole no. Heap s1 s2 whole no. 6 is a whole no. System.out.println(a+s1+c+s2);
Working with Strings : Using public methods defined in the java.lang.String
public char charAt(int index)
returns the character with the index specified.
public String concat(String s)
concatenates s at the end of the string invoked & returns the reference of new String Object.
public Boolean equalsIgnoreCase(String s)
Compares 2 String Objects irrespective of their character case.
public int length()
returns the no. of characters of the character sequence encapsulated in the string object.
length() of String class is different than the length that we use to get no. of elements in an array.
java.lang.Object java.lang.String Output : true true false true public boolean equals(java.lang.Object); public boolean equals(java.lang.Object); equals (java.lang.Object) of java.lang.Object is overridden by equals(java.lang.Object) of java.lang.String