aspose file tools
The moose likes Java in General and the fly likes What is there in Sting class that is not in String Buffer due to which we are seeing immutability.? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "What is there in Sting class that is not in String Buffer due to which we are seeing immutability.?" Watch "What is there in Sting class that is not in String Buffer due to which we are seeing immutability.?" New topic
Author

What is there in Sting class that is not in String Buffer due to which we are seeing immutability.?

Himanshu Bhatnagar
Greenhorn

Joined: Sep 27, 2011
Posts: 9
How have sun made String immutable.Even string buffer and sting builder are final classes ,but they are mutable through final key word the sting has become un-extendable not immutable.Its not an sufficient condition

Say in a code i do this

String s= "Hello";
s=s+"Bill";

Here "Hello Bill" will be a new object , as string is immutable .What in the string class actually triggered it, to make this new object .?
What is there in sting class that is not in string Buffer due to which we are seeing immutability in only String and wrapper classes.
For Reference i have attached String.java and StringBuffer.java
Jesper de Jong
Java Cowboy
Bartender

Joined: Aug 16, 2005
Posts: 12953
    
    3

Welcome to the Ranch.

The fact that String, StringBuffer and StringBuilder are final is not enough to make them immutable.

Immutable means that once an instance of a class is created, there is no way to change the value of the member variables of the class. Class String simply doesn't have any methods that let you change the content of the string, so it is immutable.

Strings are actually a special class in Java; the language has special syntax for handling strings.

When you do this:

The compiler will automatically translate that into something like this behind the scenes:

You can see that by compiling a small test program and then decompiling it with the javap tool that's included with the JDK.

So, there is nothing in the String class that causes a new object to be created; this happens because Java has special syntax for concatenating strings with the + operator, which actually gets converted by the compiler to something that uses a StringBuilder.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Himanshu Bhatnagar
Greenhorn

Joined: Sep 27, 2011
Posts: 9
Thanks A lot....!!! that really helped...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What is there in Sting class that is not in String Buffer due to which we are seeing immutability.?
 
Similar Threads
String object creation
Math class immutable
How to make class immutable ?
How to create user defined immutable class
String Immutable