Monday, 15 June 2015

Java String Constructors

The class String supports many constructors to create String objects. The simplest way to

construct a string is to assign a literal value to a String type variable:

String str = "This is a string";

The above statement will create a string object with the specified contents.

Some of the commonly used constructors are described below:

String()


Initializes a newly created String object so that it represents an empty character sequence:

String str = new String();

String (String str)

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.

Examples:

String str = new String("This is a string");

String str1 = new String(str);

The string str1 is a copy of string str. Although contents are same but str and str1 point to different string objects.

String(char[] value)

Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.

Example: String str in the following example will hold “abc”.

char cr[] = { ‘a’,’b’,’c’};

            String str = new String (cr);

String(char value[], int offset, int count)

Allocates a new String that contains characters from a sub-array of the character array argument.

Example: String str in the following example will hold “cde”.

char cr[] = { ‘a’,’b’,’c’,’d’,’e’,’f’ };

            String s = new String (cr,2,3);

String(byte b[])

Constructs a new String by decoding the specified array of bytes using the platform's default charset.

String(byte[]  b, int offset, int length)

Constructs a new String by decoding the specified subarray of bytes using the platform's default charset.

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. In each of the above constructors the byte to character
conversion is done by using the default character encoding of the platform.

Example: The following example illustrates the use of the constructors, which convert byte array into string.

class SubStringCons

{ public static void main(String args[])

{ byte ascii[] = { 65,66,67,68,69,70 };

String s = new String (ascii);

System.out.println(s);

String s1 = new String (ascii, 2, 3);

System.out.println(s1);

}

}

Output:

ABCDEF

CDE

No comments:

Post a Comment