❔ What is Input & Output (I/O)?
Input: Taking data from the user
Output: Showing results to the user
In Java, we use:
Scannerclass for inputSystem.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 |
|
|
|---|---|---|
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 |
|
|
📥 Input Using Scanner
The Scanner class (in java.util package) is used to take input from the keyboard.
🔸 Steps to Use Scanner:
Import it: import java.util.Scanner;
Create Scanner object: Scanner sc = new Scanner(System.in);
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 |
|---|---|---|
| Integer input |
|
| Decimal input |
|
| One word |
|
| Full line input |
|