+ 3

Why the output is false?

String a=new String("java"); String b=new String("java"); System.out.print(a==b);

16th Sep 2020, 6:46 PM
Rashmi Jana
1 Réponse
+ 6
When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in "PermGen" area of heap. string literals refer the same object eg: String s1 = "java"; String s2 = "java"; System.out.println(a == b); // true This is true because only 1 string with " abc" created in string constant pool, variable s1 and s2 both reffer to the same string. By using new() 2 different objects are created and they have different references: String a = new String("java"); String b = new String("java"); System.out.println(a == b); // false Here this is false because 2 different objects are created in the heap area(not in string pool) Note* Plz note that == is a reference matching operator(not content matching). For content matching u have to use .equals() method. eg: String sr = "java"; String fr = new String("java"); System.out.print(sr.equals(fr));// true This is true because we are matching contents not refere
16th Sep 2020, 6:55 PM
A S Raghuvanshi
A S Raghuvanshi - avatar