Java String

Last modified on October 16th, 2014 by Joe.

String is one of the widely used java classes. It is special in java as it has some special characteristics than a usual java class. Lets explore java String in this article and this page aims to serve you as a single point reference for all your queries on Java String.

Though you might be knowing most of the things, this will help you to recall them and I am sure you will find one or two new things. I recommend you to take your time and read through this completely as java String is a basic building block of your java programs.

Immutable Java String

Java String is a immutable object. For an immutable object you cannot modify any of its attribute’s values. Once you have created a java String object it cannot be modified to some other object or a different String. References to a java String instance is mutable. There are multiple ways to make an object immutable. Simple and straight forward way is to make all the attributes of that class as final. Java String has all attributes marked as final except hash field.

Java String is final. I am not able to nail down the exact reason behind it. But my guess is, implementors of String didn’t wany anybody else to mess with String type and they wanted de-facto definition for all the behaviours of String.

We all know java String is immutable but do we know why java String is immutable? Main reason behind it is for better performance. Creating a copy of existing java String is easier as there is no need to create a new instance but can be easily created by pointing to already existing String. This saves valuable primary memory. Using String as a key for Hashtable guarantees that there will be no need for re hashing because of object change. Using java String in multithreaded environment is safe by itself and we need not take any precautionary measures.

Java String Instantiation

In continuation with above discussion of immutability of java String we shall see how that property is used for instantiating a Sting instance. JVM maintains a memory pool for String. When you create a String, first this memory pool is scanned. If the instance already exists then this new instance is mapped to the already existing instance. If not, a new java String instance is created in the memory pool.

This approach of creating a java String instance is in sync with the immutable property. When you use ‘new’ to instantiate a String, you will force JVM to store this new instance is fresh memory location thus bypassing the memory map scan. Inside a String class what you have got is a char array which holds the characters in the String you create.

Following are some of the ways to instantiate a java String

String str1 = "javapapers";
String str2 = new String("Apple");
String str3 = new String(char []);
String str4 = new String(byte []);
String str5 = new String(StringBuffer);
String str6 = new String(StringBuilder);

We have an empty constructor for String. It is odd, java String is immutable and you have an empty constructur which does nothing but create a empty String. I don’t see any use for this constructor, because after you create a String you cannot modify it.

Java String Comparison

Do not use == operator to compare java String. It compares only the object references and not its contents. If you say, “if references are same, then the value must be same” – this doesn’t cover, “even if references are not same, the content can be same”. Therefore == operator doeenot 100% guarantee the equality of java String. Consider,

String stringArray1 = new String(“apple”, “orange”);
“apple” == stringArray1[0]; gives FALSE.

“apple”.equals(stringArray1[0]); gives TRUE.

equals() method is part of Object class. Java String class overrides it and provides implementation for equality comparison. String’s equals() implemetation uses three step process to compare two java String:

  1. Compare references (if both String references are same return true else continue)
  2. Compare length (if both String length are not same return false else continue)
  3. Compare character by character sequentially.

Shall we always use equals() method for equality comparison in any type of objects? No. You need to check the implementation in its respective class. StringBuffer and StringBuilder do not have an implementation for equals() method.

Use equalsIgnoreCase(String) to compare String irrespective of case (Case insensitivity).
“javaString”.equalsIgnoreCase(“JAVASTRING”); returns TRUE.

Lexicographic Comparison of Java String

First what is lexicographic comparison? Consider, ‘A’ for ‘Apple’ and ‘B’ for ‘Ball’. Term ‘Apple’ appears first in dictionary and later follow ‘Ball’. Java String has got an excellent method to do this sort of comparison for two String and identify which comes first and the other follows.

In the above, “Apple” calls compareTo(String) and “Apple” comes first lexicograpically before “Ball”, therefore this returns value < 0. If calling String and argument String are same then returned value is 0. That is, “Apple”.compareTo(“Apple”); Else, you get > 0.

Java String Conversion

Java conversion is a huge topic by itself. I will take only String as scope for this section.

Example: 1+” Apple”; results in “1 Apple”.

So how does the above happen? When + operator is used with a java primitive, following happens:

  1. Use respective type class and convert the primitive to an object. Like 1 -> new Integer(1);
  2. Invoke toString() of that respective class.

