1.9 Printing and Reading Values of Variables


The print and println methods that we have used to print strings can also be used to print values of variables of any type.

Example 1

The following program prints the value of an int variable.
class PrintValue
{
   // This program assigns a value to the variable
   // "number" and then prints that value.
   public static void main (String[] args)
   {
      int number = 37;
      System.out.println(number);
   }
} 

Of course, we must be sure that variables have values before we attempt to print them.

Example 2

The following program will produce an error message if we attempt to compile it.
class NoValue
{
   // This program is wrong because the variable
   //"number" is never given a value.
   public static void main (String[] args)
   {
      int number;
      System.out.println(number) ;
   }
} 

In the statement

System.out.println("Hello"); 
the string "Hello" contained within the parentheses is called the argument of the println method. The print and println methods both print strings. If we give an argument that is not a string, it must be converted to a string. For all of Java's primitive types, this conversion is done automatically.

It is also possible to use a mixture of strings and variables of other types as the argument of the print or println methods. In this case, Java will, again, automatically convert any non-string values to strings. Then the concatenation operator (+) can be used to produce one string for printing.

Example 3

If the String variable friend refers to the string "Nadine" and the int variable age has the value 17, then the statement
System.out.println(friend + " is " + age  " years old");
will print
Nadine is 17 years old

We must be careful when we print more than one variable with one print or println statement as the results may not be what we want.

Example 4

If the byte variables height and width have values 4 and 6, then the statement
System.out.println("Dimensions are " + height + width); 
will print

Dimensions are 46
It would be better to write

System.out.println("Dimensions are" + height
                         + " and " + width); 

to print

Dimensions are 4 and 6

As the previous examples illustrate, integer values are converted to strings of just the right length before printing. To print boolean variables, the strings "true" or "false" are generated. For char variables, a one character string is produced. For floating point variables, the values are normally converted to strings containing 8 digits for float values and 16 digits for double values. However, any trailing zeros after a decimal point will not be printed.

Example 5

Consider the following program.

class PrintValues
{
   public static void main (String[] args)
   {
      boolean b true;
      float f = 12.3456789f;
      double d1 = 1234.567898765432;
      double d2 = 1234.5678;
      System.out.println(b);
      System.out.println(f);
      System.out.println(d1);
      System.out.println(d2);
   }
} 
It should produce the following output

true
12.345679
1234.567898765432
1234.5678

The process of reading values into memory is rather complicated in Java. To make reading simpler, we have included with this text (in Appendix A and on our web site) a set of methods that allows you to read values from the standard input device for your computer (likely the computer's keyboard), in a fairly simple way. The methods are contained in a class called In. (If you prefer to use Java's methods for reading values, instructions for their use can be found in Appendix B.)

The class In is not part of Java; you will not likely see it used outside this text. To use the methods contained in In, obtain a copy of the file In.java, copy it into the directory that you are using for your Java programs, and then compile it, just as you would compile any Java program, to produce a file called In.class. Now, to read a value of a particular type, simply write the name of the appropriate method in an assignment statement as shown in the next example.

Example 6

To read a value into the int variable i, we can use the method getInt that reads a single integer from the standard input device, usually the keyboard. The form of the statement that reads the value is:

   i = In.getInt();

Notice the use of parentheses with the getInt method. Any time that we use a method in Java, we must include parentheses, even if, as is the case here, the method has no argument. (We have already seen this in the use of

System.out.println(); 
to print a blank line.)

Other methods in the class In include: getLong to read a long value, getChar to read a single character, getString to read a string, getFloat to read a float value, and getDouble to read a double value. They are all used in the same way.

The methods all assume that each input value is terminated by a newline. Thus, to use them at a keyboard, you must press the enter key after keying in the value. If incorrect input is entered, the methods that were expecting numeric input give a value of zero. If the user simply hits the enter key when entering a string, the method getString produces the value "", the empty string that contains no characters.

Now that we have methods for both reading and printing, we can write interactive programs, ones that ask or prompt the user for input, wait until the user responds to the prompt by providing some input, process this input in some way, and produce some output.

Example 7

This program illustrates a simple interactive process.

class Interactive
{
   public static void main (String[] args)
   {
         // obtain name and age
         System.out.println("What is your first initial?");
         char firstlnitial = In.getChar();
         System.out.println("What is your family name?");
         String familyName = In.getString();
         System.out.println("What is your age in years?");
         int age = In.getlnt();
         // respond to input
         System.out.println("Well, " + firstlnitial + "
                            + familyName + ". - "
                            + "I see that your age is " + age);
   }
} 
If a user were to respond to the prompts with
N
Fung
17
then the program would produce the following output:
Well, N. Fung - I see that your age is 17

Exercise 1.9

  1. What would be printed by each fragment?
      a)
      int i = -47, j = 35;

      System.out.println("The value of i is " + i + "\nwhile j is " + j + ".");

      b)
      boolean done = false;

      System.out.println("We are not " + done + " yet");

      c)
      double x = 0.012, Y = 2.7374e1;

      System.out.println("x -> " + X + "\ny -> " + y);

  2. Write a program that creates a double variable called myMass, asks the user to give his/her mass, and then prints a message giving the person's mass.