It's not a secret anymore!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Unable to undustand the System.out.println behaviour 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 "Unable to undustand the System.out.println behaviour" Watch "Unable to undustand the System.out.println behaviour" New topic
Author

Unable to undustand the System.out.println behaviour

Shyam kumar
Ranch Hand

Joined: May 21, 2006
Posts: 146
Greetings Ranchers,

Please have a look at the code snippet below:

1. StringBuffer str1=new StringBuffer("Hello World!");
2. String str2=new String("Hello World!");
3. System.out.println("str1.hashcode()"+str1.hashCode());
4. System.out.println("str2.hashcode()"+str2.hashCode());
5. System.out.println("str1 == str2"+str1 == str2);

When I'm executing the above piece of code, I'm getting the following output
---------- run ----------
str1.hashcode()15655788
str2.hashcode()-969099747
false
Output completed (0 sec consumed) - Normal Termination

Ideally line no. 5 is attempting to compare two incompatible types, String and StringBufffer and should throw an error if we rewrite the line as

5. System.out.println("str1 == str2"+(str1 == str2));

BUT, the strange part is that I'm getting output as false. And unlike the first two output the text string "str1 == str2" is also not printed.

Can anyone explain me the sanity behind this behaviour?
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9351
    
    2

Hi Above,

The line ("str1 == str2"+(str1 == str2)); returns false because you are comparing the references to two different objects. str1 points to a different object and str2 points to a different object in the memory. so the O/P false.

For the System.out.println("str1 == str2"+str1 == str2);, the compiler interprets it as, (("str1 == str2"+str1) == str2); bcos + has higher precedence than ==.

Regards,
Jothi Shankar Kumar. S


SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
Shyam kumar
Ranch Hand

Joined: May 21, 2006
Posts: 146
That's Great Shankar
Thanks a lot...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Unable to undustand the System.out.println behaviour