• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

I am Confused !!!!! Pls Help

 
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class StringTest {
public static void main(String[] args) {
String s1 = "abc";
String s2 = "ab";
s2 = s2 + "c";
System.out.println(s1 == s2); // false
System.out.println(s1 == (s2.intern())); // true
}
}

Hi Great Ranchers ... I am a bit confused ... .... ..... Please explain the above output ....

Thanks Regards
 
Ranch Hand
Posts: 171
Flex Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

In line 1 one String object is getting created in the string constant pool( if "abc" does not already exist in String constant pool) and a reference variable s1 will refer to it.In line 2 also one String object is getting created in the string constant pool( if "ab" does not already exist in String constant pool) and a reference variable s2 will refer to it.In line 3 a new String object "abc" is getting created,as s2
in not a compile time constant.s1 and s2 do not refer to same String object.
s1==s2 is false as both s1 and s2 are refering to different objects. s1 to an object in the pool memory and s2 to an object in normal (non-pool) memory.
The intern() method is invoked on s2 and as the pool already contains a string equal to "abc",now s2 refer to the object in the pool memory.
Thus s1==s2.intern() is true.
[ December 19, 2008: Message edited by: Daisy Lakhanpal ]
 
Willie Smits increased rainfall 25% in three years by planting trees. Tiny ad:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic