Thursday, June 21, 2007

Difference between new String("hello") and "hello"

public class test
{
public static void main(String[] args)
{
String a = new String("hello");
String b = new String("hello");

if(a == b)
System.out.println("Equal");
else
System.out.println("Not Equal");

String c = "hello";
String d = "hello";
if(c == d)
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}

i expected i will get since a, b, c and d are reference to difference objects (or maybe i am wrong)
"Not Equal"
"Not Equal"

however, what i get is
"Not Equal"
"Equal"

isnt that c and d are refrence to different objects?

Strings are pooled and shared in Java, for efficiency reasons. By constructing a String object with the new keyword, you are explicitly telling the JVM not to the use strings from the pool. Therefore, for String a and b, they are referencing to 2 different strings (that is, 2 strings that are located on different addresses in the memory), whereas for c and d, they are referencing the to the same string located on the same address in memory.



== compares the memory addresses and not the value of the variables.

equals
public boolean equals(Object obj)Indicates whether some other object is "equal to" this one.
The equals method implements an equivalence relation:

It is reflexive: for any reference value x, x.equals(x) should return true.
It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.
For any non-null reference value x, x.equals(null) should return false.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true).

3 comments:

Novie Ardilla said...

Thanks for the good article, hope you guys want to come to my website to .
Agen Taruhan Judi Bola
Daftar Judi Bola Online
Cara Bermain Judi Bola
Daftar Bola Online
Daftar Agen Bola Online Terpercaya
Prediksi Bola
Live Draw HK

Sherly Claudia said...

This is sensible information! Where else will if ind out more?? Who runs this joint too? sustain the excellent function
DominoQQ
Judi Bola
Slot Online
Ceme Online
BCA368
BCA368

link alternatif pastipoker said...

The isAlive method returns true if the thread has been started and not stopped