Java Reference
In-Depth Information
Using the + Sign with Strings
If you connect two strings with the + operator, the result is the concatenation (pasting) of
the two strings.
EXAMPLE
String name = "Chiana";
String farewell = "Good bye " + name;
System.out.println(farewell);
This sets farewell to the string "Good bye Chiana" . So, it outputs the following to the
screen:
Good bye Chiana
Note that we added a space at the end of "Good bye " .
string when you connect it to a string with the + operator. For numbers, it does the
obvious thing. For example,
String solution = "The answer is " + 42;
will set the String variable solution to "The answer is 42" . Java converts the integer
constant 42 to the string "42" and then concatenates the two strings "The answer is "
and "42" to obtain the longer string "The answer is 42".
Notice that a number or other value is converted to a string object only when it is
connected to a string with a plus sign. If it is connected to another number with a plus
sign, it is not converted to a string. For example,
System.out.println("100" + 42);
outputs
10042
but
System.out.println(100 + 42);
outputs
142
Classes
Classes are central to Java and you will soon be defining and using your own classes. The
class String , which we discuss in this section, gives us an opportunity to introduce some
Search WWH ::




Custom Search