Java Reference
In-Depth Information
Chapter 11
Strings
In this chapter, you will learn:
String
object is
•
What a
String
objects
•
How to create
String
literals
•
How to use
Strings
•
How to manipulate
Strings
in a switch statement
•
How to use
StringBuilder
and
StringBuffer
objects to work with mutable strings
•
How to use
What is a String?
A sequence of zero or more characters is known as a string. In Java programs, a string is represented by an object of the
java.lang.String
class. The
String
class is immutable. That is, the contents of a
String
object cannot be modified
after it has been created. The
String
class has two companion classes,
java.lang.StringBuilder
and
java.lang.
StringBuffer
. The
StringBuilder
class was introduced in Java 5. The companion classes are mutable. You should use
them when the contents of your string can be modified.
String Literals
A string literal consists of a sequence of zero or more characters enclosed in double quotes. All string literals are
objects of the
String
class. Examples of string literals are
"" // An Empty string
"Hello" // A string literal consisting of 5 characters
"Just a string literal" // A string literal consisting of 21 characters
Multiple string literals can be used to compose a single string literal.
// Composed of two string literals "Hello" and "Hi". It represents one string literal "HelloHi"
"Hello" + "Hi"