Course Content‎ > ‎Session 2‎ > ‎

I/O in Java

I/O in Java using corejava and java.text package

Usually Input/Output with any programming language occurs with Streams and Buffers. When a program is executed, it requests resources such as memory, streams for doing Input / Output, usage of CPU, files on disk etc. For a program to communicate with the outside world, it opens a path, on which the data travels. This path is called a stream. Java has two types of streams: Character streams and Byte Streams.

Character Streams handle textual data. Sources of textual data are web pages, text files, console etc.

Byte Streams read data in bytes or binary format. For example, they can read an integer 2 in binary format (10)

Streams typically have buffers associated with them. Buffers provide a temporary location for the storage of character or bytes. An example of the usage of buffer is following: If the program refuses to accept input and the user continues to type, then the characters being typed can be stored in a buffer, available for programs use, when it is ready. Doing Input / Output in Java is fairly trivial, when reading data from a web page or a file. But is not so trivial when reading data from a console. So, to make this process easy, you are provided with the corejava package. This package in my opinion should make your life easy.

Using the corejava Package

First of all, you should download the package and install it. Assure that the package works for you. You can try using this small program below and make sure, when you run it using java, you do not get any error messages. Typically, if your classpath is not set correctly you would get error message like: Console class not found on import etc. Please make sure the corejava package is installed in CoreJavaBook Directory.

    //Begin Code Fragment
    import corejava.*;
    import java.text.*; 
    public class Mortgage 
        public static void main(String[] args
            double principal;
            double yearlyInterest;
            int years;
            principal = Console.readDouble("Loan amount (no commas):");
            yearlyInterest = Console.readDouble("Interest rate in % (ex: use 7.5 for 7.5%):")/100;
            years = Console.readInt("The number of years:");
            double monthlyInterest = yearlyInterest / 12;
            double payment = principal * monthlyInterest/(1 -    (Math.pow(1/(1 + monthlyInterest),years * 12)));
            System.out.println("Your payment is ");
            NumberFormat nf = NumberFormat.getCurrencyInstance();
    } // End of Code Fragment
Let’s talk about reading data first. Whenever you want to do Input / Output from the console, please be sure to include the following two packages: corejava Package (Provided on the website) and java.text package is part of the java compiler. Following are the two lines you must type in your source file

    import corejava.*;
    import java.text.*;

One of the classes in the corejava package is called Console. The Console class allows you to read data from the keyboard via console i.e. DOS or UNIX shell. The purpose of the Console class is to read various kinds of data like integers, floats and Strings. This is made possible by three method definitions inside the Console class.


Method Names are case sensitive. The Console class definition is located in the corejava subdirectory of CoreJavaBook Directory. So, let’s work towards reading in our first variable:

Let’s say we want to read a string into a variable.

    import corejava.*;
    import java.text.*;
    public class ReadString
            public static void main(string[] args)
               String myname;
               myname = Console.readLine("Please enter your name"):
               System.out.println("My name is " + myname);
In the above program, we declared a variable called myname of type String in line 5. To read a value into myname we go to line 6. Here we make a call to the method called readLine in the class called Console. The convention that you use for doing this is:


and hence, Console.readLine. You might have noticed in the class, that anytime call to a method is made, I have been using these brackets(). These brackets receive input into a method. Anyhow in Console.readLine(), we type a string that says "Please enter a name". Basically we are telling the Console.readLine() function to take this String as input and print it to the screen. After printing the String, it waits there with a flashing cursor. So, when the user types his/her name and hits enter, then that name is read by Console.readLine method. The name read by Console.readLine method is stored in the variable called myname. Essentially, the readLine method returns a value from the keyboard to myname. In Line 7 we print a "My name is" and concatenate it with the value of myname. So it should print:  

    My name is Sukhjit Singh

Now let’s practice reading in a number:

    //Reading an integer
    import corejava.*;
    import java.text.*;
    public class ReadNum
    public static void main(String[] args) 
             int num;
             num = Console.readInt("Please enter a number"):
             System.out.println("The number is " + num);
     //Reading a double
    import corejava.*;
    import java.text.*;
    public class ReadMcDouble
        public static void main(string[] args)
            double bigmac;
            bigmac = Console.readDouble("Enter the price of BigMac on Saturday"):
            System.out.println("I got a bigmac for " + bigmac);
Output with Java

You must wonder what is System.out.println all about. There is a package called System that has a class called out which in turn has a method called println. When we make a call to the println method, it prints the input, to the screen. For example,

    double x = 3333.33333;

Then the println method will print 3333.33333. In order to print a number to the screen, System.out.print (x) can be used. This command prints the value of the variable with the maximum number of non-zero digits of that type. For example,

    x = 10000 / 3.0;
    System.out.print (x);

Output would be 3333.3333333333335

There is a NumberFormat class in the java.text package that has three methods for giving standard formatters for currency, percentage values and numbers. In order, to print the output of x in the above formats, the formatter adds $ for currency symbols, % (percent) sign for percentage values and comma for numbers. The output of x would look like this:

    $3, 333.33
    333, 333%
