Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • 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
  • Liutauras Vilda
  • Bear Bibeault
  • Junilu Lacar
  • Martin Vashko
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Scott Selikoff
  • salvin francis
  • Piet Souris

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
 
If I had asked people what they wanted, they would have said faster horses - Ford. Tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!