Java Reference
In-Depth Information
String Literals
You have already made extensive use of string literals for output. Just about every time the println()
method was used in an example, we used a string literal as the argument. A string literal is a sequence
of characters between double quotes:
"This is a string literal!"
This is actually a String literal with a capital S - in other words, a constant object of the class String
that the compiler creates for use in your program.
Some characters can't be entered explicitly from the keyboard for inclusion in a string literal. You can't
include a double quote character as it is, for example, as this is used to indicate where a string literal
begins and ends. You can't include a newline character by pressing the Enter key since this will move the
cursor to a new line. As we saw back in Chapter 2, all of these characters are provided in the same way
as char constants - you use an escape sequence. All the escape sequences you saw when we looked at
char constants apply to strings. The statement:
System.out.println("This is \na string constant!");
will produce the output:
This is
a string constant!
since \n is used for a newline character. Like values of type char , strings are stored internally as
Unicode characters. You can also include Unicode character codes in a string as escape sequences of the
form \unnnn where nnnn are the four hexadecimal digits of the Unicode coding for a particular
character. The u can only be in the lower case. The Greek letter,
π
, for example, is \U03C0 .
You will recall from our preliminary discussion of classes and objects in Chapter 1 that a class usually
contains data and methods and, naturally, this is true of the String class. The sequence of characters
included in the string is the class data, and the methods in the class String enable you to process the
data in a variety of ways. We will go into the detail of how the class is defined in Chapter 5, but in this
chapter we will concentrate on how we can create and use objects of the class String . You know how
to define a String literal. The next step is to learn how a String variable is declared and how
String objects are created.
Creating String Objects
Just to make sure there is no confusion in your mind, a String variable is simply an object of the class
String . You declare a String variable in much the same way as you define a variable of one of the
basic types. You can also initialize it in the declaration, which is generally a good idea:
String myString = "My inaugural string";
Search WWH ::




Custom Search