String class supports different types of constructors. Lets see the different types of constructors with example.
Default constructor
1 |
String str= new String(); |
The above will create an instance of string without any characters.
String object with character array as parameters
If you want to create String with initial values , We have variety of constructors
String (char chars[]))
We can also specify sub range of character array for initializing string .
String (char chars[],int startIndex,int numberOfCharacters)
Example:
1 2 3 4 5 6 7 8 9 10 |
package com.j2eereference.coreJava; public class StringConstructors { public static void main(String[] args) { char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; String str1 = new String(chars); String str2 = new String(chars, 2, 3); System.out.println(str1); System.out.println(str2); } } |
output
abcdef
cde
String object from another string object
We can create string object from another String object as below.
1 2 3 4 5 6 7 8 9 |
package com.j2eereference.coreJava; public class StringConstructors { public static void main(String[] args) { String str1 = new String("j2eereference"); String str2 = new String(str1); System.out.println(str1); System.out.println(str2); } } |
Output
j2eereference
j2eereference
String constructor with byte array
We can create String object from byte array as below.
String(byte asciiChars[])
and
String(byte asciiChars[],int startIndex,int numberOfCharacters)
1 2 3 4 5 6 7 8 9 10 |
package com.j2eereference.coreJava; public class StringConstructors { public static void main(String[] args) { byte ascii[] = { 65, 66, 67, 68, 69, 70 }; String str1 = new String(ascii); String str2 = new String(ascii, 2, 3); System.out.println(str1); System.out.println(str2); } } |
output
ABCDEF
CDE
String constructor with Unicode
Java 1.5 supports Unicode character set as argument in string constructor.
String(int codePoints[],int startIndex,int numberOfCharacters)
Here codePoints is the array contains Unicode points
String constructor with StringBuilder
Java 1.5 supports string constructors with StringBuilder parameter.
String(StringBuilder strBuilder)
1 2 3 4 5 6 7 8 |
package com.j2eereference.coreJava; public class StringConstructors { public static void main(String[] args) { StringBuilder strBuilder = new StringBuilder("j2eereference"); String str = new String(strBuilder); System.out.println(str); } } |
output
j2eereference
Hemant says
July 17, 2012 at 6:24 pmReally, I impressed by this site. I saw many java sites but this is one of the best site.
This is simple and full of knowledge.
ravi krishnarpan says
July 20, 2012 at 6:18 pmThis site is simply the best !Thanks for imparting this kind of knowledge in simple but sublime
language .