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"

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Why did you post an answer that is almost a duplicate of a previously posted answer to this question?
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.
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 )
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.
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.

2 Comments

Comments, downvotes? Say something.
To add to this: In Java, == compares the memory location, and equals() compares the content of the Strings.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.