• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • salvin francis
  • fred rosenberger

string related question

 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
program:
class strc
{
public static void main(String args[])
{
String s1="amisha";
String s2="amisha";
if(s1==s2)
{
System.out.println("same");
}
else
{
System.out.println("different");
}
}
}

in java string is an object. so when i evaluate if(s1==s2) , the test condition is evaluated as false. because both string object refers to different memory location even if contents are same. so output of this program should be different but when i run this progarm , output is same.

please tell me how this works ?
 
Ranch Hand
Posts: 2410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you create a String literal it automatically goes into the String pool. Whenever you create another reference to the same literal it refers to the String already in the pool. A new String object is not created.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See Corey McGlone's article, "Strings, Literally."
 
author
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Create symphonies in seed and soil. For this tiny ad:
Devious Experiments for a Truly Passive Greenhouse!
https://www.kickstarter.com/projects/paulwheaton/greenhouse-1
    Bookmark Topic Watch Topic
  • New Topic