Java Reference
In-Depth Information
(e.g., a number), the nonstring value is converted into a string and concatenated with the other
string. Here are some examples:
// Three strings are concatenated
String message =
"Welcome "
+
"to "
+
"Java"
;
// String Chapter is concatenated with number 2
String s =
"Chapter"
+
2
;
// s becomes Chapter2
// String Supplement is concatenated with character B
String s1 =
"Supplement"
+
'B'
;
// s1 becomes SupplementB
If neither of the operands is a string, the plus sign (
+
) is the addition operator that adds two
numbers.
The augmented
+=
operator can also be used for string concatenation. For example, the
following code appends the string
"and Java is fun"
with the string
"Welcome to
Java"
in
message
.
message +=
" and Java is fun"
;
So the new
message
is
"Welcome to Java and Java is fun"
.
If
i = 1
and
j = 2
, what is the output of the following statement?
System.out.println(
"i + j is "
+ i + j);
The output is
"i + j is 12"
because
"i + j is "
is concatenated with the value of
i
first. To force
i + j
to be executed first, enclose
i + j
in the parentheses, as follows:
System.out.println(
"i + j is "
+ (i + j));
4.4.4 Converting Strings
The
toLowerCase()
method returns a new string with all lowercase letters and the
toUpperCase()
method returns a new string with all uppercase letters. For example,
"Welcome".toLowerCase()
returns a new string
welcome
.
"Welcome".toUpperCase()
returns a new string
WELCOME
.
toLowerCase()
toUpperCase()
The
trim()
method returns a new string by eliminating whitespace characters from both
ends of the string. The characters
' '
,
\t
,
\f
,
\r
, or
\n
are known as
whitespace characters
.
For example,
whitespace character
"\t Good Night \n".trim()
returns a new string
Good Night
.
trim()
4.4.5 Reading a String from the Console
To read a string from the console, invoke the
next()
method on a
Scanner
object. For
example, the following code reads three strings from the keyboard:
read strings
Scanner input =
new
Scanner(System.in);
System.out.print(
"Enter three words separated by spaces: "
);
String s1 = input.next();
String s2 = input.next();
String s3 = input.next();
System.out.println(
"s1 is "
+ s1);
System.out.println(
"s2 is "
+ s2);
System.out.println(
"s3 is "
+ s3);
Search WWH ::
Custom Search