The char type only represents one character. To represent a string of characters , use the data type called String . For example, the following code declares the message to be a string that has an initial value of "Welcome to Java".
String message = "Welcome to Java" ;
String is actually a predefined class in the Java library just like the System class and JOptionPane class. 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. Reference data types will be thoroughly discussed in Chapter 7, "Classes and Objects." For the time being, you only need to know how to declare a String variable, how to assign a string to the variable, and how to concatenate strings.
As first shown in Listing 2.1, two strings can be concatenated . The plus sign ( + ) is the concatenation operator if one of the operands is a string. If one of the operands is a non-string (e.g., a number), the non-string 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' ; // s becomes SupplementB
If neither of the operands is a string, the plus sign ( + ) is the addition operator that adds two numbers .
The shorthand += 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" .
Suppose that 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 ) );