This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Java in General and the fly likes I think there is a bug in the java soft Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "I think there is a bug in the java soft" Watch "I think there is a bug in the java soft" New topic

I think there is a bug in the java soft

saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689

hello, i am trying to print this lineX statement to the console
but it just displays flase
it is not displaying s3==s4 false
so, this is the bug in java :roll:

atleast it must to give compile time error

SCJP 1.4
amod gole
Ranch Hand

Joined: Dec 07, 2005
Posts: 83
hi krish.....
there is no bug in your code
in this case
first s3 gets concanated to your "s3==s4"
and then there is comparision betn
"s3==s4apple" == s4
first second
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42958
There is no bug in either the JVM or the compiler. You're assuming that you can test string equality by using "==". In general, that is not so - use the String.equals method.
Srinivas Kalvala
Ranch Hand

Joined: Oct 20, 2005
Posts: 257



First read this,

Println() always calls the toString() method on Object and the returned toString() String argument will not be placed String pool but will be stored as a normal attribute in local method stack, or treated as argument to method println().

Here the toString() method on both s3 & s4 will be called and 2 String objects in local stack will be created, so the == will give false, because, they are pointing to different memory locations.

One can rectify this using the equals method.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24193

This is a wonderfully subtle issue, and only Amod Gole picked up on it; neither Ulf nor Srinivas spoke to it.

The reason that only 'false' is printed, and not 's3 == s4 false' is that the expression

"s3 == s4" + s3 == s4

is not interpreted as

"s3 == s4" + (s3 == s4)

but rather as

("s3 == s4" + s3) == s4

and, given that, it should be obvious why just 'false' is printed.

Note that much of what Srinivas says about Strings and pools and stacks and locals and so on and so on wouldn't be relevant (or quite correct) even if this was a question about equals() vs. == -- but it's not.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: I think there is a bug in the java soft
jQuery in Action, 3rd edition