• 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

Equals and == on Booleans and Strings

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The following code will give
1: Byte b1 = new Byte("127");
2:
3: if(b1.toString() == b1.toString())
4: System.out.println("True");
5: else
6: System.out.println("False");
A) Compilation error, toString() is not avialable for Byte.
B) Prints "True".
C) Prints "False".
The answer is C and I do not seem to get it, can someone help explain it.
 
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My friend,
Each time you call the toString() on the Byte object, it creates a NEW string object. The contents ( the string "127") may be the same, but they are two distinct objects in two different locations in memory. Remember == compares the references? That is the reason it returns false.
The only exception to this rule is when strings are created using the assignment constructor. ie., String s="Hello". When you do this, the string object is created in the string pool. When you subsequently create new string objects with the same value ( "Hello") using the same assignment declaration, JVM reuses the string already present in the pool and so the reference comparison == would return true.
Ajith
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic