The String Constructors in Java

The String class supports several constructors. To create an empty String, we call the default constructor

String s = new String();

Example

char chars[] = { ‘a’, ‘b’, ‘c’ };
String s = new String(chars);

This constructor initializes s with the string “abc”

Construct one String from another

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

Java
Java

Construct string from subset of char array

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);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}

This program generates the following output

ABCDEF
CDE

Leave a Comment