Java String


In Java language, a String is a sequence of characters. Java implements strings as an object of type string.

Example:-

char ch[]={'p','r','o','g','r','a','m','t','p','o','i','n','t'};
String s=new String(ch);  
or
String s="programtpoint"; 

When a string object has been created, you can't change the characters that consist of that string.

String objects are stored in java heap memory which is called as the String pool.

The String is immutable which means string instance cannot be changed after it has been created. When you want to modify a string use StringBuffer. The StringBuffer is mutable.

The String and StringBuffer classes are defined in java.lang.string class.


To Create a String Object

There are two steps to create a String object:

  • By string literal
  • By new keyword

By String Literal

Java automatically constructs a string object so, you can use a string literal to initialize a string object.

The JVM always checks the string pool, when you create a string literal. In string pool, the string already exists the reference of an instance is returned. if it does not exist then new string instance is created.

String s="welcome to onlinetpoint";  //  string literal 

By new Keyword

 String s=new String("Welcome");

Example:-

public class String
{  
    public static void main(String []args) {      
		String s="welcome to ";
        String s1=new String("onlinetpoint");
        System.out.println(s+s1);
    }
}  



Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.