In Java, String class is a sub-class of java.lang and there are available to all programs automatically. Java implements String as objects of String unlike other programming language which implements it as character arrays.
String Constructors:
- The string class can be initialized using several constructors. To create an empty string, default constructor is as follows:
String s = new String();
Above will create an instance of String with no characters in it.
- To create a String containing character sequence use below constructor:
String(char chars[ ])
For example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
In the above example a string object will be created having ‘abc’ as its value.
- String object can also be passed as constructor argument.
String(String strObj)
See below example:
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
The output from this program is as follows:
Java
Java
As you can see, s1 and s2 contain the same string.
- String class provides constructors that initialize a string when given a byte array.
String(byte asciiChars[ ])
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
}
}
This program generates the following output:
ABCDEF
- String can also be initialized using below code as well:
String s = new String(“JAVA”);
String Length:
The string length is the number of characters in contains. This value can be obtained using length() method. Its return type is int.String s = new String(“JAVA”);
System.out.println(s.length());
String Literals:
We saw that how a string can be constructed through array of characters using new keyword. Java provides simpler way to construct a string using literals. For each string literal in the program Java automatically constructs a string object.String s = “Java”;
System.out.println(s.length());

String s = "Java";
String s1 = "Java";
String s = "abodeqa";
String s1 = "abodeqa";
System.out.println( s==s1 );
String s1 = new String ("Java");

String s1 = new String("abodeqa");
String s2 = new String("abodeqa");
String s3 = "abodeqa";
System.out.println( s1==s2 ); // return false because both the object are referring to different memory locations
System.out.println( s1==s3 ); // return false because s1 is in heap and s3 is in string pool
System.out.println( s1.equalsTo ); // return true
String s = "Java";
String s1 = new String("Java");
String s2 = new String("Java").intern();
System.out.println(s==s2); // true
System.out.println(s==s1); //false
System.out.println(s1==s2); //false

Leave a Reply