Java Reference
In-Depth Information
50cm in width, 100cm in height and 20cm in depth. We simply do compute
the volume in cubic meters
m
3
by converting the dimension units into meter
equivalents and performing the product of these dimensions to get the volume.
Thus the volume of that 3D box is
0
.
2
m
=0
.
1
m
3
.
0
.
5
m
×
1
m
×
How do we program this? We simply need to
evaluate
the arithmetic expression
0
.
5
×
1
×
0
.
2
Program 1.3
Expression: Evaluating the volume of a 3D box
class
VolumeBox
{
public static void
main ( String [
]
args )
System . out . println (0.5
∗
1
∗
0.2) ;
}
}
Storing the above program into filename
VolumeBox.java
, compiling and
executing it, we get the expected output:
0.1
Thus we can
calculate
the value of
any
arithmetic expression, say the generic
myExpression
expression, and
display
its value by executing the instruction
System.out.println(myExpression);
Of course, this straight number alone is not
very informative, so it is better to display a message on the console telling
what the number really means. We do this by printing the message without
the return carriage (line return) using the instruction
System.out.print
.
class
VerboseVolumeBox
{
public static void
main ( String [ ] args )
System . out . print (
"Volume of the box (in cubic meters):"
);
System . out . println (0.5
∗
1
∗
0.2) ;
}
}
Compiling and running this program yields the better verbose output:
Volume of the box (in cubic meters):0.1
1.3.1 Arithmetic operations and priority order
The arithmetic operations used in expressions are:
-
The addition (
+
)
Search WWH ::
Custom Search