One of the most frequent questions on String conversion is

“how do you convert java String to Date?”

Best way to convert String to Date is as follows:

String dateInString = "November 21, 2011";
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date formattedDate = dateFormat.parse(dateInString);

Java String Transformation

How to transform a String to upper / lower case. Java String has got nice utility methods.

toLowerCase(Locale locale)
toUpperCase(Locale locale)
and String can be trimmed using trim()

What is intern()

Hope you remember about the memory pool of java String that we discussed at the start of this article. We have a method named intern() in java String. When you invoke this method on a String,

  1. it checks if the same String is available in memory pool.
  2. If it exists, returns it.
  3. Else, adds this String to the memory pool and returns the String.

Java String Concatenation

+ is a special operator when it comes to java String. It helps to concatenate two String. I have already written a post exclusively for String concatenation. Please refer that for more on java String concatenation.

Comments on "Java String"

  1. Rajeev says:

    Nice Tutorial…

  2. Amit Thakur says:

    it is very nice notes about String..
    Thanks for sharing it with us.
    and hoping for the same in the future..


  3. hamid says:

    thank you so much
    very straight forward article.

  4. Praveen says:

    You are back after a long time with a good article!

  5. abdhesh says:

    this is nice tutorials.

  6. Joe says:

    Yes Praveen.

    I plan to write as often as possible, hope I keep up the promise.

  7. Dev Ghotkule says:

    Thank you so much for this information!!

  8. Anonymous says:

    it is very nice tutorial to every learner in java strings

  9. kamlesh says:

    really nice article

  10. abhishek says:

    Very nice tutorial..

  11. prakash says:

    nice blogs, i have gone through all of your topics , much helped me for interviews.

  12. Sam says:

    1. “Java String is final.”

    Immutability necessitates that a class be final or at least there should be no way to extend it(by providing private constructor & factory methods)

    2. “Shall we always use equals() method for equality comparison in any type of objects?”

    Why not? At worst if a class does not override the equals method, the equals method from Object would be used (which just compares if the two references are equals).
    The reason a class may not have overridden the equals method is if the equals method of the Object class is sufficient for it.

    Good practice would dictate that equals method be overridden for most class and “equals” method be called when comparing two objects.

    3. “It is odd, java String is immutable and you have an empty constructur which does nothing but create a empty String. I don’t see any use for this constructor, because after you create a String you cannot modify it.”

    I’m sure that empty constructor is used a lot.
    After all how many time have we done,
    String default = “”;
    Empty String would be created using the default constructor … just because we have a short cut to create strings doesn’t change the fact that Strings are real objects and the JVM needs to call a proper constructor to create it!

    Great article. It did cover a lot of good ground!

  13. Joe says:

    Hi Sam,

    Regarding using empty constructor,

    String default=””;

    yes I agree we use the above a lot. But my question is, though we are creating an empty String we are not again using the same object. Since java String is immutable, already instantiated empty String is not modified to create the new String. Thats why I told it as odd..

    People tend to think of the following as instantiating and assigning. But it is not the case w.r.t String.

    String fruit =””;
    fruit = “apple”;

    Thanks for the comment.

  14. SIDDU says:

    implementors of String didn’t wany anybody else to mess with String type and they wanted de-facto definition for all the behaviours of String.

    in this there is spelling amistake instead of want u wrote wany

  15. Darshan says:

    Hi Joe,
    I read your articles and finding it very useful to understand the actual concept.
    Could you please explain about
    hashCode() method and relation between equals() and hashCode()


  16. prakash says:

    hello joe,
    thanks for this nice blog but i have to ask
    String str1 = “javapapers”;
    String str2 = new String(“Apple”);
    what is the difference between them and when two use String str1 = “javapapers”;
    and when using new operator..

  17. murugavel says:

    really very nice blog.. keep it up.

  18. Manoj says:

    Hi joe,
    Now am the follower of your blog. I need a clear explain of hashCode(). Can you help me about that. I have read some article related to hashCode(). But still am not clear. Can you please explain with an example and output.


  19. Megha says:

    Hi joe,
    I must say that your explanation and examples are very good and easy to understand.

  20. Anonymous says:

    when we create a string object using String str1=”javapapers” jvm will create a string object in the string constant pool.when we use statement String str2=new String(“Apple”) then jvm will create a string object in the heap area.

  21. Sivaprakash says:

    Thanks for educating all.

  22. UTTPAL says:


    I likes ur blog
    I have a question in my mind.

    String s1=”HELLO”;
    String s2=”HELLO”+s1+new String(“hai”)+”RAAm”;

    String s3= s1+s2;

    Now my question is how many objects are creating above in STRING1,STRING2,STRING3


  23. Prabhat says:

    Such a very nice topic joe. Thanks for posting…..

    But i have a question, i didn’t get
    References to a java String instance is mutable.

  24. laxmi says:

    String s1=”Hi”;

    In the above statement s1 is a reference to the string object. You have not actually created the object. Already existing “Hi” string from the string pool is assigned to the reference obj rather than creating a new string object. s1 which is a reference is mutable.

    If you say
    String s2 = new String(“Hi”);
    s2 is a new string object which is immutable.

    correct me if I am wrong.

  25. Anonymous says:

    thank u very much sir..

  26. Hemant Chaudhary says:

    you are always great sir…….
    Thankx for such a nice job

  27. Anonymous says:

    Very good initiative never seen a good heart to teach and share it like this

  28. […] String class will be the undisputed champion on any day by popularity and none will deny that. This is a […]

  29. Sabyasachi says:

    In both case gives the result as equal.

    System.out.println(“— part1 —“);
    String[] strArr = {“as”, “AS”};
    if(“as” == strArr[0])
    System.out.println(“not equal”);
    System.out.println(“— part2 —“);
    String[] stringArray1 = new String[]{“apple”, “orange”};
    if(“apple” == stringArray1[0])
    System.out.println(“not equal”);

  30. chikky says:

    class StringEx
    {public static void main(String args[])
    {String s1=”hello”;
    string s2=”friend”;
    sir, the output for the program is hellofriend
    then how can we say that string is immutable bcoz as here the string is being retrived by another would you plz explain it as early as possible..

  31. chikky says:

    class StringEx
    {public static void main(String args[])
    {String s1=”hello”;
    string s2=”friend”;
    sir, the output for the program is hellofriend
    then how can we say that string is immutable bcoz as here the string is being retrived by another would you plz explain it as early as possible..

  32. […] interviewers. Sometimes we even get bored of this play with String equals. I have written a detailed tutorial on java string and its immutable property, comparing strings and conversion. This is one area where people keep on […]

  33. Avinash says:

    Hi Joe,

    Your blog is very simple to understand and so its awesome.

    I have a question here, below string from your doesn’t seem to be a valid
    String stringArray1 = new String(“apple”, “orange”);

    String[] stringArray1 = {“apple”, “orange”};
    is fine.

    did you mean the below one ?

  34. saravana says:

    String s=”abc”;

    it is possible or not,if possible mention reason if possible

  35. Rajesh says:

    Hi joe
    can you explain about why stringBuffer and stringBuilder doent override equals and hashcode methods

  36. Arsh says:

    Not possible.

  37. Arsh says:

    Hi, Here you are using String literals which are referencing to String literal pool. And contents of s1 are different so they are not referencing the same objects.
    Read about string pool if you have any doubts regarding string literals.

  38. Sharmi says:

    hello joi,
    Your blog is realy very good. Your explanation is very simple and clear. So if you dont mind plz you also post about operator overloading in java and encapsulation in java. i want to know your view for this two topics. thanks.

  39. Bijoy says:

    String s1 = new String (“hare krishna hare krishna”);
    String s2 = new String (“hare krishna hare krishna”);
    if (s1==s2) { //Only compare the Object not the Value
    } else {

    if (s1.equals(s2)) { //Only compare the Value
    } else {


  40. Bijoy says:

    really very nice post…..thanks

  41. bhushan says:

    thnx this blog is really very useful .but I have one quest i.e. if == is compares only the object references and not its contents. then when and where should use this …..waiting for your replay ……..

  42. SAMBIT says:

    Hi joe plz give some hint about that creating a new object everytime whe we create an object.

  43. swapna says:

    i have a question when we write a same method in both abstract class and interface and a class imeplents and extends both then which method will be invoked?
    interface a
    public void show();

    abstract class b
    abstract public void show();

    public class c extends b implements a
    public void show()

    public static void main(String[] args)
    c t = new c();;

  44. Anonymous says:

    i dont like ur example no one is coreect and not understandable

    so tuff not correct

  45. Anonymous says:

    its very nice.

  46. Anonymous says:

    thank you..

  47. Anwar says:

    Hi joe,
    what is difference between two Intialization given below?

    String s=”Anwar”;
    String s1=new String(“Anwar”);

  48. Krishna says:

    Hi Joe,

    Your explanations and the examples you take are very helpful.

    String stringArray1 = new String(“apple”, “orange”);

    This particular line in the above post is wrong and should be replaced by

    String[] stringArray1 = new String[]{“Apple”,”Orange”};

    Please reply if my observation is wrong.

  49. Mayur says:

    Thanks for your knowledge sharing.

  50. rakesh says:

    please create a index of all the topics in this tutorial to make navigation easy

  51. rakesh says:

    btw great tutorial

  52. Abhinav says:

    Is the object hashcode and object reference same?

  53. satish says:

    str1 is a pointing javapapers kk.first of all it checks in String Constant Pool that javapapers is not there so it create object for javapapers stored in const memory next time you writen str2=”javapapers” str2=str1;
    bcoz same string why to create object so pointing to same ref it saves physicalmemory one onebject contains 8bits

  54. Anonymous says:

    Hi Laxmi,

    String s1=”Hi”;
    => Here one object with value “Hi” is created and 1 reference s1 to refer that object is created.
    => So string object is immutable but you can use s1 to refer other object.

    String s1 = new String(“Hi”);
    => Here two objects created and one reference variable to refer “Hi”
    => So this both object are immutable but you can change reference of s1 to refer other string object.

    Hope you got your answer

  55. […] be you should also go through String equals also at this juncture as String equality is one of the celebrated topic in […]

  56. iswarya says:

    hai frd….
    String a=”hai”;
    if we write like this the value of a is gng to store into the String concatenate pool and it may or may not store into the heap memory.
    String a=new String(“hai”)’
    it is directly stores into the heap memory.
    that is the main difference in that

  57. Atmprakash says:

    nice arrticle.thanks and keep it up

  58. Naga says:

    It is a very nice post.Thanks for posting this explanation.

  59. Macs says:

    I have tested its possible please check.

  60. […] Object has a method named equals. In String class the default behavior is overridden.  The String equals behavior is modified to check if the character sequence is same as the compared one and returns […]

  61. praveen says:

    Hi joe,

    if i create a string as
    String s=new String(“Joe”);

    is “Joe” will also be created in String Constant Pool along with object in Heap.

    if so what is the use of intern() method?


  62. Derris says:

    String s1 = “hare krishna hare krishna”;
    String s2 = “hare krishna hare krishna”;
    if (s1==s2) { //Only compare the Object not the Value
    } else {

    if (s1.equals(s2)) { //Only compare the Value
    } else {
    check it out

  63. Adi says:

    Hi Joe,

    A very good article for every who intended to know more about java String,hope you post more about String classes like StringBuffer and StringBuilder

  64. Shivi says:

    can you give some idea about compareToIgnoreCase

  65. joe says:


  66. joe says:

    sorry this one for joe

  67. Srividhya says:


    To answer this question,
    For s1->1 obejct will be created,s2-> 2 objects created one is for HelloHellohaiRAAM and aonther is hai,For s3-> one more object created by concadinating both the strings.

    I guess this is correct based on my understaing, correct me if it is worng

  68. suganya says:

    Hi Joe,

    I really like your passion towards Java. Can u pls explain intern() in detail.
    When we say
    String a = “abc”;
    First it will scan the String pool if found return the string else it will add that to String pool. Correct me if Im wrong.
    I don’t understand what new thing the intern() method does here???

    Please make me clear

  69. Udit says:

    String stringArray1 = new String(“apple”, “orange”);
    “apple” == stringArray1[0]; gives FALSE

    But the above statements is giving “TRUE” as output, please verify & explain it.Thanks

Comments are closed for "Java String".