Skip Top Navigation Bar

Constructing a String

In the Declaring Strings tutorial, we used String objects, created by using string literals. Reminder that a string literal is characters enclosed in double quotes ("). In Introduction to Arithmetic Expressions, we used the + operator to concatenate, or add, string literals. We also used string literals as part of output in Introduction to Console Input and Output, Formatting Output with Escape Sequences and Formatting Output with Text Blocks.

Need a refresher on creating objects and calling methods? Learn: Creating Objects and Calling Methods

String Constructor

While in previous String tutorials, we used string literals to create String objects. There is a String constructor that can also be used. To satisfy any curiousity, here is an example of how to create a String object using a String constructor:

String myName = new String("Duke");

We will likely stick to using string literals to create String objects.

Strings Are Immutable

Recall that the value of a String is immuntable, it cannot be changed. A String variable's value can be altered by assigning it to a new String, but not by changing the existing String. Consider the example below.

String phrase = "Duke";
phrase = phrase + " loves Java";

The value "Duke" is concatenated with " loves Java" and a new String object is created that is "Duke loves Java".

String Methods

Throughout this series of String tutorials, we have provided some common String methods and examples of their use. For a complete list of String methods can be found in the String API.

Methods that are part of the AP Computer Science A Java subset are denoted by the APCSA label.

int length()

This method returns the number of characters that are in the String.

Your Turn

Let's try it in the Java Playground.

Complete List of String Learn Tutorials

Resources

Next Learn Tutorial

Learn: String Indexing