Java Reference
In-Depth Information
You can write the object named by the String variable blessing to the screen as
follows:
System.out.println(blessing);
which produces the screen output
Live long and prosper.
The String Class
The class String is a predefined class that is automatically made available to you when you
are programming in Java. Objects of type String are strings of characters that are written
within double quotes. For example, the following declares the variable motto to be of type
String and makes motto a name for the String object "We aim to please." :
String motto = "We aim to please.";
Concatenation of Strings
When you use the + operator on two strings, the result is the string obtained by con-
necting the two strings to get a longer string. This is called concatenation . So, when it
is used with strings, the + is sometimes called the concatenation operator . For exam-
ple, consider the following:
+ operator
concatenation
String noun = "Strings";
String sentence;
sentence = noun + "are cool.";
System.out.println(sentence);
This will set the variable sentence to "Stringsare cool." and will output the follow-
ing to the screen:
Stringsare cool.
Note that no spaces are added when you concatenate two strings. If you wanted
sentence set to "Strings are cool." , then you should change the assignment state-
ment to add the extra space. For example, the following will add the desired space:
sentence = noun + " are cool.";
We added a space before the word "are" .
You can concatenate any number of String s using the + operator. Moreover, you
can use the + operator to concatenate a String to almost any other type of item. The
result is always a String . In most situations, Java will convert an item of any type to a
Search WWH ::




Custom Search