• 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

doubt about String being cannt be changed !!!

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You have created two strings containing names. Thus

String fname="John";
String lname="String"

How can you go about changing these strings to take new values within the same block of code?

1)
fname="Fred";
lname="Jones";
2)
String fname=new String("Fred");
String lname=new String("Jones");

3)
StringBuffer fname=new StringBuffer(fname);
StringBuffer lname=new StringBuffer(lname);


4) None of the above

I think the answer will be first one. Since once string is created we can change its value. I have checked it in eclipse.

But I got the answer as 4 none of the above since string cant be changed once created or assigned a value.

Please clarify
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes answer is 4, because String are immutable, we can't change Strings,
but we can change StringBuffer And StringBuilder which are Mutable
 
ansuman mohapatra
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thats what im trying to say. I have tried changing the value of the string.

String s = "Hello";
System.out.println(s);
s = "Hello2";
System.out.println(s);

Output came as
Hello
Hello2

Tried that in eclipse. Please clarify.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You are not changing the value of the String object, you are only making the variable s refer to another String object.

In Java, variables are not objects themselves - they are only references to objects that are stored on the heap. For more information on how variables work in Java, see this JavaRanch Campfire story: Cup Size -- a story about variables
reply
    Bookmark Topic Watch Topic
  • New Topic