Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.
In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string.
For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
There are two ways to create String object:
- By string literal
- By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Output
java
strings
example
String Length
The length of a string is the number of characters that it contains. To obtain this value, call the length( ) method, shown here:
int length( )
The following fragment prints “3”, since there are three characters in the string s:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());