• 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

String objects

 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Here is a question about String objects..
The statement ...
String s = "Hello" + "Java";
yields the same value for s as ...
String s = "Hello";
String s2= "Java";
s.concat( s2 );
1.True
2.False
The answer given is False.
I think it should be true. Because although String objects are immutable, the final object pointed to by reference s is the same --> HelloJava.
I tried running this and it says false (s.equals(new s)).
How come? Where am I going wrong?
Regards,
Kapil
 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi kapil
when u say s="Hello"+"Java";
the "HelloJava" is assogned to s;
where as s.concat(s2) return a concated new String ,which should be assigned to some String type var.
here concatitation is done what value is not assigned to anything.
if u say System.out.println(s.concat( s2 ))then it will show HelloJava
right
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Kapil, adding to what Pawan said, if you have assigned
s.concat(s2) to s ( s = s.concat(s2)), System.out.println(s), would then display "HelloJava".
 
kapil apshankar
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks!
Got it!
Regards,
Kapil
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The result of concatenation is a new string object
say
String s1 = "Hello"+"World"
String s= "Hello" ;
String s2 = "World" ;
s.concat(s2);
** After this the value of s remains "Hello' only.
so s1.equals(s) returns false.

However s1.equals(s.concat(s2) returns true.
Hope it helps
Ravi
reply
    Bookmark Topic Watch Topic
  • New Topic