A very useful reference type is String
, which is a collection of characters. It is implemented using the String
class.
String
variables are assigned String literals. A literal is a fixed value. A String
literal is a collection of characters 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.
Classes and Objects
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 multiple house from the same design 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 they are all houses.
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
.
Your Turn
Let's try this out in the Java Playground.
- Modify the code above to assign
name
to your name.
- Experiment by declaring and initializing many different
String
variables with different values.
Next Learn Tutorial
Learn: Mutable vs Immutable Data