Java Learning Guide – Input and Output in Java
Description:
This beginner-level guide explains how to get input from the user and display output in Java.
It uses the Scanner class for input and System.out.println for output. Great for students
starting interactive Java programs.
🖥️Output in Java
To print text or variables to the screen, we use:
java
CopyEdit
System.out.println("Hello, World!");
System.out.print("Enter your name: ");
println() moves to the next line.
print() keeps the cursor on the same line.
🔽 Input in Java using Scanner
To read user input in Java, we must import and use the Scanner class from the java.util
package.
✏️Example:
java
CopyEdit
import java.util.Scanner;
public class InputExample {
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.");
}
}
🧠 Common Scanner Methods
Method Reads Example Input
nextInt() Integer 25
nextDouble() Decimal number 5.75
next() Single word Hello
nextLine() Full line Hello there
🛑 Tip: Clear Input Buffer
When switching from nextInt() to nextLine(), add an extra sc.nextLine() to clear the
newline character:
java
CopyEdit
int age = sc.nextInt();
sc.nextLine(); // consume leftover newline
String name = sc.nextLine();
✅ Mini Project Idea
Create a Java program that:
Asks the user for their name
Asks their favorite color
Displays a greeting with that color and name