java

Java Input/Output


Java Input Output

 

Input(Scanner Class) - In Java, the Scanner class is used to read user input from various sources, such as the keyboard (console input), files, or streams. 

Note: 

1) It is pre-defined class available in java.util package.

2) If we use Scanner class, must have to create object for Scanner class.

 

Creating a object 

Scanner scanner = new Scanner(System.in);

Explanation:

  • Scanner scanner = new Scanner(System.in); creates a Scanner object to read input from the standard input stream (System.in represents the keyboard input).
  • The Scanner class provides various methods to read different types of input.

                scanner.nextLine() -  reads a line of text entered by the user.

                scanner.nextInt() - reads an integer entered by the user.

                scanner.nextDouble() - reads an floating value entered by the user.

 

Output - System.out.print()

System-

1. It is a predefined or final class which is available in java.lang package. 
2. It provides access to system.

out-

1. It is a public and static member of the System class representing the standard output stream.
2. Available in java.lang.System package.

println()-

1. println() means "print line". It is a method which prints the text on your screen.
2. To access it, System.out keyword is used.
3. Available in java.io.PrintStream package.

Note:

The sentence written under it becomes visible to you on your console, when you run the program.

 

Example

import java.util.Scanner;

public class UserInputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine(); // Reads a line of text entered by the user

        System.out.print("Enter your age: ");
        int age = scanner.nextInt(); // Reads an integer entered by the user

		

		// printing the output
        System.out.println("Hello, " + name + "! You are " + age + " years old.");

        scanner.close(); // Closing the scanner
    }
}

 

  • scanner.close() - is used to close the scanner object after input operations are done (it's good practice to close the scanner to release resources).