views:

194

answers:

6

I've read that in Java an object of type String can't change. But int and char variables can. Why is it? Can you give me an example?

Thank you. (I am a newer -_- )

+5  A: 

int and char can't change either. As with strings, you can put a different value into the same variable, but an integer itself doesn't change. 3 will always be 3; you can't modify it to be 4.

itowlson
+2  A: 

I'm not sure that it is possible to show (by example) that Strings cannot change. But you can confirm this by reading the description section of Javadoc for the String class, then reading the methods section and noting that there are no methods that can change a String.

EDIT: There are many reasons why Strings are designed to be immutable in Java. The most important reason is that immutable Strings are easier to use correctly than mutable ones. And if you do need the mutable equivalent of a String for some reason, you can use the StringBuilder (or StringBuffer) class.

Stephen C
+7  A: 

As bzabhi said, strings are immutable in Java. This means that a string object will never change. This does not mean you can not change string variables, just that you cannot change the underlying memory representation of the string. for an example:

String str = "Hello";
str += " World!";

Following the execution of these lines, str will point to a new string in memory. The original "Hello" string still exists in memory, but most likely it will not be there for long. Assuming that there are no extenuating circumstances, nothing will be pointing at the original string, so it will be garbage collected.

I guess the best way to put this would be to say that when line 2 of the example executes, a new string in memory is created from the concatenation of the original string and the string being added to it. The str variable, which is just a reference to a memory location, is then changed to point at the new variable that was just created.

I am not particularly knowledgeable on the point, but, as I understand it, this is what happens with all "non-primitive" values. Anything that at some point derives from Object follows these rules. Primitive values, such as ints, bools, chars, floats and doubles allow the actual value in memory to be changed. So, from this:

int num = 5;
num += 2;

the actual value in memory changes. Rather than creating a new object and changing the reference, this code sample will simply change the value in memory for the num variable.

As for why this is true, it is simply a design decision by the makers of Java. I'm sure someone will comment on why this was made, but that isn't something I know.

Seburdis
*Why?* I'm just guessing here, but it's probably because if you were to extend a string you'd have to re-allocate memory anyway. The chars are stored contiguously, and the following char might not be available for use, so it just reallocates a new chunk of memory either way.
Mark
i.e. -- it's just more efficient this way (in most cases). Unless you want to allocate huge strings only for potential use. But that's what StringBuffer is for...
Mark
(I'd compare `int` to `Integer` - they behave in very similar ways. `AtomicInteger` and `StringBuilder`, for instance, behave quite differently from `Integer`/`int` and `String`.)
Tom Hawtin - tackline
Why? Imagine having to explicitly make a copy every time it is used as an argument or returned. C++ copies implicitly. Although what gets copied depends on type of type. Java goes for an easier model (at least easier for programmers, not implementors of high performance implementations).
Tom Hawtin - tackline
+1  A: 

This little article can probably explain it better than I can: http://www.jchq.net/tutorial/09%5F02Tut.htm

Mark
+3  A: 

String is an immutable type (the value inside of it cannot change). The same is true for all primitive types (boolean, byte, char, short, int, long, float, and double).

int    x;
String s;

x = 1;
x = 2;
s = "hello";
s = "world";
x++; // x = x + 1;
x--; // x = x - 1;

As you can see, in no case can you alter the constant value (1, 2, "hello", "world") but you can alter where they are pointing (if you warp your mind a bit and say that an int variable points at a constant int value).

TofuBeer
+2  A: 

It's also worthwhile to note that since strings are immutable, that if they are passed into a method, they can't be modified inside of the method and then have those changes seen outside of the method scope.

public void changeIt(String s) {
    // I can't do anything to s here that changes the value 
    // original string object passed into this method
} 

public void changeIt(SomeObject o) {
    // if SomeObject is mutable, I can do things to it that will 
    // be visible outside of this method call
}
Jeremy Raymond