Java Reference
In-Depth Information
158
4.6 Strings
Next to numbers, strings are the most important data type that most programs use. A
string is a sequence of characters, such as ÐHello, World!Ñ . In Java, strings are
enclosed in quotation marks, which are not themselves part of the string. Note that,
unlike numbers, strings are objects. (You can tell that String is a class name
because it starts with an uppercase letter. The primitive types int and double start
with lowercase letters.)
The number of characters in a string is called the length of the string. For example,
the length of ÐHello, World!Ñ is 13. You can compute the length of a string
with the length method.
A string is a sequence of characters. Strings are objects of the String class.
int n = message.length();
A string of length zero, containing no characters, is called the empty string and is
written as Ȓȓ.
Use the + operator to put strings together to form a longer string.
String name = "Dave";
String message = "Hello, " + name;
The + operator concatenates two strings, provided one of the expressions, either to the
left or the right of a + operator, is a string. The other one is automatically forced to
become a string as well, and both strings are concatenated.
Strings can be concatenated, that is, put end to end to yield a new longer string.
String concatenation is denoted by the + operator.
For example, consider this code:
String a = "Agent";
int n = 7;
String bond = a + n;
Search WWH ::




Custom Search