Pages

Friday, October 24, 2025

What is System.in and nextInt() ?

 Let’s break it down simply 👇

🧩 1. System.in

  • System is a built-in Java class that gives access to system-level input and output.

  • in is a static field inside the System class.

  • System.in represents standard input stream — usually the keyboard.

💡 In short:
System.in = the stream that takes input from the keyboard.


🧮 2. nextInt() (from Scanner class)

  • nextInt() is a method of the Scanner class.

  • It reads the next integer value from the input stream connected to the scanner.

Example:

import java.util.Scanner;

public class Example {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); // connect scanner to keyboard input
        System.out.print("Enter a number: ");
        int num = sc.nextInt();              // reads an integer from user
        System.out.println("You entered: " + num);
        sc.close();
    }
}

🔍 Step-by-step of what happens:

  1. new Scanner(System.in) → connects the scanner to keyboard input.

  2. sc.nextInt() → waits for the user to type an integer and press Enter.

  3. It reads that integer and stores it in a variable (like num).


🧠 Summary Table

Expression Type Meaning
System.in Input Stream Takes input from keyboard
new Scanner(System.in) Scanner Object Reads input from user
nextInt() Method Reads the next integer value entered

Would you like me to also explain what happens internally (how Java converts the typed number to an integer)?

No comments:

Post a Comment

Encode and Decode Strings - NeetCode.IO Solution by me + gemini pro 3.0 explained

  class Solution {         // encode: List of Strings -> String     public String encode ( List < String > strs) {         Stri...