Илия Камбуров Илия Камбуров - 29 days ago 11
Java Question

What is the difference between this two ways of initializing String

This two codes have defferent outputs and i don't know why.

String a="abc";
String b="abc";
System.out.println(a==b + " " + a.equals(b));


The output is "true true"

String a="abc";
String b=new String("abc");
System.out.println(a==b + " " + a.equals(b));


The output is "false true"

Answer

when you use this

String a="abc";
String b="abc";

the java creates only one object in memory which is abc and here a and b are pointing to same object and == don't check the string content instead it check the reference value. but as soon as you do this

String b=new String("abc");

java creates a new object b in memory which is different from a ,now b and a are pointing to two different objects hence if you compare contents with equals function result will be true but if you compare reference now, result will be false

Read about it's usage

Comments