This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt about String being cannt be changed !!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "doubt about String being cannt be changed !!!" Watch "doubt about String being cannt be changed !!!" New topic

doubt about String being cannt be changed !!!

ansuman mohapatra

Joined: Mar 04, 2008
Posts: 27
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?

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

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

Cleared SCJP.....
gobburi saikrishna
Ranch Hand

Joined: Jan 21, 2008
Posts: 52
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

Joined: Mar 04, 2008
Posts: 27
thats what im trying to say. I have tried changing the value of the string.

String s = "Hello";
s = "Hello2";

Output came as

Tried that in eclipse. Please clarify.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14952

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

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: doubt about String being cannt be changed !!!
jQuery in Action, 3rd edition