The Class String
In this lesson, we will cover the class String from the Java Class Library.
String literals
Imagine that our program asks for the user’s full name, which we can represent as a string. Later in our program, we might want to use only the user’s first name or just the last name or, maybe, only the user’s initials. In this lesson, we explore how to work with strings.
Earlier, we used string literals and println
statements to display lines of text. For example,
"Java is a programming language."
is a string literal. Actually, a string literal is an object that belongs to the class String
. As such, it is a String
object, or more simply a string, and it has the data type String
. The class String
is standard in Java and is a part of the Java Class Library within the package java.lang
.
Creating String
objects
We can declare the data type of a variable to be String
much as we declare variables of other data types. We also can assign a string to a String
variable. For example, we can write
String greeting = new String("Hello");
The new
operator creates a new object of the indicated class type—String
in this case—and String("Hello")
initializes the object’s data portion. Here, the String
object is initialized to "Hello"
.
Although we use the new
operator to create an object of any class, we can create a String
object more simply. Instead of the previous Java statement, we can write
String greeting = "Hello";
Thus, we can use a string literal as we would a primitive literal in an assignment statement. Java includes this simplification since strings are so prevalent in Java programs. We will see other classes later in this chapter that allow a similar initialization. For almost all classes, however, we must use the new
operator to create a new object.
Get hands-on with 1400+ tech skills courses.