Java Reference
In-Depth Information
4 int minutes = hours * 60;
5 int seconds = minutes * 60;
6 System.out.println("Hours in a year = " + hours);
7 System.out.println("Minutes in a year = " + minutes);
8 System.out.println("Seconds in a year = " + seconds);
9 }
10 }
Notice that the three println commands at the end each have a string literal
concatenated with a variable. The program produces the following output:
Hours in a year = 8760
Minutes in a year = 525600
Seconds in a year = 31536000
You can use concatenation to form arbitrarily complex expressions. For example,
if you had variables x , y , and z and you wanted to write out their values in coordinate
format with parentheses and commas, you could say:
System.out.println("(" + x + ", " + y + ", " + z + ")");
If x , y , and z had the values 8 , 19 , and 23 , respectively, this statement would
output the string "(8, 19, 23)" .
The + used for concatenation has the same level of precedence as the normal
arithmetic + operator, which can lead to some confusion. Consider, for example, the
following expression:
2 + 3 + " hello " + 7 + 2 * 3
This expression has four addition operators and one multiplication operator.
Because of precedence, we evaluate the multiplication first:
2 + 3 + " hello " + 7 + 2 * 3
2 + 3 + " hello " + 7 + 6
This grouping might seem odd, but that's what the precedence rule says to do: We
don't evaluate any additive operators until we've first evaluated all of the multiplica-
tive operators. Once we've taken care of the multiplication, we're left with the four
addition operators. These will be evaluated from left to right.
The first addition involves two integer values. Even though the overall expression
involves a string, because this little subexpression has just two integers we perform
integer addition:
2 + 3 + " hello " + 7 + 6
5 + " hello " + 7 + 6
Search WWH ::




Custom Search