Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java- creating a String object but assigning otherwise afterwards

Tags:

java

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?

like image 777
user3133542 Avatar asked Apr 07 '26 06:04

user3133542


1 Answers

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

  • How do I compare strings in Java?
like image 154
Sotirios Delimanolis Avatar answered Apr 21 '26 03:04

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!