In class practice   Variables and Expressions

June 25, 2007

Here is an example:

For following variables and expressions:

variable name data type initial value
W constant float 3.5f
x char 'A'
y int
result double

y = W+x;
result = W*y;

We can have the corresponding Java program:

public class varAndExp
{
    public static void main (String[] args)
    {
        //variable declaration
        final float W = 3.5f;
        char x = 'A';
        int y;
        double result;

        //expression 1
        y = (int)(W+(float)(x));

        //expression 2
        result = W*y;

        //output the result
        System.out.println("The result is " + result);
    } // end of main method
}// end of class varAndExp

The output of the program is 238.0

Follow the above example and write Java programs based on the given variables and expressions. Please be careful to the necessary type conversion. What are the output of the programs?

A.   Solution

variable name data type initial value
x double 1
y double 7
z double 4
result float

result = x+2*(y/z)+18;

 

B.   Solution

variable name data type initial value
x int 1
y int 7
z int 4
result float

result = x+2*(y/z)+18;

CSolution

variable name data type initial value
w double 4.3
X constant int 4
y float 1.7
z double
result double

w = w+1;
y = y-1;
z = w/y+X;
result = (w - X)*y/z+z-w;

DSolution

variable name data type initial value
W constant char 'A'
X constant char 'a'
y char '+'
z int
result char

z = W + y + X;
result = z + 'B'-'b'-101;