Java Reference
In-Depth Information
Forexample, if you insert the following code snippet into the main method
of StarterApp1.java (see Chapter 1):
int i = 5;
int j = 3;
System.out.println ("i*j=" +(i*j));
the output to the console looks like
i*j= 15
The (i*j) expression inside the println parameter results in an integer
value, which the + append operator converts automatically to a string and
attaches to the preceding string.
Note that the parentheses around the i*j term are not necessary accord-
ing to the higher precedence of the multiplication operator compared to the +
append operator (see Appendix 2 for a table listing the precedence rules). How-
ever, with addition, as in
System.out.println ("i+j=" +i+j);
you must be careful. Without parentheses, the compiler will treat the two +
operands as equal precedence and perform a string concatenation of the i value
(5) and the j value (3) resulting in
i+j = 53
if you instead desired the numerical sum, as in
i+j= 8
you must use the following:
System.out.println ("i+j=" +(i+j));
In general, for the sake of clarity, it is good practice to use parentheses whenever
a numerical expression appears inside a print or println parameter.
For floating-point values, Java automatically adjusts the output based on the
number of digits in the fractional part of the value. For this code snippet,
double = 5.0;
int y = 3.0;
System.out.println ("x*y=" +(x*y));
System.out.println ("x/y=" +(x/y));
the output to the console looks like
x*y= 15.0
x/y= 1.6666666666666667
Note the variation in the number of digits in the fraction. The basic println
method does not provide a way to specify the formatting of numerical values.
Search WWH ::




Custom Search