• 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

Question on strings

 
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Ranchers,

Need your help on strings.
1. String s ="abc"
2.String b ="abc"
3. String c = new String("abc")

Whta is difference between all three .
If i do(s==b) it gives true. How come that, it shuld give false bcoz two objects of string has been created. They are pointing to different addresses in memory with same value.

Can someone explain me.
 
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
this question needs to in the FAQ or something.

String objects are immutable, at the same time however you have a string pool in the heap where string objects are stored (to save memory)

so if you save

a= "car";
b= "car;

a and b are pointing to the same object in the pool so they are pointing to the same area.

SO they are equal using (==)
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Ali Khalfan:
this question needs to in the FAQ or something...


It is. SCJP FAQ: How many String objects are there? What is the String pool?

The answer provides a link to the article, Strings, Literally, which should explain this situation.
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you compare String s and b by if(s==b),two differnt objects are not created but two diffent rferences pointing to the same objects are created. Thats why it is showing TRUE.

Have you chaecked using .equals()?
 
reply
    Bookmark Topic Watch Topic
  • New Topic