Principle 1.7.4. EFFECTIVE DESIGN: Using the Java Library.
Learning how to use classes and objects from the Java class library is an important part of object-oriented programming in Java.
System
and PrintStream
classes, which are used for printing a program’s output.HelloWorld
(Listing 1.5.1), use this type of interface.HelloWorldCanvas
program (Listing 1.5.16), is an example of a GUI.java.io
package. We have already seen how the output method println()
is used to output a string to the console. For example, the following println()
statementSystem.out.println("Hello, World");
java.io.PrintStream
class is Java’s printing expert, so to speak. It contains a variety of print()
and println()
methods that can be used to print all of the various types of data we find in a Java program. A partial definition of PrintStream
is shown in Figure 1.7.1. Note that in this case the PrintStream
class has no attributes, just methods.PrintStream
class.print()
and println()
methods are instance methods of a PrintStream
object, we can only use them by finding a PrintStream
object and “telling” it to print data for us. As shown in Figure 1.7.2, Java’s java.lang.System
class contains two public (+) PrintStream
objects, System.out
and System.err
.PrintStream
class.System.err
stream is used primarily for error messages, whereas the System.out
stream is used for other printed output. Similarly, as its name suggests, the System.in
object can be used to handle input, which will be covered in Chapter 2.print()
and println()
methods is that println()
will also print a carriage return and line feed after printing its data, thereby allowing subsequent output to be printed on a new line. For example, the following statementsSystem.out.print("hello");
System.out.println("hello again");
System.out.println("goodbye");
hellohello again
goodbye
System.out.println()
statements each of which prints a line of the verse. The complete program is shown in Listing 1.7.3. You can run the program in the self-study exercises below.OldMacDonald.java
class. public class OldMacDonald
{
public static void main(String args[]) // Main method
{
System.out.println("Old MacDonald had a farm");
System.out.println("E I E I O.");
System.out.println("And on his farm he had a duck.");
System.out.println("E I E I O.");
System.out.println("With a quack quack here.");
System.out.println("And a quack quack there.");
System.out.println("Here a quack, there a quack,");
System.out.println("Everywhere a quack quack.");
System.out.println("Old MacDonald had a farm");
System.out.println("E I E I O.");
} // End of main
} // End of OldMacDonald
OldMacDonald
class to “sing” one more verse of the song for an animal of your choice.********** * ** ** * * ** * * * * * * **** * *********