When would this code print out....
class jaha{
public static void main (String [] args){
String x="hello";
String y="hello";
if (x.equals(y)){
System.out.println("true");
if (x==y){
System.out.println("true");
}
if (x!=y){
System.out.println("false");
}
}
}
}
Is there any values of x and y to make it print out
true
false
??
Re: When would this code print out....
Re: When would this code print out....
output of the code would be:
true
false
x.equals(y) gives us true
but as x and y are strings x==y doesnt work so it prints false
hope it helps :)
Re: When would this code print out....
Quote:
Originally Posted by
rougeking
output of the code would be:
true
false
x.equals(y) gives us true
but as x and y are strings x==y doesnt work so it prints false
hope it helps :)
Not quite. x == y will be true *sometimes*. Since most Strings are interred in the String pool in order to minimize the unnecessary needless creation of objects, many times stringA will == stringB even when you don't expect it to. But if you explicitly tell the JVM to create a new String object via the new String(...) constructor, then you know that == will return false even if the Strings contain the same chars in the same order. The reason being that == checks for object equality -- that two references are actually one and the same, while the equals(...) method tests for functional equality -- that two objects are functionally equal as defined by the equals method of their class.