Java Programming

code - 1

{

String a = "ABC";

String b = "ABC";

boolean c = (a==b);

System.out.println("a == b? "+c);

}

code - 2

{

String a = new String("ABC");

String b = new String("ABC");

boolean c = (a==b);

System.out.println("a == b? "+c);

}

Why the output of code 1 and code 2 is differnce

[377 byte] By [Java1a] at [2007-10-2 7:37:06]
# 1
http://forum.java.sun.com/thread.jspa?threadID=691424One thread is enough. As if there weren't 500000 about this already.
CeciNEstPasUnProgrammeura at 2007-7-16 21:19:24 > top of Java-index,Java Essentials,New To Java Technology Archive...
# 2

The difference is that in c1 code, both the String Objects a and b refer to the same object instance i.e. "ABC". However, in c2 code, when you initialize them with new String() constructor, two different instances a and b of String are created. == operator compares the two object instances. If they refer to the same instance, it return true otherwise false. Is it clear?

dhirendra_logicona at 2007-7-16 21:19:24 > top of Java-index,Java Essentials,New To Java Technology Archive...
# 3
String is Object USE: boolean c = (a.equals(b));it will give you correct result
vasko__@hotmail.coma at 2007-7-16 21:19:24 > top of Java-index,Java Essentials,New To Java Technology Archive...
# 4
> String is Object USE: boolean c = (a.equals(b));>it will give you correct result== will also give you the correct result. It all depends on what you want to test. == and equals() are completely different things.
CeciNEstPasUnProgrammeura at 2007-7-16 21:19:24 > top of Java-index,Java Essentials,New To Java Technology Archive...