Strings, I/O and formatting (Part-1)

"Hey Isla Are you serious??Strings,IO and formatting???"Hmmm..yeah I agree with you.This is basic Java.Anyway no problem we'll go further and discuss and see how much you know about Java Strings,I/O and formatting.We'll start with a little background information about strings.


  • Strings are immutable objects.(You know what I mean)
  • String is a 16-bit Unicode character
  • In java string is an object.You can create a new instance using new keyword

String myString=new String();
This creates a new string object and assign it to myString reference variable.Cool..Now we need to assign a value to the new variable.Let's do it like this.

myString="Hasitha";

And we are done.Now we have a string variable with a value.Is this the only way we can do this.Absolutely no.String class has a number of constructors.We can do the same thing as follows.


String myString=new String("Hasitha");
String myString="Hasitha";

Hmmm...Note that there are some differences between these options.We'll discuss those later.Now you know how to instantiate a string variable and assign a value to it.Okay now we'll move to the following example.


String s=myString;
We instantiated a new variable which is referring to the same myString reference.
myString=myString.replace("tha","");
System.out.print(myString+",");
System.out.println(s);

So according to you what would be the output.A simple question.Obviously it's Hasi,Hasi.Since s is referred to the same myString reference,when myString changes s should change.But you are wrong.The output is Hasi,Hasitha.WTH....!!!!. Yeah that's the beauty of immutability in Java strings.Once you created a string object it remains the same throughout the program until you re- instantiate it.So what is happening here.

  • A new String object is created in the heap with the reference myString and the value Hasitha
  • The same object is referenced by s.
  • When myString.replace invokes it creates a new object in heap and assign myString reference to that new object
  • S is still referring to the original Hasitha :p string.

The immutability of strings can illustrate further by following example.

String s="I am don";
s.replace("don","hasitha");
System.out.println(s);

As we learned this prints "I am don" in console.So that's it we have learned some interesting facts about strings in Java in this post.Let's talk more about Strings in next post.

Comments