What is String in java

The string is probably the most commonly used class in java library. String class is encapsulated under java.langpackage. Generally, a string is a sequence of characters. But in Java, a string is an object that represents a sequence of characters. The java.lang.String class is used to create string object.

In Java, a string is basically an object that represents a sequence of char values. An array of characters works same as java string.

For example:
1.	char[] ch={'k','a','p','i','l'}; 
2.	String s=new String(ch); 
     is same as:
1.	String s="kapil";  

What is an Immutable object?

An object whose state cannot be changed after it is created is known as an Immutable object. String, Integer, Byte, Short, Float, Double and all other wrapper class's objects are immutable.

How to create String object?

There are two ways to create String object:

1. By string literal

2. By new keyword

3. Using another String Object

4. Using + Operator

1) String Literal

String literal is a simple string enclosed in double quotes " ". A string literal is treated as a String object.

String str1 = "Hello";

Why java uses concept of string literal?

Java uses a concept of String literal because no new objects are created if it exits already in string constant pool.

2) By new keyword

1. String s=new String("Welcome");//creates two objects and one reference variable

3) Using another String object

String str2 = new String(str1);

4) Using + operator (Concatenation)

String str4 = str1 + str2;


String str5 = "hello"+"Java";

Java String Example
1.	public class StringExample{
2.	public static void main(String args[]){  
3.	String s1="java";//creating string by java string literal  
4.	char ch[]={'s','t','r','i','n','g','s'};  
5.	String s2=new String(ch);//converting char array to string 
6.	String s3=new String("example");
       //creating java string by new keyword 
7.	System.out.println(s1);  
8.	System.out.println(s2);  
9.	System.out.println(s3);  
10.	}}