Java Tutorial - Input and Output Handling

"Unleash Java mastery! Elevate your coding game with our Java Tutorial on Input and Output Handling. Transform the way you write code. Dive in now! 🔥"

8 min read

Java Input and Output - Understanding Scanner, BufferedReader, and Console

Input and Output Handling

Java stands out as a highly utilized programming language renowned for its adaptability across diverse applications. A pivotal facet of programming involves managing user input and presenting information on the screen. In the realm of Java, multiple methods exist to navigate the realms of input and output. These include:

  • Using the Scanner class
  • Using the Buffered Reader class
  • Using the Console class

Let's briefly explore each method.

Using the Scanner Class

The Scanner division provides functionalities for acquiring input from the keyboard. It is housed within the java.util bundle, necessitating its importation before application.

```java

import java.util.Scanner;

```

To create an object of the Scanner class, we can use the following syntax:

```java

Scanner input = new Scanner(System.in);

```

In this context, we instantiate an unit named 'input,' designed to receive input from System.in, representing the basic input (keyboard). This 'input' object proves versatile, enabling the invocation of diverse procedures within the Scanner division. These procedure encompass:

  • `nextLine()`: to take input as a String
  • `nextInt()`: to take input as an int
  • `nextDouble()`: to take input as a double
  • `nextBoolean()`: to take input as a boolean
  • and so on

Example using the Scanner class:

```java

import java.util.Scanner;


public class StudentData {


    public static void main(String[] args) {

        // variable declaration

        String name, studentId, major;

        double gpa;


        // create a new scanner

        Scanner input = new Scanner(System.in);


        // display output to the user

        System.out.println("### Student Data ###");

        System.out.print("Name: ");

        name = input.nextLine();

        System.out.print("Student ID: ");

        studentId = input.nextLine();

        System.out.print("Major: ");

        major = input.nextLine();

        System.out.print("GPA: ");

        gpa = input.nextDouble();


        // display output again

        System.out.println("--------------------");

        System.out.println("Name: " + name);

        System.out.println("Student ID: " + studentId);

        System.out.println("Major: " + major);

        System.out.println("GPA: " + gpa);

    }

}

```

Output:

```

### Student Data ###

Name: John Doe

Student ID: 1234567890

Major: Computer Science

GPA: 3.8

--------------------

Name: John Doe

Student ID: 1234567890

Major: Computer Science

GPA: 3.8

```

Using the BufferedReader Class

The BufferedReader division finds its purpose in reading data from various sources, including files, sockets, or the keyboard. It is situated within the java.io bundle, necessitating its importation prior to utilization.

```java

import java.io.BufferedReader;

import java.io.InputStreamReader;

```

To create an object of the BufferedReader class, we can use the following syntax:

```java

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

```

In this instance, we instantiate an object named 'input,' tasked with retrieving data from System.in, representing the standard input (keyboard). This 'input' object proves valuable for invoking the readLine() method, which yields input in the form of a String. Should the need arise to obtain input in other data variety, conversion becomes imperative. This involves actions like:

  • `Integer.parseInt(input.readLine())`: to take input as an int
  • `Double.parseDouble(input.readLine())`: to take input as a double
  • `Boolean.parseBoolean(input.readLine())`: to take input as a boolean
  • and so on

Example using the BufferedReader class:

```java

import java.io.BufferedReader;

import java.io.InputStreamReader;


public class StudentData {


    public static void main(String[] args) throws Exception {

        // variable declaration

        String name, studentId, major;

        double gpa;


        // create a new buffer reader

        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));


        // display output to the user

        System.out.println("### Student Data ###");

        System.out.print("Name: ");

        name = input.readLine();

        System.out.print("Student ID: ");

        studentId = input.readLine();

        System.out.print("Major: ");

        major = input.readLine();

        System.out.print("GPA: ");

        gpa = Double.parseDouble(input.readLine());


        // display output again

        System.out.println("--------------------");

        System.out.println("Name: " + name);

        System.out.println("Student ID: " + studentId);

        System.out.println("Major: " + major);

        System.out.println("GPA: " + gpa);

    }

}

```

Output:

```

### Student Data ###

Name: Jane Doe

Student ID: 0987654321

Major: Electrical Engineering

GPA: 3.5

--------------------

Name: Jane Doe

Student ID: 0987654321

Major: Electrical Engineering

GPA: 3.5

```

Using the Console Class

The Console class serves as a means for engaging with users via the console. It is part of the java.io package, requiring prior importation before application.

```java

import java.io.Console;

```

To create an object of the Console class, we can use the following syntax:

```java

Console input = System.console();

```

In this context, we establish an object named 'input,' dedicated to receiving input from System.console(), representing the active console. This 'input' entity proves versatile, allowing the utilization of diverse methods within the Console class. These methods include:

  • `readLine()`: to take input as a String
  • `readLine(String format, Object... args)`: to take input as a String with a specific format
  • `readPassword()`: to take input as a char[] without displaying what is typed
  • `readPassword(String format, Object... args)`: to take input as a char[] without displaying what is typed with a specific format
  • and so on

Example using the Console class:

```java

import java.io.Console;


public class StudentData {


    public static void main(String[] args) {

        // variable declaration

        String name, studentId, major;

        double gpa;


        // create a new console

        Console input = System.console();


        // display output to the user

        System.out.println("### Student Data ###");

        name = input.readLine("Name: ");

        studentId = input.readLine("Student ID: ");

        major = input.readLine("Major: ");

        gpa = Double.parseDouble(input.readLine("GPA: "));


        // display output again

        System.out.println("--------------------");

        System.out.println("Name: " + name);

        System.out.println("Student ID: " + studentId);

        System.out.println("Major: " + major);

        System.out.println("GPA: " + gpa);

    }

}

```

Output:

```

### Student Data ###

Name: Jack Smith

Student ID: 5678901234

Major: Mechanical Engineering

GPA: 3.2

--------------------

Name: Jack Smith

Student ID: 5678901234

Major: Mechanical Engineering

GPA: 3.2

```

Conclusion

In this article, we've delved into Java input and output, comprehending the process of receiving input from users and showcasing output on the screen. We've gained knowledge that three classes—Scanner, BufferedReader, and Console—serve as tools for managing input and output in Java. Each class possesses its own set of merits, drawbacks, and distinct usage methods. The article also provides code examples showcasing the application of these classes. Through a comprehensive understanding of Java input and output handling, we can craft programs that are more engaging and dynamically responsive.


Post a Comment
Search
Menu
Theme
Share