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 a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.