Skip Top Navigation Bar

Declaring Strings

A very useful reference type is String, which is a collection of characters. It is implemented using the String class. Recall, a class is a blueprint that defines the data and behavior of this data type.

String variables are assigned String literals. A literal is a fixed value. A String literal is enclosed in double quotes. The following are examples of String literals: "Hello", "The big brown dog jumped over the lazy orange cat", "!@#$%^&*()". When we use a String literal we are creating a String object.

An object is an instance of a class. We can declare and initialize many objects or instances of a class. Consider a blueprint for a house. A builder can construct that same house at various different addresses. The houses, aka objects, each have a distinct address, they might have a different color, different roof material, maybe a different number of bedrooms or bathrooms. But essentially it is the same house.

Declaring and Initializing String Variables

String variables are declared similar to how we would create an int or char variables.

String name = "John";

In this case, the String "John" is assigned to the variable name.

Let's try this out in the Java Playground. Toggle the Console to "Detailed Output" to get an understanding of what is happening in the computer.

Modify the code above to assign name to your name. Experiment by declaring and initializing many different String variables with different values.