*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes crack the output! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "crack the output!" Watch "crack the output!" New topic
Author

crack the output!

Anshuman Acharya
Ranch Hand

Joined: Jan 19, 2001
Posts: 144
the output of this is true... i was just goofing around and seeing the o/ps for some unique cases...
can anyone explain this.. i guess
a null is a null is a null!
//code
class a{
static String s1;
static String s2 = new String(s1);
public static void main(String args[]){
System.out.println(s1 == s2);
}
}
//code ends here

Anshuman Acharya
Ranch Hand

Joined: Jan 19, 2001
Posts: 144
also, this code gives no o/p...
tho' o and s both are null the equals method of String returns a false if the argument passed to it is not of type String-
//code
class a{
public static void main(String args[]){
Object o = new Object();
String s = new String();
if(s.equals(o))
System.out.println("We are Equal");}
}
//code ends
S Dave
Ranch Hand

Joined: Jan 28, 2001
Posts: 103
to my surprise when i printed out o and s I got a blank for s while
" java.lang.Object@72068142 " for o.
Anshuman Acharya
Ranch Hand

Joined: Jan 19, 2001
Posts: 144
an interesting observation Sweekriti!
While the toString method for String returns the string literal representation(which in this case is nothing) for Object it returns the name of the class of which the object is an instance and the hexadecimal rep. of its hash code separated by the @ symbol.
HEnce, it is always advisable for user-made objects to override the toString method if they want a meaningful representation.
natarajan meghanathan
Ranch Hand

Joined: Feb 01, 2001
Posts: 130
Anshuman,
I get a null pointer exception when i ran the code u have posted. I think it should give null pointer exception because, s1 = null and u r trying s1 == s2.
thanks.

Sun Certified Programmer for Java 2 Platform
Wong KK
Ranch Hand

Joined: Jan 15, 2001
Posts: 52
I can't run the above code too. I am using JDK1.2.2
It gives :
Exception in thread "main" java.lang.ExceptionInInitializerError: java.lang.Null
PointerException:
Please clarify.
Anshuman Acharya
Ranch Hand

Joined: Jan 19, 2001
Posts: 144
sorry folks i am wrong... and the sad fact is that so are you, natrajan!
the thing is that the nullpointerexception pops from the fact that s2 is being built upon a null reference in its assignment.
declare s2 as String s2; and you'll get true.. try it...
natarajan meghanathan
Ranch Hand

Joined: Feb 01, 2001
Posts: 130
Yes Anshuman,
After i posted it it flashed in my mind. It is due to s2 rather than s1. And if we do String s2, it is obviously true.
thanx.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: crack the output!