+ 1

Java: Can someone explain this code please.

hello why this conditions is not true String a =new String("hello world"); if(a=="hello world") { System.out.println(1); } else{ System.out.println(0); } is It related to objects? because Ive just started with objects I dont have much knowledge about it

18th Feb 2018, 6:00 AM
Rohit Kashyap
Rohit Kashyap - avatar
4 Réponses
+ 9
Change the "if" part to: if(a.equals("hello world")) String comparison must use equals method, the == operator returns true only if you compare two objects that refer to the same thing. e.g. String a = "Hello, world"; String b = a; System.out.println(b == a); Hth, cmiiw
18th Feb 2018, 6:33 AM
Ipang
+ 3
It would also work with the ==, if you change the first line to String a = "hello world" ; Because string literals are interned in a special memory area. By calling new String you told the JVM to put your String on the heap like a normal object.
18th Feb 2018, 7:08 AM
1of3
1of3 - avatar
+ 1
thank you guys, I got it now.
18th Feb 2018, 9:50 AM
Rohit Kashyap
Rohit Kashyap - avatar
0
@1of3 can you suggest me where can I learn more about it.
18th Feb 2018, 9:51 AM
Rohit Kashyap
Rohit Kashyap - avatar