This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Why does it return Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why does it return "FALSE"...?" Watch "Why does it return "FALSE"...?" New topic
Author

Why does it return "FALSE"...?

Rekha Anand
Ranch Hand

Joined: Feb 23, 2008
Posts: 36
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
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

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 ]

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
 
subject: Why does it return "FALSE"...?
 
Similar Threads
Wrapper-Method-Q
* Byte == comparision
Byte and String
String Question
related to "=="