Skip to main content
Engineering LibreTexts

1.6: From the Java Library- System and PrintStream

  • Page ID
    15061
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    Java comes with a library of classes that can be used to perform common tasks. The Java class library is organized into a set of packages, where each package contains a collection of related classes. Throughout the book we will identify library classes and explain how to use them. In this section we introduce the System and PrintStream classes, which are used for printing a program’s output.

    Java programs need to be able to accept input and to display output. Deciding how a program will handle input and output (I/O) is part of designing its user interface, a topic we take up in detail in Chapter 4. The simplest type of user interface is a command-line interface, in which input is taken from the command line through the keyboard, and output is displayed on the console. Some Java applications use this type of interface. Another type of user interface is a Graphical User Interface (GUI), which uses buttons, text fields, and other graphical components for input and output. Java applets use GUIs as do many Java applications. Because we want to be able to write programs that generate output, this

    section describes how Java handles simple console output.

    In Java, any source or destination for I/O is considered a stream of bytes or characters. To perform output, we insert bytes or characters into the stream. To perform input, we extract bytes or characters from the stream. Even characters entered at a keyboard, if considered as a sequence of keystrokes, can be represented as a stream.

    There are no I/O statements in the Java language. Instead, I/O is handled through methods that belong to classes contained in the 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() statement

    System.out.println("Hello, World");

    prints the message “Hello, World” on the Java console. Let’s now examine this statement more carefully to see how it makes use of the Java I/O classes.

    The 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 [fig:printstreamUML]. Note A UML class diagram of the PrintStream class. fig:printstreamUML that in this case the PrintStream class has no attributes, just operations or methods.

    Because the various 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.15, Java’s java.lang.Systemclass contains three predefined streams, including two PrintStream objects. This class has public (\(+\)) attributes. None of its public methods are shown here.

    Both the System.out and System.err objects can be used to write output to the console. As its name suggests, the errstream is used primarily for error messages, whereas the 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.

    The only difference between the 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 statements

    System.out.print("hello");         
    System.out.println("hello again"); 
    System.out.println("goodbye"); 

    would produce the following output:

    hellohello again
    goodbye

    The System class. fig:systemUML

    Now that we know how to use Java’s printing expert, let’s use it to “sing” a version of “Old MacDonald Had a Farm.” As you might guess, this program will simply consist of a sequence of System.out.println() statements each of which prints a line of the verse. The complete Java application program is shown in Figure [fig:oldmac].

    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

    This example illustrates the importance of using the Java class library. If there’s a particular task we want to perform, one of the first things we should ask is whether there is already an “expert” in Java’s class library that performs that task. If so, we can use methods provided by the expert to perform that particular task.

    One good way to learn how to write programs is to modify existing programs. Modify the OldMacDonald class to “sing” one more verse of the song.

    Write a Java class that prints the design shown on the left.

    algorithm

    applet

    application program

    assignment statement

    comment

    compound statement (block)

    data type

    declaration statement

    default constructor

    executable statement

    expression

    identifier

    literal value

    object instantiation

    operator

    package

    parameter

    primitive data type

    pseudocode

    qualified name

    semantics

    statement

    stepwise refinement

    syntax

    Good program design requires that each object and method have a well-defined role and clear definition of what information is needed for the task and what results will be produced.

    Good program design is important; the sooner you start coding, the longer the program will take to finish. Good program design strives for readability, clarity, and flexibility.

    Testing a program is very important and must be done with care, but it can only reveal the presence of bugs, not their absence.

    An algorithm is a step-by-step process that solves some problem. Algorithms are often described in pseudocode, a hybrid language that combines English and programming language constructs.

    A syntax error occurs when a statement breaks a Java syntax rules. Syntax errors are detected by the compiler. A semantic error is an error in the program’s design and cannot be detected by the compiler.

    Writing Java code should follow the stepwise refinement process.

    Double slashes (//) are used to make a single-line comment. Comments that extend over several lines must begin with /* and end with */.

    An identifier must begin with a letter of the alphabet and may consist of any number of letters, digits, and the special characters _ and $. An identifier cannot be identical to a Java keyword. Identifiers are case sensitive.

    A keyword is a term that has special meaning in the Java language (Table 1.1).

    Examples of Java’s primitive data types include the int, boolean, and double types.

    A variable is a named storage location. In Java, a variable must be declared before it can be used.

    A literal value is an actual value of some type, such as a String ("Hello") or an int (5).

    A declaration statement has the form: ;

    An assignment statement has the form: = ; When it is executed it determines the value of the Expression on the right of the assignment operator (\(=\)) and stores the value in the variable named on the left.

    Java’s operators are type dependent, where the type is dependent on the data being manipulated. When adding two intvalues (\(7 + 8\)), the \(+\) operation produces an int result.

    A class definition has two parts: a class header and a class body. A class header takes the form of optional modifiers followed by the word class followed by an identifier naming the class followed, optionally, by the keyword extends and the name of the class’s superclass.

    There are generally two kinds of elements declared and defined in the class body: variables and methods.

    Object instantiation is the process of creating an instance of a class using the new operator in conjunction with one of the class’s constructors.

    Dot notation takes the form qualifiers.elementName. The expression System.out.print("hello") uses Java dot notation to invoke the print() method of the System.out object.

    A Java application program runs in stand-alone mode. A Java applet is a program that runs within the context of a Java-enabled browser. Java applets are identified in HTML documents by using the tag.

    A Java source program must be stored in a file that has a .java extension. A Java bytecode file has the same name as the source file but a .class extension. It is an error in Java if the name of the source file is not identical to the name of the public Java class defined within the file.

    Java programs are first compiled into bytecode and then interpreted by the Java Virtual Machine (JVM).

    The value 12 is stored in num.

    int num2 = 711 + 712;

    The definition of the OldMacDonald class is:

    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.");
    
         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 pig.");
         System.out.println("E I E I O.");
         System.out.println("With an oink oink here.");
         System.out.println("And an oink oink  there.");
         System.out.println("Here an oink, there an oink,");
         System.out.println("Everywhere an oink oink.");
         System.out.println("Old MacDonald had a farm");
         System.out.println("E I E I O.");
       }  // End of main
    }  // End of OldMacDonald

    The definition of the Pattern class is:

    public class Pattern
    {
         public static void main(String args[])// Main method
         {
             System.out.println("**********");
             System.out.println("* **  ** *");
             System.out.println("*   **   *");
             System.out.println("* *    * *");
             System.out.println("*  ****  *");
             System.out.println("**********");
         }  // End of main
    }  // End of Pattern

    Fill in the blanks in each of the following statements.

    =14pt

    A Java class definition contains an object’s


    and


    .

    A method definition contains two parts, a


    and a


    .

    =11pt

    Explain the difference between each of the following pairs of concepts.

    Application and applet.

    Single-line and multiline comment.

    Compiling and running a program.

    Source code file and bytecode file.

    Syntax and semantics.

    Syntax error and semantic error.

    Data and methods.

    Variable and method.

    Algorithm and method.

    Pseudocode and Java code.

    Method definition and method invocation.

    For each of the following, identify it as either a syntax error or a semantic error. Justify your answers.

    Write a class header as public Class MyClass.

    Define the init() header as public vid init().

    Print a string of five asterisks by System.out.println("***");.

    Forget the semicolon at the end of a println() statement.

    Calculate the sum of two numbers as N \(-\) M.

    Suppose you have a Java program stored in a file named Test.java. Describe the compilation and execution process for this program, naming any other files that would be created.

    Suppose N is 15. What numbers would be output by the following pseudocode algorithm? Suppose N is 6. What would be output by the algorithm in that case?

    0. Print N.
    1. If N equals 1, stop.
    2. If N is even, divide it by 2.
    3. If N is odd, triple it and add 1.
    4. Go to step 0.

    Suppose N is 5 and M is 3. What value would be reported by the following pseudocode algorithm? In general, what quantity does this algorithm calculate?

    0. Write 0 on a piece of paper.
    1. If M equals 0, report what's on the paper and stop.
    2. Add N to the quantity written on the paper.
    3. Subtract 1 from M.
    4. Go to step 1.

    Puzzle Problem: You are given two different length ropes that have the characteristic that they both take exactly one hour to burn. However, neither rope burns at a constant rate. Some sections of the ropes burn very fast; other sections burn very slowly. All you have to work with is a box of matches and the two ropes. Describe an algorithm that uses the ropes and the matches to calculate when exactly 45 minutes have elapsed.

    Puzzle Problem: A polar bear that lives right at the North Pole can walk due south for one hour, due east for one hour, and due north for one hour, and end up right back where it started. Is it possible to do this anywhere else on earth? Explain.

    Puzzle Problem: Lewis Carroll, the author of Alice in Wonderland, used the following puzzle to entertain his guests: A captive queen weighing 195 pounds, her son weighing 90 pounds, and her daughter weighing 165 pounds, were trapped in a very high tower. Outside their window was a pulley and rope with a basket fastened on each end. They managed to escape by using the baskets and a 75-pound weight they found in the tower. How did they do it? The problem is that anytime the difference in weight between the two baskets is more than 15 pounds, someone might get hurt. Describe an algorithm that gets them down safely.

    Puzzle Problem: Here’s another Carroll favorite: A farmer needs to cross a river with his fox, goose, and a bag of corn. There’s a rowboat that will hold the farmer and one other passenger. The problem is that the fox will eat the goose if they are left alone on the river bank, and the goose will eat the corn if they are left alone on the river bank. Write an algorithm that describes how he got across without losing any of his possessions.

    Puzzle Problem: Have you heard this one? A farmer lent the mechanic next door a 40-pound weight. Unfortunately, the mechanic dropped the weight and it broke into four pieces. The good news is that, according to the mechanic, it is still possible to use the four pieces to weigh any quantity between one and 40 pounds on a balance scale. How much did each of the four pieces weigh? (Hint: You can weigh a 4-pound object on a balance by putting a 5-pound weight on one side and a 1-pound weight on the other.)

    Suppose your little sister asks you to show her how to use a pocket calculator so that she can calculate her homework average in her science course. Describe an algorithm that she can use to find the average of 10 homework grades.

    A Caesar cipher is a secret code in which each letter of the alphabet is shifted by N letters to the right, with the letters at the end of the alphabet wrapping around to the beginning. For example, if N is 1, when we shift each letter to the right, the word daze would be written as ebaf. Note that the z has wrapped around to the beginning of the alphabet. Describe an algorithm that can be used to create a Caesar encoded message with a shift of 5.

    Suppose you received the message, “sxccohv duh ixq,” which you know to be a Caesar cipher. Figure out what it says and then describe an algorithm that will always find what the message said regardless of the size of the shift that was used.

    Suppose you’re talking to your little brother on the phone and he wants you to calculate his homework average. All you have to work with is a piece of chalk and a very small chalkboard—big enough to write one four-digit number. What’s more, although your little brother knows how to read numbers, he doesn’t know how to count very well so he can’t tell you how many grades there are. All he can do is read the numbers to you. Describe an algorithm that will calculate the correct average under these conditions.

    Write a header for a public applet named SampleApplet.

    Write a header for a public method named getName.

    Design a class to represent a geometric rectangle with a given length and width, such that it is capable of calculating the area and the perimeter of the rectangle.

    Modify the OldMacDonald class to “sing” either “Mary Had a Little Lamb” or your favorite nursery rhyme.

    Define a Java class, called Patterns, modeled after OldMacDonald, that will print the following patterns of asterisks, one after the other heading down the page:

     *****     *****   *****
      ****     *   *   * * *
       ***     *   *    * *
        **     *   *   * * *
         *     *****   *****

    Write a Java class that prints your initials as block letters, as shown in the example in the margin.

    Challenge: Define a class that represents a Temperature object. It should store the current temperature in an instance variable of type double, and it should have two public methods, setTemp(double t), which assigns t to the instance variable, and getTemp(), which returns the value of the instance variable. Use the Riddle class as a model.

    Challenge: Define a class named TaxWhiz that computes the sales tax for a purchase. It should store the current tax rate as an instance variable. Following the model of the Riddle class, you can initialize the rate using a TaxWhiz()method. This class should have one public method, calcTax(double purchase), which returns a double, whose value is purchases times the tax rate. For example, if the tax rate is 4 percent, 0.04, and the purchase is $100, then calcTax()should return 4.0.

    What is stored in the variables num1 and num2 after the following statements are executed?

      int num1 = 5;
      int num2 = 8;
      num1 = num1 + num2;
      num2 = nmm1 + num2;

    Write a series of statements that will declare a variable of type int called num and store in it the difference between 61 and 51.

    Modify the UML diagram of the Riddle class to contain a method named getRiddle() that would return both the riddle’s question and answer.

    Draw a UML class diagram representing the following class: The name of the class is Circle. It has one attribute, a radius that is represented by a double value. It has one operation, calculateArea(), which returns a double. Its attributes should be designated as private and its method as public.

    To represent a triangle we need attributes for each of its three sides and operations to create a triangle, calculate its area, and calculate its perimeter. Draw a UML diagram to represent this triangle.

    Try to give the Java class definition for the class described in The Person class. fig:person

    the UML diagram shown in Figure 1.17.


    This page titled 1.6: From the Java Library- System and PrintStream is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by Ralph Morelli & Ralph Wade via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.