String objects can be created by either using literals:
String s = "a string";
or by calling one of the constructors:
String s = new String("a string");
If we use the String literal, it’ll try to reuse already existing object from the String constant pool.
On the other hand, when instantiating a String using the constructor, a new object will be created
This constructor accepts many types of arguments and uses them to create a new String object.
Available Signatures
public String()
public String(byte[] bytes)
public String(byte[] bytes, Charset charset)
public String(byte[] bytes, int offset, int length)
public String(byte[] bytes, int offset, int length, Charset charset)
public String(byte[] bytes, int offset, int length, String charsetName)
public String(byte[] bytes, String charsetName)
public String(char[] value)
public String(char[] value, int offset, int count)
public String(int[] codePoints, int offset, int count)
public String(String original)
public String(StringBuffer buffer)
public String(StringBuilder builder)
Example
@Test
public void whenCreateStringUsingByteArray_thenCorrect() {
byte[] array = new byte[] { 97, 98, 99, 100 };
String s = new String(array);
assertEquals("abcd", s);
}