String Constructor in Java

String Constructor in Java: The String Constructor plays an important role in creating and initializing String objects. Strings are fundamental data types used to represent sequences of characters, and they are widely used in Java applications for various purposes, from storing text to manipulating data.

Java provides a number of constructors for the String class, each designed to fulfill specific requirements when creating String objects. These constructors offer flexibility and versatility in handling character sequences, byte arrays, and even StringBuilder and StringBuffer objects.

Every Java developer should have proper knowledge about String Constructor in Java because it empowers them to manipulate and manage textual data efficiently. This discussion will discuss different String constructors available in Java, exploring their functionalities and use cases and equipping you with the knowledge to leverage them effectively in your Java programming language.

String Constructor in Java

Here, we have mentioned some of the most commonly used constructors of the string class, and those are:

ConstructorDescription
String()creates an empty string. It’s mostly useless because String is immutable.
String(String original)creates a string object from another string. Since String is immutable, it’s of no use.
String(byte[] bytes)constructs a new string from the byte array using the system’s default encoding.
String(byte bytes[], String charsetName)uses the specified character encoding. If the encoding is not supported, UnsupportedEncodingException is thrown.
String(byte bytes[], Charset charset)a better way to specify an encoding for constructing the string object.
String(byte bytes[], int offset, int length)It’s similar to the above constructor, except we must specify the encoding.
String(byte bytes[], int offset, int length, Charset charset)Similar to above, except that the character set encoding name is passed as a string. This will throw UnsupportedEncodingException if the encoding is not supported.
String(byte bytes[], int offset, int length, String charsetName)creates a string from the input Unicode code points array. It throws an IllegalArgumentException if any of the code points are invalid. This constructor throws IndexOutOfBoundsException if the offset is negative, the length is negative, or the offset is greater than codePoints.length – length.
String(char value[])creates the string object from the character array.
String(char value[], int offset, int count)The offset specifies the index of the first character. The length specifies the number of characters to use. This constructor throws IndexOutOfBoundsException if offset is negative, length is negative, or offset is greater than value.length – length.
String(int[] codePoints, int offset, int count)creates a new string from the contents of the string buffer. This constructor internally calls the StringBuffer toString() method.
String(StringBuffer buffer)creates a string from the input Unicode code points array. It throws an IllegalArgumentException if any of the code points are invalid. This constructor throws IndexOutOfBoundsException if the offset is negative, the length is negative, or the offset is greater than codePoints.length – length.
String(StringBuilder buffer)creates a new string from the contents of the string builder.

String Constructors Examples

String Constructor Examples illustrate the versatility of Java’s String class in creating and manipulating strings. These examples showcase how developers can instantiate strings using different constructors to suit specific needs.

From constructing empty strings to copying existing ones, decoding byte arrays into text, or extracting portions of character sequences, these examples provide a comprehensive understanding of how to harness the power of Java’s String constructors.

Whether working with character arrays, byte data, or other string-related operations, these examples serve as valuable tools for developers seeking to efficiently manage textual data in their Java applications.

Let’s try to understand each of the above constructors one by one with examples:

String()

This constructor creates an empty string. We also called this the default constructor and the syntax for this is:

String emptyString = new String();

String(String original)

This constructor creates a new string object in the heap area containing the same character sequence as the original string.

String original = "SoftwareTestingo";
String copiedString = new String(original);

String(byte[] bytes)

This constructor creates a new string object by decoding the given byte array using the platform’s default character set(i.e., by decoding ASCII values into the characters). Let’s take an example to understand how this constructor works:

public class ByteArrayConstructor 
{
	public static void main(String[] args) 
	{
		/*Range of bytes: -128 to 127. These byte values will be 
		converted into corresponding characters.*/

		byte byteArray[] = { 65, 66, 67, 68 };
		String str = new String(byteArray); 
		System.out.println("The String is : "+str); 
	}
}

Output:

The String is : ABCD

String(byte bytes[], String charsetName)

This constructor decodes an array of bytes into a string using the specified character set. Here is an example:

import java.io.UnsupportedEncodingException;
public class ByteArrayConstructor 
{
	public static void main(String[] args) throws UnsupportedEncodingException 
	{
		/*Range of bytes: -128 to 127. These byte values will be 
		converted into corresponding characters.*/

		// Corresponds to "Hello"
		byte[] bytes = {72, 101, 108, 108, 111}; 
		String decodedString = new String(bytes, "UTF-8");
		System.out.println("The String: "+decodedString);
	}
}

String(byte bytes[], Charset charset)

This constructor decodes an array of bytes into a string using the specified Charset.

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
public class ByteArrayConstructor 
{
	public static void main(String[] args) throws UnsupportedEncodingException 
	{
		/*Range of bytes: -128 to 127. These byte values will be 
		converted into corresponding characters.*/

		// Corresponds to "Hello"
		byte[] bytes = {72, 101, 108, 108, 111}; 
		Charset utf8 = Charset.forName("UTF-8");
		String decodedString = new String(bytes, utf8);
		System.out.println("The String Is: "+decodedString);
	}
}

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

