Skip to content

Creating String Objects

Estimated time to read: 1 minute

Overview

There are various constructors to create a String object, however, Java provides a standard constructor.

Since Strings are so common in programming, Java offers a simplified method for creating Strings.

Anything enclosed in quotes " " is converted to a String reference and object by Java. (If it didn't do the above, we would have to create a byte array, place the individual bytes and then pass that to the string)

String nameString = new String("Pete");
String companion = nameString.substring(0,3);
// companion is set to "pet"

String upper = newString.toUpperCase();
// upper is set to "PETE"

int size = nameString.length(); // size is set to 4
int anotherSize = "BryanTheHappyMinnow".length(); // anotherSize is set to 19

Anonymous String Objects

System.out.println("Hello World!");

The statement above takes the String literal with the contents of "Hello World" and the creates a String object from it with the same contents.

This is an anonymous string. There is no direct way to work with this string, it is ephemeral as it is passed directly into System.out.println.

String Concatenation

Strings can be chained together with a plus sign

String firstName = "Chris";
String lastName = "Wells";
String fullName = firstName + " " + lastName;

The plus sign has to different meanings: one for addition and one for concatenation. Java decides what to do based on the data types of the operands. It will automatically box and unbox as required.

Overuse of concatenation can build large number as String objects - This is a huge drain on performance and memory.