Building expressions using variables

 

We can build expressions using variables just as we did with numeric values.  Remember that we have both arithmetic and relational operators to work with.  Here’s a code segment with two variables of type double (Note: The class and main method definitions are missing.  You would need to add those to run this example):

 

       double x = 2.3;

       double y = 3.2;

 

       System.out.println(x + y);

       System.out.println(x != y);

       System.out.println(2 * x < y);

 

The output of the code segment above would be (try to reason it out first):

 

5.5

true

false

 

Our next example will compute the volume of a cone given the radius of it base and its height and then display the result.  A simple Web search will reveal that the formula for the volume is:   Ok great.  Now what? When we’re faced with such a task it’s often important to first identify what variables we’re going to need.  Luckily we can look for the formula to provide us with a hint – a big hint.  Each of the variables in the formula corresponds to a variable in our program!  Since the volume must be a real number, we declare all the variables to be of type double.  Here’s the full program:

 

               public class ComputeConeVolume

       {

          public static void main(String[] args)

          {

             double pi = 3.141592654;

             double radius = 10.0;

             double height = 5.0;

             double volume;

      

             volume = 1.0/3.0 * pi * radius * radius * height;

            

             // don’t worry about the next statement wrapping around

      System.out.println(“The volume of a cone with radius “ + radius + “ and height “ + height  + “ is “ + volume);

    }

 }

 

The first four lines in main are the declarations, followed by the expression to compute the volume, and finally a statement to display the result.  You can see that the program computes the volume of a particular cone, one with a radius of 10 and a height of 5.  If you were interested in a cone with different dimensions, you would need to modify the initial values and the recompile and run the program.  This seems to be a big limitation, but fortunately we’ll be able to overcome this in the next unit when we look at how to obtain input from the user.