1

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"

2 Answers2

1

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

Community
  • 1
  • 1
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
  • Why did you post an answer that is almost a duplicate of a previously posted answer to this question? – Jim Garrison Aug 15 '16 at 05:51
  • i was writing this answer and he posted somewhere when i was about to finish and there is a difference , i mention about what == does and what equals does.i respect your point of view though i think it's worth posting it. – Pavneet_Singh Aug 15 '16 at 05:56
  • Ok they are pointing at the same object but what happens when after that I do this b="qwe";? (i guess in this moment i create new object with qwe ) – Илия Камбуров Aug 15 '16 at 06:06
  • it mean you are also creating a new object (if there is no string constant in the memory with "qwe" string content) and assigning it's reference to `b` because ` b="qwe";` means ` b=new String("qwe");`. String objects has this shortcut feature. – Pavneet_Singh Aug 15 '16 at 06:12
0

This has to be a duplicate of a large number of questions, but I will comment by saying that when you do the following:

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

The JVM creates a single String object in the constant pool which contains the String abc. Hence, the a and b Strings simply point to the same string in the pool.

However, when you do the following:

String a = "abc";
String b = new String("abc");

a new object is created even though abc already exists in the pool. Hence the comparison a == b returns false, although the contents of both these strings remains equivalent.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360