JAVA - Zero to Hero / Java Fundamentals

Input and Output

❔ What is Input & Output (I/O)?

  • Input: Taking data from the user

  • Output: Showing results to the user

In Java, we use:

  • Scanner class for input

  • System.out.println() for output

🖨️ Output Using System.out.println()

This prints text on the screen and moves the cursor to the next line after printing.


🔸 Code Example:

System.out.println("Welcome to Java!");
System.out.println("This is output.");
Welcome to Java!
This is output.

🔍 Why use it?

✅ To display results or messages line by line, especially when printing separate outputs.


🖨️ Output Using System.out.print()

This prints text on the screen but does NOT move to the next line.

🔸 Code Example:

System.out.print("Welcome to ");
System.out.print("Java!");
Welcome to Java!

🔍 Why use it?

✅ When you want to continue output on the same line, like displaying progress, menus, or formatted output.


🔄 Difference Between print() and println()

Feature

System.out.print()

System.out.println()

Moves to next line?

❌ No

✅ Yes

Cursor position after print

Same line

Starts on a new line

Use case

Inline output (e.g., Name: John)

Separate lines for each output

Example

System.out.print("Hello ");

System.out.println("Hello");


📥 Input Using Scanner

The Scanner class (in java.util package) is used to take input from the keyboard.

🔸 Steps to Use Scanner:

  1. Import it: import java.util.Scanner;

  2. Create Scanner object: Scanner sc = new Scanner(System.in);

  3. Use methods like nextInt(), nextLine(), nextDouble() to get input

💻 Code Example: Taking Input

import java.util.Scanner;

public class Main {
    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.");
    }
}
Enter your name: xyz
Enter your age: 21
Hello xyz! You are 21 years old.

🔍 Common Scanner Methods

Method

Used for

Example

nextInt()

Integer input

int a = sc.nextInt();

nextDouble()

Decimal input

double d = sc.nextDouble();

next()

One word

String word = sc.next();

nextLine()

Full line input

String line = sc.nextLine();