This constructor decodes a portion of an array of bytes into a string using the platform’s default character set.

import java.io.UnsupportedEncodingException;
public class ByteArrayConstructor 
{
	public static void main(String[] args) throws UnsupportedEncodingException 
	{
		/*Range of bytes: -128 to 127. These byte values will be 
		converted into corresponding characters.*/

		// Corresponds to "Hello"
		byte[] bytes = {72, 101, 108, 108, 111};
		String decodedString = new String(bytes, 1, 3); 
		// Output "ell"
		System.out.println("The String Is: "+decodedString);
	}
}

String(byte bytes[], int offset, int length, Charset charset)

This constructor decodes a portion of an array of bytes into a string using the specified Charset.

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
public class ByteArrayConstructor 
{
	public static void main(String[] args) throws UnsupportedEncodingException 
	{
		/*Range of bytes: -128 to 127. These byte values will be 
		converted into corresponding characters.*/

		// Corresponds to "Hello"
		byte[] bytes = {72, 101, 108, 108, 111};
		Charset utf8 = Charset.forName("UTF-8");
		String decodedString = new String(bytes, 1, 3, utf8);
		// Output "ell"
		System.out.println("The String Is: "+decodedString);
	}
}

String(byte bytes[], int offset, int length, String charsetName)

This constructor decodes a portion of an array of bytes into a string using the specified character set.

import java.io.UnsupportedEncodingException;
public class ByteArrayConstructor 
{
	public static void main(String[] args) throws UnsupportedEncodingException 
	{
		/*Range of bytes: -128 to 127. These byte values will be 
		converted into corresponding characters.*/

		// Corresponds to "Hello"
		byte[] bytes = {72, 101, 108, 108, 111};
		String decodedString = new String(bytes, 1, 3, "UTF-8");
		// Output "ell"
		System.out.println("The String Is: "+decodedString);
	}
}

String(char value[])

This constructor creates a new string with the same character sequence as the provided character array.

public class ByteArrayConstructor 
{
	public static void main(String[] args)
	{
		/*Range of bytes: -128 to 127. These byte values will be 
		converted into corresponding characters.*/

		char[] charArray = {'H', 'e', 'l', 'l', 'o'};
		String str = new String(charArray);
		System.out.println("The String Is: "+str);
	}
}

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

This constructor creates a new string with a portion of the provided character array.

public class ByteArrayConstructor 
{
	public static void main(String[] args)
	{
		/*Range of bytes: -128 to 127. These byte values will be 
		converted into corresponding characters.*/

		char[] charArray = {'H', 'e', 'l', 'l', 'o'};
		String str = new String(charArray, 1, 3); 
		// Creates "ell"
		System.out.println("The String is: "+str);
	}
}

String(int[] codePoints, int offset, int count)

This constructor creates a new string from a subarray of code points.

public class ByteArrayConstructor 
{
	public static void main(String[] args)
	{
		/*Range of bytes: -128 to 127. These byte values will be 
		converted into corresponding characters.*/

		// Corresponds to "Hello"
		int[] codePoints = {72, 101, 108, 108, 111}; 
		// Creates "ell"
		String str = new String(codePoints, 1, 3);
		
		System.out.println("The String Is: "+str);
	}
}

String(StringBuffer buffer)

This constructor creates a new string with the same character sequence as the contents of the specified StringBuffer.

public class ByteArrayConstructor 
{
	public static void main(String[] args)
	{
		StringBuffer stringBuffer = new StringBuffer("Hello, World!");
		String str = new String(stringBuffer);
		
		System.out.println("The String Is: "+str);
	}
}

String(StringBuilder buffer)

This constructor creates a new string with the same character sequence as the contents of the specified StringBuilder.

public class ByteArrayConstructor 
{
	public static void main(String[] args)
	{
		StringBuilder stringBuilder = new StringBuilder("Hello, World!");
		String str = new String(stringBuilder);

		System.out.println("The String Is: "+str);
	}
}

Depending on your specific needs, these constructors provide various ways to create and manipulate strings in Java.

Conclusion:

We’ve explored the diverse array of String constructors in Java, each serving a unique purpose in string manipulation. Understanding these constructors is essential for Java developers to work with textual data efficiently.

If you have any doubts or require further clarification regarding the “String Constructor in Java,” please don’t hesitate to comment below. Your questions are valuable, and we’re here to assist.

Moreover, we welcome your suggestions on enhancing this article or covering related topics in more detail. Your feedback helps us provide content that better serves your needs. Please feel free to share your insights and suggestions in the comment section. Thank you for engaging with our content, and we look forward to your valuable input!

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment