• 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
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Ganesh Patekar

String objects

 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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
  • Quote
  • Report post to moderator
Thanks!
Got it!
Regards,
Kapil
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • 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
 
Yup, yup, yup. Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!