Java Reference
In-Depth Information
Using Primitive Variables Tutorial Answers and Explanation
The first println statement:
System.out.println(++intTest);
contains a pre-increment for intTest. The pre-increment is performed before the println operation and the value of
intTest is increased from 3 to 4. The println is then performed, resulting in a 4 appearing in the console.
The second println statement:
System.out.println(intTest++);
contains a post-increment. This means the println is performed first, resulting in the value of intTest being displayed
as 4 again, and then the value of intTest is incremented to 5. Result:
4
4
The next println contains a formula that divides two integers and, as mentioned earlier, any fractional result is
truncated.
System.out.println(intTest/2);
So, 3 divided by 2 results in 1.5, but the .5 is dropped. The other formulas:
System.out.println(intTest/2.0);
System.out.println(intTest/doubleTest);
divide an integer by a double. When an integer is divided by a double, the integer is promoted to a double. In other
words, the JVM converts the integer (2) into a double (2.0) then performs the operation. Division between two
doubles will retain any fractional result, so the .5 is retained for both results. Result:
1
1.5
1.5
Now let's consider the following line:
System.out.println(Math.pow(doubleTest, intTest)/(2.0*3.0));
The multiplication is done first (because it is enclosed in parentheses, (2.0*3.0)) resulting in 6.0. The JVM now
“sees” the formula as Math.pow(doubleTest, intTest)/6.0 and performs the remaining operations from left to right:
Math.pow raises doubleTest (2.0) by the power of intTest (3) resulting in 8.0. Then 8.0 is divided by 6.0. Result:
1.3333333333333333
The next statement's math operations are simply executed from left to right.
System.out.println(Math.pow(doubleTest, intTest) * 3/2);
 
Search WWH ::




Custom Search