Java Reference
In-Depth Information
Self-Test Exercises
1. What output is produced by the following lines?
String s = "Hello" + "Joe";
System.out.println(s);
2. Write Java statements that will cause the following to be written to the screen:
One two buckle your shoe.
Three four shut the door.
3. What is the difference between System.out.println and System.out.print ?
4. What is the output produced by the following lines?
System.out.println(2 + " " + 2);
System.out.println(2 + 2);
TIP: Different Approaches to Formatting Output
If you have a variable of type double that stores some amount of money, you would
like your programs to output the amount in a nice format. However, if you just use
System.out. println , you are likely to get output that looks like the following:
Your cost, including tax, is $19.98327634144
You would like the output to look like this:
Your cost, including tax, is $19.98
To obtain this nicer form of output, you need some formatting tools.
We will present three approaches to formatting numeric (and other) output. We
will discuss the method printf and the two formatting classes NumberFormat and
DecimalFormat . The printf method is often the simplest way to format output.
However, printf uses an older methodology and so some authorities prefer to use
NumberFormat , DecimalFormat , or similar formatting classes because these classes use
a programming methodology that is perhaps more in the spirit of modern (object-
oriented) programming. We will let you (or your instructor if you are in a class)
decide which methodology to use. After this chapter, this topic seldom uses any of
these formatting details.
Formatting Output with printf
Starting with version 5.0, Java includes a method named printf that can be used to
give output in a specific format. The method printf is used the same way as the
System.out.
printf
Search WWH ::




Custom Search