Overloaded Constructors of the String Class in Java
The String
class provides several overloaded constructors to create string objects in different ways. Each constructor behaves differently based on the type of argument passed.
1. String()
- Creates an empty string.
String s = new String(); System.out.println("Empty String: '" + s + "'");
Output:
Empty String: ''
2. String(String original)
- Creates a new String with the same content as the original string.
String original = "Java"; String copy = new String(original); System.out.println(copy); // Java
Behavior: Creates a new string object (not the same reference as original
).
3. String(char[] value)
- Creates a string from a character array.
char[] chars = {'H', 'e', 'l', 'l', 'o'}; String s = new String(chars); System.out.println(s); // Hello
4. String(char[] value, int offset, int count)
- Creates a string from a subarray of characters.
char[] chars = {'J', 'a', 'v', 'a', 'X'}; String s = new String(chars, 1, 3); System.out.println(s); // ava
Behavior: Starts at index 1
and takes 3 characters: a
, v
, a
.
5. String(byte[] bytes)
- Creates a string from a byte array using the platform’s default charset.
byte[] bytes = {65, 66, 67}; String s = new String(bytes); System.out.println(s); // ABC
6. String(byte[] bytes, int offset, int length)
- Creates a string from a subarray of bytes.
byte[] bytes = {65, 66, 67, 68}; String s = new String(bytes, 1, 2); System.out.println(s); // BC
7. String(StringBuffer buffer)
- Creates a string from a
StringBuffer
object.
StringBuffer sb = new StringBuffer("Hello"); String s = new String(sb); System.out.println(s); // Hello
8. String(StringBuilder builder)
- Creates a string from a
StringBuilder
object.
StringBuilder sb = new StringBuilder("World"); String s = new String(sb); System.out.println(s); // World
Summary Table
Constructor | Purpose |
---|---|
String() | Creates an empty string |
String(String original) | Copy constructor |
String(char[] value) | From character array |
String(char[], int, int) | From part of char array |
String(byte[] bytes) | From byte array |
String(byte[], int, int) | From part of byte array |
String(StringBuffer) | From StringBuffer |
String(StringBuilder) | From StringBuilder |
Discuss various overloaded constructors of the String class with suitable code examples. Explain the behavior of each.