• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

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.
 
today's feeble attempt to support the empire
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic