3

I have a question concerning establishing String objects in Java.

Let's say I create a String object like this:

String mystring=new String();

Now, if I take this String object and assign to it a string like this:

mystring="abc";

What exactly happened here? Is mystring addressed exactly to the original object or is it a different object? Like String mystring; is the short-hand for String mystring=new String(); what could mystring="abc"; stand for?

Alex Wittig
  • 2,800
  • 1
  • 33
  • 42
user3133542
  • 1,695
  • 4
  • 21
  • 42
  • In Java `String mystring;` is **not** a short-term for `String mystring = new String();`. It's just a declaration of variable without any assigment, not even `null`. You can't do anything with such a thing except for assigning a value for it. – Crozin Dec 24 '13 at 23:45

2 Answers2

3
String mystring = new String();

creates a new String object and assigns the value of its reference to the variable mystring.

So

Variable                       Heap
--------                       ----    
mytring --------------------->  "" // an empty String object

Then you do

mystring="abc";

This assigns the value of the reference to the String object "abc" to the variable mystring. So

Variable                       Heap
--------                       ----    
mystring ------------------->  "abc"   
                                "" // will be garbage collected at some point

A variable does not change. The object it's referencing or the reference itself can change.

Like String mystring; is the short-term for String mystring=new String();

No String mystring; is a variable declaration. When that line is executed, the variable mystring is declared but not initialized.

On the other hand, String mystring = new String() both declares and initializes the variable mystring.

for what could mystring="abc"; stand for?

That is an assignment expression, assigning the value of the reference to the String object "abc" to the variable mystring.

It's also important to understand that Strings are immutable. Once you create a String object, you cannot change it. For example, in the following code

String name = "user3133542"; // cool
name = "some other value";

You are not changing the object that name is referencing, you are creating a new object and assigning its value to the variable name.

The String API does not provide any methods to change its value. We therefore call it immutable.

Consider going through the Java String tutorial.

Also, before you ask your next question, read this

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 1
    Could you also point out that strings are immutable, and that changing the value of mystring will create a new object? – DOK Dec 24 '13 at 23:46
0

You are changing mystring with mystring="abc"; It is not the exactly to the original object at all. The mystring is a variable not object.

fastcodejava
  • 39,895
  • 28
  • 133
  • 186