Java String Tutorial

This entry is part 27 of 34 in the series Core Java Course

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool).

  • The String class represents character strings.
  • All string literals in Java programs, such as “abc”, are implemented as instances of this class.
  • Strings are like constants, once created its value can not be changed.
  • String objects are immutable and hence it can be shared.
  • String Buffer and String Builder can be used in place of String if lot of String Operation is to be performed.

String Creation

There are two way you can create strings in java. Both looks same but there is difference between both approach.

 

Important Aspect of String

1.Immutable

Important Method

1.intern()
2.length()
3.toString()
4.trim

String Storage

As you must be knowing, everything in java except primitives are Object. This is true for String too. String is also an Object, hence it will reside on Heap only. But there is one more term used for String storage and that is String Pool/ String Literal Pool. Most of the time people think of it as a separate pool of String Object(True for me too). But this is not true. String Pool/ String Literal Pool are nothing but a collection of references to String objects. As we know that String object is immutable it’s good to “share” the same String object with multiple references. (Vice versa is true also as String objects are shared between different references that is the reason String Objects are made Immutable.)

String Literal & Object

Strings are created in the following two formats which differ from each other in alot of ways.

  1. String Literal
  2. Using New keyword

So when we are saying String literal, we are actually referring the reference in String Pool and when we are saying String Object(Using new keyword) we are directly referring the String Object in Heap. But in both cases we are referring the Object in Heap only(Directly/ Indirectly).

How to Create

Now question arises how to create String Literal and String Object. As we know that we can create String Object in 2 ways.

String str1=”abc”;

Using new Keyword

When we are using new operator to create String, we are actually creating the String object in Heap like in First option. Here we are creating a String Object in Heap memory with value as “abc”. and a reference named “str”.
Also note that as we are using “”(literals) for creating this String Object, a literal will also be created. In total there will be 1 String Object 1 String literal and reference will be created. But reference will refer only the String object in Heap and not the literal in String pool.
And when we are using “” we are creating the literals(Everything inside “” are treated as literals). In this case(2nd scenario) JVM will look for all the references in String Pool and check if any of them pointing to String object in heap with value “abc”, if it finds any, it will return the reference of that object. Otherwise JVM will create a new String Object in Heap and interned it (Using inter() method) in String Pool(Reference for this object will be added in String Pool) for later refernce. And reference of the newly created object will be returned. Now if we again write the same code to create String literal.

String Literal

These types of strings are created in the Heap and if the String constant pool has an object with the same value, the object in the heap would be referred to that object in the String constant pool. The reference variable “str2” will be pointing to the object in the heap.

The String constant pool is a pool which stores unique string object thus enforcing the immutability i.e. even when you do concat on a previously created string, a new object is created both in the heap and the constant pool(provided there was no similar object present there before) and that object is returned accordingly to the program.

Garbage Collection for String

 You might have heard that String literals are never eligible for Garbage Collection. Note we have mentioned String literal and not String Object. There is a difference. An object is eligible for garbage collection when it is no longer referenced from an active part of the application. String literals always have a reference to them from the String Literal Pool. That means that they always have a reference to them and are, therefore, not eligible for garbage collection. But there may be some String Object which don’t have any reference then they will be eligible for garbage collection.

Cheatsheet

  • String Object is used for holding String of text.
  • Part of java.lang package.
  • Strings can be added by using concatenation Operator(+).
  • Characters use single quotes(‘ ‘) as delimiter while Strings use double quotes(” “) as delimiters.
  • String objects are immutable. Value of the string object can not be changed once assigned.
  • String class is final means method of the String class can not be overriden.
  • All String literals are added to String pool by JVM.
  • String have method length() while Array have a property length to check the length.
  • To overcome the immutable property of String StringBuffer and StringBuilder comes into picture.
Series Navigation<< String BuilderJava serialization concept and Example >>

8 Comments Java String Tutorial

  1. subas kumar tosh

    Develope a programme, read password from keyboard,find is it in the below pattern or not

    1>should have one upper case character,one digit,one special character.
    2>it’s length should be between 8,16

    Reply
  2. anjum

    i am a life science student and i dont have idea of any of the computer languages and now i want to learn java…….so how can i learn that from the above…..i even dont know what is loop,array,strings and coding in java….and i want to learn this all bloody java at any cost……

    Reply
    1. J Singh

      Hi Anjum,

      As you don’t have any basic knowledge i would suggest you to take help from teacher as you cant understand everything online.

      Regards

      Reply
    1. jagggu

      public class Hi {

      public static void main(String[] args) {
      String a=”TAMILNADU”;
      int i;
      for(i=0;i<a.length();i++)
      {
      System.out.print(a.charAt(i));
      }
      System.out.print(" ");
      }

      }
      output:
      T A M I L N A D U
      if u want" TAMIL NADU"
      use the method index and mention the length(where u want to give the space ),use your own style…….

      Reply

Leave A Comment

Your email address will not be published. Required fields are marked *