Write about Java scanner class

Write about Java scanner class

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Write about Java scanner class
Write about Java scanner class

Write about Java scanner class

PROGRAM: Java scanner class

/* Java scanner class */

Java Scanner Class – Explanation, Syntax & Example Program

The Scanner class in Java is used to take input from the user.
It can read data like integers, strings, doubles, float, characters, and more directly from the keyboard.

In simple words:
👉 Scanner class allows your Java program to accept user input.


⭐ What is Scanner Class?

The Scanner class is part of java.util package.
It provides methods to read different types of values from:

  • Keyboard (most common)

  • Files

  • Strings

To use it, you must import it first.


📌 Importing Scanner Class

import java.util.Scanner;

This line tells Java that you want to use the Scanner class.


🧩 Syntax of Scanner Class

Scanner sc = new Scanner(System.in);
  • Scanner → class name

  • sc → object name (you can choose any name)

  • new Scanner() → creates the Scanner object

  • System.in → takes input from keyboard


🔍 Common Scanner Methods

Method Description
nextInt() Reads an integer
nextFloat() Reads a float value
nextDouble() Reads a double value
next() Reads a single word
nextLine() Reads a full line (including spaces)
nextBoolean() Reads true/false
nextLong() Reads long value
nextShort() Reads short value

🖥️ Example Program Using Scanner Class

Here is a simple program that takes name and age from the user:

import java.util.Scanner;

public class UserInputExample {
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print(“Enter your name: “);
String name = sc.nextLine();

System.out.print(“Enter your age: “);
int age = sc.nextInt();

System.out.println(“Hello ” + name + “, you are ” + age + ” years old.”);

sc.close();
}
}


🔍 Line-by-Line Explanation

import java.util.Scanner;

This imports the Scanner class for user input.

Scanner sc = new Scanner(System.in);

Creates a Scanner object named sc to take input from keyboard.

String name = sc.nextLine();

Reads a full line (name can include spaces).

int age = sc.nextInt();

Reads an integer value for age.

sc.close();

Closes the Scanner to free resources.


⭐ Uses of Scanner Class

  • Accepting form-like inputs

  • Taking choices in menu-driven programs

  • Reading numbers in math-based programs

  • Reading strings, characters, and boolean values

  • Beginner-friendly user interaction

Leave a Reply

Your email address will not be published. Required fields are marked *