Java Tutorial

OOPS concept


Java Strings

A java string is an object of the class java.lang. Java string contains a sequence of characters.

String is immutable, means its content cannot be modified once it is created. For example, the method toUpperCase() constructs and returns a new String instead of modifying the its existing content.


String message= "How are you?";

Also String can be creared as:

char[] ch={'t','u','t','o','r','i','a','l',' ','h','e','a','p'};  
String name = new String(ch);  

This will create an string name with value tutorial heap.

If your program requires lot of modification in a string then it is better to use String Buffer or String Builder classes.

Creating String object

There are two ways to create a string object:

  • By String literal
  • By new Keyword

  • We have already seen the syntax in above two examples. Let's understand it in more detail.

    String literal

    It is created with the help of double quotes.


    String message = "Java on TutorialHeap";

    If two string literals have the same contents, they will share the same storage inside the common pool. This approach is adopted to conserve storage for frequently-used strings.

    String message = "Java on TutorialHeap";
    String message1 = "Java on TutorialHeap"; //not create new instance

    By new keyword

    When a string is created by using new keyword object is created in heap memory and the literal (value) is placed in the string constant pool.

    String message = new String("Java Tutorial on Tutorial Heap");

    Methods of String Class