Java Reference
In-Depth Information
4.4 The String Type
A string is a sequence of characters.
Key
Point
The char type represents only one character. To represent a string of characters, use the data
type called String . For example, the following code declares message to be a string with
the value "Welcome to Java" .
String message = "Welcome to Java" ;
VideoNote
Introduce strings and objects
String is a predefined class in the Java library, just like the classes System and Scanner .
The String type is not a primitive type. It is known as a reference type . Any Java class can
be used as a reference type for a variable. The variable declared by a reference type is known
as a reference variable that references an object. Here, message is a reference variable that
references a string object with contents Welcome to Java .
Reference data types will be discussed in detail in Chapter 9, Objects and Classes. For the
time being, you need to know only how to declare a String variable, how to assign a string
to the variable, and how to use the methods in the String class. More details on using strings
will be covered in Chapter 10.
Table 4.7 lists the String methods for obtaining string length, for accessing characters
in the string, for concatenating strings, for converting a string to upper or lowercases, and for
trimming a string.
T ABLE 4.7
Simple Methods for String Objects
Method
Description
length()
Returns the number of characters in this string.
Returns the character at the specified index from this string.
charAt(index)
Returns a new string that concatenates this string with string s1.
concat(s1)
Returns a new string with all letters in uppercase.
toUpperCase()
Returns a new string with all letters in lowercase
toLowerCase()
Returns a new string with whitespace characters trimmed on both sides.
trim()
Strings are objects in Java. The methods in Table  4.7 can only be invoked from a spe-
cific string instance. For this reason, these methods are called instance methods . A non-
instance method is called a static method . A static method can be invoked without using
an object. All the methods defined in the Math class are static methods. They are not tied
to a specific object instance. The syntax to invoke an instance method is reference-
Variable.methodName(arguments) . A method may have many arguments or no argu-
ments. For example, the charAt(index) method has one argument, but the length()
method has no arguments. Recall that the syntax to invoke a static method is ClassName
.methodName(arguments) . For example, the pow method in the Math class can be invoked
using Math.pow(2, 2.5) .
instance method
static method
4.4.1 Getting String Length
You can use the length() method to return the number of characters in a string. For exam-
ple, the following code
String message = "Welcome to Java" ;
System.out.println( "The length of " + message + " is "
+ message.length());
 
 
 
Search WWH ::




Custom Search