Java Reference
In-Depth Information
operates. If either or both of the operands of the + operator are strings, then string
concatenation is performed.
The Addition program shown in Listing 2.3 demonstrates the distinction
between string concatenation and arithmetic addition. The Addition program
uses the + operator four times. In the first call to println , both + operations per-
form string concatenation, because the operators are executed left to right. The
first operator concatenates the string with the first number ( 24 ), creating a larger
string. Then that string is concatenated with the second number ( 45 ), creating an
even larger string, which gets printed.
In the second call to println , we use parentheses to group the + operation
with the two numeric operands. This forces that operation to happen first.
Because both operands are numbers, the numbers are added in the arithmetic
LISTING 2.3
//********************************************************************
// Addition.java Author: Lewis/Loftus
//
// Demonstrates the difference between the addition and string
// concatenation operators.
//********************************************************************
public class Addition
{
//-----------------------------------------------------------------
// Concatenates and adds two numbers and prints the results.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("24 and 45 concatenated: " + 24 + 45);
System.out.println ("24 and 45 added: " + (24 + 45));
}
}
OUTPUT
24 and 45 concatenated: 2445
24 and 45 added: 69
 
Search WWH ::




Custom Search