Java String

 

Java String

We all know String class in Java is immutable and the value once stored in String Object can't be modified. Also we have discussed about this in our earlier tutorials like difference between String, StringBuffer and StringBuilder and how to create user defined immutable class in Java. We will see how "==" equals operator works on String Object. 

We know that when we apply "==" equals operator on Object it will check only the Object reference rather than values stored in the Object. So using "==" on string Object will result incorrect output and advised to use equals() method which internally overrides hashcode() which will check the values in the Objects using hashing algorithm and gives the correct output.

In this tutorial we will see about how "==" equals operator works internally on string Object with different scenarios. 

Program : 1


public class StringTest {
 
 public static void main(String[] args) {
  String str1 = "javadiscover";
  String str2 = "javadiscover";
  System.out.println(str1 == str2);
 }
}

OUTPUT:


true



We can see in above disassembled code from Java class file, both String references are same. So when we compare these string Objects with "==" operator we will get true. 


Program : 2


public class StringTest {
 
 public static void main(String[] args) {
  String str1 = "javadiscover";
  String str2 = "java" + "discover";
  System.out.println(str1 == str2);
 }
}

OUTPUT:


true



We can see both the string Objects are referred by same reference. So we are getting true when we compare by "==" operator. 


Program : 3


public class StringTest {
 
 public static void main(String[] args) {
  String str1 = "javadiscover";
  String str2 = "java";
  String str3 = "discover";
  String str4 = str2 + str3;
  System.out.println(str1 == str4);
 }
}

OUTPUT:


false



From above code we can clearly see first 3 string objects are having different references. But 4th "Str4" String in java file contains same value of 1st String "str1" but JDK has created StringBuilder class instead of String with different reference. Hence we are getting false when we compare "str1" and "str4" with "==" operator. 



No comments:
Write comments