One of the following methods can be used to obtain a formatter:

    NumberFormat.getCurrencyInstance ( );
    NumberFormat.getPercentInstance ( );
    NumberFormat.getNumbernstance ( );  

Each of these methods returns an object of type NumberFormat. You can use that object to format one or more numbers. Thereafter, you can apply the Format method to the NumberFormat object to get a String that contains the formatted number.

    double x = 10000.0 / 3.0;
    NumberFormat nf = NumberFormat.getNumberInstance( );
    String fx = nf.format (x); // string "3,333.33"
    System.out.println (x);
Additionally, if you wish to set the maximum and minimum of digits to be displayed, you can use following methods in the NumberFormat class:  


For example, the above code can be modified like this:

    double x = 10000.0 / 3.0;
    NumberFormat nf = NumberFormat.getNumberInstance( );
    String fx = nf.format (x); // string "3,333.33"
    System.out.println (x);  

Setting the number of integer digits is not very common because by specifying a minimum number, you force leading zeroes for smaller values and for larger values, the displayed value is truncated (giving wrong result). Setting the maximum number of fractional digits is very useful because the last displayed digit is rounded up, if the first discarded displayed digit is 5 or more. If you want to see trailing zeroes, set the minimum number of fractional digits to the same value as maximum. Otherwise, you should leave the minimum number of fractional digits at default value of 0.

Returns a NumberFormat object to convert currency values to strings like $:
    static NumberFormat getCurrencyInstance( );
Returns a NumberFormat object to format numbers like comma for thousand separator:
    static NumberFormat getNumberInstance( );
Returns a NumberFormat object to convert percentages to strings like 33%:
    static NumberFormat getPercentInstance( );
Sets the maximum number of digits after the decimal point for the Format object:
    void setMaximumFractionDigits (int digits);
Sets the minimum number of digits after the decimal point for the Format object. If the number has fewer fractional digits than the minimum, then trailing zeroes are supplied.
    void setMinimumFractionDigits (int digits);
Sets the maximum number of digits before the decimal point for the Format object. If you specify too few digits, then the number is truncated
    void setMaximumIntegerDigits (int digits);
Sets the minimum number of digits before the decimal point for the Format object. If the number has fewer digits than minimum, then leading zeroes are supplied
    void setMinimumIntegerDigits (int digits)

Using the corejava Format class

This is an easier and alternate way to print formatted numbers. Using Format.printf, we can print only one formatted value at a time. For example, to print a floating-point number with a width of 10 and two digits after the decimal point, you can use:

    Format.printf("Your monthly income is %10.2f\n", income);

Output would be:

    Your monthly income is 3.33

If you say %-10.2f, it would print 3.33 (left justified). In order to have percent sign in the output, you need to have %% in the format specification. Another common format is %nd to print an integer in a field with width n. For example, if you wish to print 5 with leading spaces, you can say %10d. It will print 5. Here are the rules for the formatting specifiers:

  1. The code starts with a % and ends with c, d, e, E, f, g, G, I, o, s, x, X
  2. f - for printing floating point numbers in a fixed format
  3. e, E - floating point numbers in exponential notation
  4. g, G - floating-point numbers in general format (fixed format for small numbers and exponential format for large numbers)
  5. d, i - for printing integers in decimal
  6. x - for printing integers in hexadecimal
  7. o - integers in octal
  8. s - for Strings
  9. c - for characters
In betweeen the % and the format code are the following fields (they are all optional):

  1. +- force display of + for positive numbers
  2. 0 - show leading zeroes
  3. - align left in the field
  4. space - prepend a space in front of the positive numbers

Here are few examples to illustrate the above:

    // Output - prints an integer 5
    int x = 5;
    Format.printf("This is a %d integer", x);
    // Output - prints - This is a string
    Format.printf("%s", "This is a string");
    // Output - prints x with 2 decimals and 6 leading spaces - 3.33
    float x = 3.33;
    Format.printf("This is a floating point %10.2f number", x);
    // Output - prints x with 2 decimals and 6 trailing spaces that is, left justified //number -3.33    
    float x = 3.33;
    Format.printf("This is a floating point %-10.2f number", x);

Here are some examples of the most commonly used conversion codes:

1. %10d (prints an integer using a width of 10)

2. %5i (prints an integer using a width of 5)

3. %10.2f (prints a floating number using a width of 10 and precision of 2). For example, a value of 1123.456 would print as 1123.45 and a value of 123.4 would print as 123.40

4.  %10.2e (prints a floating point number with e notation). For example, 1.12e + 003 (Lowercase e may be replaced by E)

5. %s (prints a string). For example, %500s (uses a width of 500 for printing a string)

6. %c (prints a character). For example, %5c would use 5 spaces for single character and %05s would use 5 spaces for printing a single character. But for the first four spaces it will print leading 0's.

7. %-15d would left align the number being printed with respect to width of 15. For example, a value of 95 would be printed as follows 95_ _ _ _ _ _ _ _ _ _ _ _ _ ("_" indicates a space)