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 [Link] for output. Great for students
starting interactive Java programs.
🖥️Output in Java
To print text or variables to the screen, we use:
java
CopyEdit
[Link]("Hello, World!");
[Link]("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 [Link]
package.
✏️Example:
java
CopyEdit
import [Link];
public class InputExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Enter your age: ");
int age = [Link]();
[Link]("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 [Link]() to clear the
newline character:
java
CopyEdit
int age = [Link]();
[Link](); // consume leftover newline
String name = [Link]();
✅ 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