Input and Output in Java

printlnprintfnextFloat

In the previous blog, we learned about the StringBuffer class in Java. If you want to know more about it, visit the StringBuffer class in Java. In this blog, we will go through the Input and Output statements in Java. Before going through the input and output in Java. First, let's understand what is input and output in a programming language. Input is nothing but the data that is sent to the computer for processing and output is nothing but the processed information sent out by the computer. Now coming to Java, input in Java is the data that is given to the program/code and the output is the data that we receive from the program in the form of result. In order to make the program more interesting we use input and output. To make input /output operations faster, Java uses the concept of Stream.

Reading Input in Java

In Java, printing output is a very easy task. We just need to call System.out.println and the output is displayed on the screen. But it is not the case with input, in order to read the input, we need to construct the Scanner class first that is attached to the System.in. In order to use the Scanner class we must import java. util. Scanner package. The statement is as follows:

import java.util.Scanner;

Once the Scanner class is imported, we need to create an object of the Scanner class as follows:

Scanner scanner = new Scanner(System.in);

In the above statement, the Scanner object is created with the argument System.in. Once the object is created, we can use that object for reading the input. There are various ways of reading input. For example, if the input has spaces between the lines, then we use nextLine. For example

e.g

System.out.println("Welcome to the Input and Output Blog");
String scanInput = scanner.nextLine();

To read a single line from an input we use next()

e.g

System.out.println("Welcome to the Input and Output Blog");
String scanInput = scanner.next();

Suppose if the input is of different datatypes, then that input can be read using the following methods:

  1. nextInt() - nextInt() is used when we want to read Integer.

    e.g

    System.outprintln("Enter the value of the integer");
    int count = in.nextInt();
  2. nextFloat() - nextFloat() can be used when we want to read the floating point values.

    e.g

    System.outprintln("Value of Pi");
    Float value = in.nextFloat();

    e.g

    import java.util.*;
    public class InputOutputEx {
        public static void main(String args[]) {
          Scanner scanner = new Scanner(System.in);
    
          System.out.println("Enter your full name : ");
          String strValue = scanner.nextLine();
          System.out.println("The value of String is:" + strValue);
          System.out.println("Enter the value : ");
          int intValue = scanner.nextInt();
          System.out.println("The value of Integer is:" + intValue);
    
          System.out.println("Enter the float value :");
          float floatValue = scanner.nextFloat();
          System.out.println("The value of Float is:" + floatValue);
    
          System.out.println("Enter the double value :");
          double doubleValue = scanner.nextDouble();
          System.out.println("The value of Double is:" + doubleValue);
      }
    }

    Output

    Enter your full name :
    abc
    The value of String is:abc
    Enter the value :
    10
    The value of Integer is:10
    Enter the float value :
    10.75
    The value of Float is:10.75
    Enter the double value :
    8577.08776886
    The value of Double is:8577.08776886

As we have seen earlier that the Scanner class is defined in the java.util package, so the import statement is included at the beginning of the program. We include the import statement only when we want to use the classes that are not defined in java.lang package.


Console class

There are times when we want to enter the password for some security purpose, then in that case the Scanner class cannot be used, because the input which we use in the Scanner class is plaintext which can be visible to anyone, due to which it can create a security breach. In order to solve this problem Java 6 has introduced a Console class for this purpose. Following is the example:

e.g

Console console = System.console();
String username = console.readLine(" Enter your User name: ");
char[] pass = console.readPassword(" Enter your Password: ");

To avoid a security breach, the Password is returned in an array of characters rather than the string. Once the processing of the password is done, we must override the array elements with the filler value. But the drawback of the Console class is that processing the input with the Console object is not as convenient as the Scanner object, because when we use the Console object we can only read one line at a time, which is not the case with Scanner object.


Formatting Output in Java

Unlike Input, displaying output is an easy task to do. In order to display the output or print the output on the console we just need to use System.out.prinln(). Following are the methods of print().

  1. print()

    print() method is used for printing the text on the console. It is the method of the PrintStream class which is overloaded. It takes a string as a parameter. After the string is printed, the cursor remains on the same line. It even works when you don't parse any parameters.

    Syntax

    public void print(String string);
  2. println()

    println is a modified version of print(). It is also used for printing the text on the console. It works like print(), but the only difference is that after printing the statement, the cursor jumps to the next line.

    Syntax

    public void println(String string);
  3. printf()

    printf() is used when we want to print the formatted string to the console.

    Syntax

    public PrintStream printf(String format, Object... args);

e.g

public class FormattingOutputEx {
  public static void main(String args[]) {
   int number = 99;
   char charEle  = 'J';
   String str = "Shortkicks";
   double doubleEle = 1345.67;
   float floatEle = 9.59f;
   System.out.println();
   System.out.println(number);
   System.out.println(charEle);
   System.out.print(str+"	");
   System.out.print(doubleEle + "	");
   System.out.print(floatEle);
   System.out.printf("'%s' %n", " javashortkicks");
  }
}

Output

99
J
Shortkicks  1345.67  9.59 'javashortkicks'

File Input and Output in Java

To read from the file we need to construct a Scanner object like the following

public PrintStream printf(String format, Object... args);

In the above statement UTF_8, character encoding is used. It is commonly used for files on the Internet. We must know the character encoding when we read a txt file. If we ignore the character encoding then it takes the default encoding. It is not good because the program may behave differently.

If the file contains a backslash then we must eliminate it by adding extra backslashes like the following

c:\\directory\\fileName.txt

Just like we use Scanner for reading from the text file, we use PrintWriter for writing to the file. We construct the PrintWriter object in the following way

PrintWriter output = new PrintWriter("atrowe.txt", StandardCharsets.UTF_8);

Here if the file doesn’t exist then it created the file.

e.g

import java.io.File;
import java.io.PrintWriter;

public class PrintWriterEx {
    public static void main(String args[]) {
        PrintWriter printWriter = new PrintWriter(System.out);
        printWriter.write("Java Shorkicks is a learning platform where you can learn");
        printWriter.flush();
        printWriter.close();

        PrintWriter printWriter1 =null;
        printWriter = new PrintWriter(new File("C:\atrowel.txt"));
        printWriter1.write("From basic concepts to advanced concepts of Java");

        printWriter1.flush();
        printWriter1.close();
    }
}
Get in Touch

Atrowel will be pleased to receive your feedback and suggestions. Those of you who would like to contribute, please send us an email.