• 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

doubt in string delcaraiton

 
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
in the main function

static public void main(String[] args)
{

String a="hai";
String b="hai";
String c=new String("ram");
String d=new String("ram");
System.out.println(a==b);
System.out.println(c==d);
}
output is

true
false

why the output c==d is not returned as true ?? how does the delaration changes their natuure to == operation ??
 
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by yogesh srinivasan:
in the main function

static public void main(String[] args)
{

String a="hai";
String b="hai";
String c=new String("ram");
String d=new String("ram");
System.out.println(a==b);
System.out.println(c==d);
}
output is

true
false

why the output c==d is not returned as true ?? how does the delaration changes their natuure to == operation ??



In the first case, both references point to the same object in memory (in the string pool). This is decided at compile time to save memory.

In the second case, when constructing an object using new, a new object will always be created. Hence the references point to different objects.

Remember that "==" will compare only the reference to the object, not the contents of the object (for which you can use the equals() method).
 
Ranch Hand
Posts: 377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi yogesh,

Have a look at Strings, Literally.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic