• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

I think there is a bug in the java soft

 
saikrishna cinux
Ranch Hand
Posts: 689
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



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
 
amod gole
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi krish.....
there is no bug in your code
System.out.println("s3==s4"+s3==s4);//lineX
in this case
first s3 gets concanated to your "s3==s4"
and then there is comparision betn
"s3==s4apple" == s4
first second
so
output
false
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 257
Firefox Browser Hibernate Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Cool.

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
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic