More About Strings In Java

Strings in Java are a sequence of characters, But, Are they considered as “Reference” Or “Primitive” data type?, Are they immutable?, What if i changed the value of a string?

Strings are Reference/Complex Object Type

Strings in Java fall under the category of Reference/Complex Object data types. They store a reference to the object rather than the object itself.

When you assign a string variable to another variable, It actually copies the reference to the object but not the object itself. It means, since the string variable holds the reference to the actual data, so it passes this reference and not the actual data. So, it’s pass by value!

Strings Are Immutable

Immutable means the object that the string is referencing to, can’t be changed, That’s it. The length of a String variable is set as soon as it’s initialized

String str = "abc"; 
// same as:
// char data[] = {'a', 'b', 'c'};
// String str = new String(data);
System.out.println(str); // abc

This takes us to the last question, …

What if I changed a string after initializing it?!

Since they are immutable, the string object will reference another place in the memory and the previous object will be available for the garage collector(if it’s not assigned to another string variable).

String str1 = "Java is fun!";
String str2 = str1;
str2 = "Strings are immutable"; // str2 is no longer points to "Java is fun!"
System.out.println(str1); // Java is fun!
System.out.println(str2); // Strings are immutable

Here is a more detailed demonstration on what exactly happens in the memory allocation

Strings are immutable
If you are coming from C# Language, Strings fall under reference types, and they are also immutable.
You may need to use StringBuilder Class In Java & C# instead of the String if you need mutable string variable
Show your support

Clapping shows how much you appreciated Omar El Gabry’s story.