• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why does it return "FALSE"...?

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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...
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic