This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why does it return "FALSE"...?  RSS feed

 
Rekha Anand
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Forum Members...

I found this piece of code -

public class samp
{
public static void main(String arg[])
{
Byte b1 = new Byte("127");

if(b1.toString() == b1.toString())
System.out.println("True");
else
System.out.println("False");
}
}


This code compiles fine and returns False. I cannot understand..WHY? Please help...
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16026
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you use the == operator to compare two objects, then Java only returns true if the two operands refer to the exact same object. In this line:

if(b1.toString() == b1.toString())

You are comparing two strings, which are objects, using the == operator. This will only return true if the two strings are the exact same object - it will return false otherwise, even if the two strings contain the same text.

If you want to compare two objects by the content, you should use the equals() method instead of ==:

if(b1.toString().equals(b1.toString()))
[ March 04, 2008: Message edited by: Jesper Young ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!