String Class Constructors in Java

By: Daniel Malcolm Emailed: 1768 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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

String s = new String();

will create an instance of String with no characters in it. Frequently, you will want to create strings that have initial values. The String class provides a variety of constructors to handle this. To create a String initialized by an array of characters, use the constructor shown here:

String(char chars[ ])

Here is an example:

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

This constructor initializes s with the string "abc".

You can specify a subrange of a character array as an initializer using the following constructor:

String(char chars[ ], int startIndex, int numChars)

Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use. Here is an example:

char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);

This initializes s with the characters cde.

You can construct a String object that contains the same character sequence as another String object using this constructor:

String(String strObj)

Here, strObj is a String object. Consider this example:

// 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 is as follows:

Java
Java

As you can see, s1 and s2 contain the same string. 

Even though Java's char type uses 16 bits to represent the Unicode character set, the typical format for strings on the Internet uses arrays of 8-bit bytes constructed from the ASCII character set. Because 8-bit ASCII strings are common, the String class provides constructors that initialize a string when given a byte array. Their forms are shown here:

String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)

Here, asciiChars specifies the array of bytes. The second form allows you to specify a subrange. In each of these constructors, the byte-to-character conversion is done by using the default character encoding of the platform. The following program illustrates these constructors:

// 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

Extended versions of the byte-to-string constructors are also defined in which you can specify the character encoding that determines how bytes are converted to characters. However, most of the time, you will want to use the default encoding provided by the platform.

Note: The contents of the array are copied whenever you create a String object from an array. If you modify the contents of the array after you have created the string, theString will be unchanged.

Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(2)


1. View Comment

Thanks....

View Tutorial          By: A.V. Bajaj at 2012-06-02 09:40:16
2. View Comment

S.N. Constructor & Description
1 String()
This initializes a newly created String object so that it represents an empty character sequence.
2 String(byte[] bytes)
This constructs a new String by decoding the specified array of bytes using the platform's default charset.
3 String(byte[] bytes, Charset charset)
This constructs a new String by decoding the specified array of bytes using the specified charset.
4 String(byte[] bytes, int offset, int length)
This constructs a new String by decoding the specified subarray of bytes using the platform's default charset
5 String(byte[] bytes, int offset, int length, Charset charset)
This constructs a new String by decoding the specified subarray of bytes using the specified charset.
6 String(byte[] bytes, int offset, int length, String charsetName)
This constructs a new String by decoding the specified subarray of bytes using the specified charset.
7 String(byte[] bytes, String charsetName)
This constructs a new String by decoding the specified array of bytes using the specified charset.
8 String(char[] value)
This allocates a new String so that it represents the sequence of characters currently contained in the character array argument.
9 String(char[] value, int offset, int count)
This allocates a new String that contains characters from a subarray of the character array argument.
10 String(int[] codePoints, int offset, int count)
This allocates a new String that contains characters from a subarray of the Unicode code point array argument.
11 String(String original)
This initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.
12 String(StringBuffer buffer)
This allocates a new string that contains the sequence of characters currently contained in the string buffer argument.
13 String(StringBuilder builder)
This allocates a new string that contains the sequence of characters currently contained in the string builder argument.


View Tutorial          By: Jameesh at 2015-03-05 07:09:38

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Daniel Malcolm
javac options in Java
Operator Precedence in Java
Calling Multiple Listeners in JSF
Using free() Function in C
ForwardAction in Struts
Listing Files and Directories sample program in C
Binary Tree - (Self-referential Structures) example program in C
A simple program using EL in JSP
Command-line Arguments in C
Example Calculator program in C - describing use of External Variables in C
Assignment Operators and Expressions in C
The for statement in C
JSF Basics
assert() Versus Exceptions in C++
RMS Basics in J2ME

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
InetAddress Example program in Java
Read from a COM port using Java program
Stack example in Java - push(), pop(), empty(), search()
How to use ArrayList in Java
Using StringTokenizer in Java
The Basic Structure of a Simple Java program
FileReader and FileWriter example program in Java
Transient vs Volatile modifiers in Java
Vector example in Java
Method Overriding in Java
Method Overloading (function overloading) in Java
instanceof sample program in Java
append() in Java
Student marks calculation program in Java
Reading from a file and writing to a file using Java program
Most Emailed Articles (in Java)
Text to Speech conversion program in Java
inheritance in Java
How to initialize an Array and how to copy the array
Using Charts in JasperReports
What is Unicode?
Operator Precedence in Java
Of Object, equals (), == and hashCode ()
DateFormat sample program in Java
A Simple whois program in Java
CharArrayReader example program in Java
ByteArrayOutputStream - sample program in Java
Vector example in Java
Arrays example in Java - asList(), binarySearch(), fill(), sort(), equals()
HashSet Sample program in Java
Disadvantages of using Native methods in Java