Wednesday, November 26, 2008

Java String tricky ques

String s1 = "hello world";
String s2 = "hello world";

if(s1==s2)
System.out.println("Yes");
else
System.out.println("No");

// output of first is Yes
the reason being that in above code you are comparing two references

public static void point1()
{
String s = new String("Friday");
String s1 = new String("Friday");
if (s == s1)
System.out.println("Equal A");
if (s.equals("Friday"))
System.out.println("Equal B");
}
ANS : Equal B
Because they are two different objects on heap , refering diff memeory addresses
hence their reference is not same.

more explanation here.

No comments: