Java Reference
In-Depth Information
Figure 2.2
Output of the FloatDemo program.
You may be surprised by the result of 15/4 in the FloatDemo program.
Because both 15 and 4 are int values, their quotient is also an int, in this case 3.
(The remainder is truncated.) The value of f is assigned to the int 3, so f
becomes 3.0.
In the expression pi * radius * radius, a double is being multiplied by two
ints. Before the multiplication occurs, the int values are promoted to doubles,
and the result is therefore a double.
Boolean Data Type
Java has a built-in data type, boolean, to represent Boolean values. A variable
of type boolean can be either true or false. Note that true and false are special
literals in Java.
The following BooleanDemo program demonstrates using the boolean data
type. Study the BooleanDemo program and try to determine what the output
will be.
public class BooleanDemo
{
public static void main(String [] args)
{
boolean t = true;
System.out.println(“t is “ + t);
int x = 10;
boolean y = (x > 15);
System.out.println(“y is “ + y);
// y = x; // Does not compile!
}
}
In the BooleanDemo program, t is declared as a boolean variable and is
assigned the value true. When t is printed out as a string, true is displayed. The
boolean y is assigned to an expression that evaluates to false because x is less
than 15. The string false is displayed when y is printed out (see Figure 2.3).
Search WWH ::




Custom Search