+ 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
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
+ 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.
+ 1
thank you guys, I got it now.
0
@1of3 can you suggest me where can I learn more about it.