java
- IntroductionInstallation and SetupJava Syntax and StructureRunning Your First ProgramJava VariablesData Types in JavaOperators in JavaJava Input and OutputControl StatementsLoops in JavaMethods in Java (Functions)Arrays in JavaString Handling in JavaOOPS Concept in JavaClasses and ObjectsConstructor and Constructor Overloadingthis KeywordStatic MembersInheritanceAggregation in JavaMethod OverloadingMethod Overridingsuper KeywordFinal Keyword with Class, Method, and VariablesAccess Modifiers in javaEncapsulation in Java Polymorphism in JavaAbstraction in JavaAbstract ClassesInterfaces in JavaDifference between Abstract Class and Interface Nested and Inner Classes Exception HandlingJava PackagesWrapper Classes and AutoboxingJava Collections FrameworkFile Handling in JavaMultithreadingBasics of Java Memory Management and Garbage CollectionJava JDBC
Java Input/Output Tutorial for Beginners
Last Updated on: 21st Oct 2025 11:53:13 AM
Welcome to this beginner-friendly tutorial on Input and Output (I/O) in Java! Input and output are essential for interacting with users, reading data, and displaying results in a Java program. This tutorial will explain how to handle basic input (from the keyboard) and output (to the console) in Java, with clear explanations and examples tailored for beginners.
We’ll cover the basics of reading input using the Scanner class and displaying output using System.out. By the end, you’ll be able to create interactive programs that take user input and show results. Let’s get started!
What Are Input and Output in Java?
-
Input: Getting data from the user (e.g., typing a name or number via the keyboard).
-
Output: Displaying data to the user (e.g., printing text or results to the console/terminal).
-
In Java, the console is the text-based interface where output appears and input is entered.
Tools We’ll Use:
-
System.out: For printing output to the console.
-
Scanner class: For reading input from the keyboard.
Beginner Tip: Make sure to import the Scanner class with import java.util.Scanner; at the top of your program.
1. Output in Java
Java uses System.out to display output in the console. The two most common methods are:
-
System.out.println(): Prints text and adds a new line.
-
System.out.print(): Prints text without adding a new line.
Explanation
-
println: Stands for “print line.” After printing, the cursor moves to the next line.
-
print: Prints text and keeps the cursor on the same line.
-
You can print strings, numbers, or variables by combining them with +.
Example Code
Let’s print some messages to the console.
public class OutputExample {
public static void main(String[] args) {
// Printing text
System.out.println("Hello, World!"); // Prints and moves to next line
System.out.print("This stays ");
System.out.print("on the same line!"); // No new line
// Printing variables
int age = 20;
System.out.println("\nYour age is: " + age); // \n adds a new line
}
}
Output:
Hello, World!
This stays on the same line!
Your age is: 20
How to Run: Save as OutputExample.java, compile with javac OutputExample.java, and run with java OutputExample.
Real-World Analogy: Think of println as writing a sentence and hitting “Enter” on a typewriter, while print is writing without pressing “Enter.”
2. Input in Java
To read input from the user, we use the Scanner class from the java.util package. It can read different data types like strings, integers, and doubles.
Steps to Use Scanner
-
Import the Scanner class: import java.util.Scanner;.
-
Create a Scanner object: Scanner scanner = new Scanner(System.in);.
-
Use methods like nextLine(), nextInt(), or nextDouble() to read input.
Common Scanner Methods
|
Method |
Description |
Example Input |
|---|---|---|
|
nextLine() |
Reads a line of text (String) |
“Hello” |
|
nextInt() |
Reads an integer |
42 |
|
nextDouble() |
Reads a decimal number |
3.14 |
|
next() |
Reads a single word (String) |
“Java” |
Note: After reading a number with nextInt() or nextDouble(), you may need to clear the leftover “newline” character with scanner.nextLine() if reading a string afterward.
Example Code
Here’s a program that takes a user’s name and age as input and displays a greeting.
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
// Create Scanner object
Scanner scanner = new Scanner(System.in);
// Prompt for name
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // Read a line of text
// Prompt for age
System.out.print("Enter your age: ");
int age = scanner.nextInt(); // Read an integer
// Display output
System.out.println("Hello, " + name + "! You are " + age + " years old.");
// Close the scanner
scanner.close();
}
}
Sample Run:
Enter your name: Alice
Enter your age: 20
Hello, Alice! You are 20 years old.
Real-World Analogy: Think of Scanner as a cashier asking for your name and age to process a ticket.
3. Handling Different Data Types
You can use Scanner to read various data types. Here’s an example that reads a string, integer, and double.
import java.util.Scanner;
public class MixedInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read a string (e.g., favorite color)
System.out.print("Enter your favorite color: ");
String color = scanner.nextLine();
// Read an integer (e.g., number of pets)
System.out.print("How many pets do you have? ");
int pets = scanner.nextInt();
// Read a double (e.g., height in meters)
System.out.print("Enter your height in meters (e.g., 1.75): ");
double height = scanner.nextDouble();
// Output the results
System.out.println("Your favorite color is " + color + ".");
System.out.println("You have " + pets + " pet(s).");
System.out.println("Your height is " + height + " meters.");
scanner.close();
}
}
Sample Run:
Enter your favorite color: Blue
How many pets do you have? 2
Enter your height in meters (e.g., 1.75): 1.65
Your favorite color is Blue.
You have 2 pet(s).
Your height is 1.65 meters.
Beginner Tip: Always close the Scanner with scanner.close() to free resources, especially in larger programs.
4. Common Issues and Solutions
-
Problem: After nextInt() or nextDouble(), the next nextLine() skips input.
-
Cause: The “Enter” key leaves a newline character (\n) in the input buffer.
-
Solution: Add scanner.nextLine() after nextInt() or nextDouble() to clear the newline.
-
Example Fix
import java.util.Scanner;
public class InputFixExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
scanner.nextLine(); // Clear the newline
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Name: " + name + ", Age: " + age);
scanner.close();
}
}
Sample Run:
Enter your age: 25
Enter your name: Bob
Name: Bob, Age: 25
-
Problem: User enters invalid input (e.g., letters when expecting a number).
-
Solution: Use error handling (try-catch) for advanced programs (covered in later tutorials).
-
5. Combining Input and Output
Let’s create a simple calculator that takes two numbers as input, adds them, and displays the result.
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input first number
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
// Input second number
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
// Calculate and display result
double sum = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + sum);
scanner.close();
}
}
Sample Run:
Enter the first number: 5.5
Enter the second number: 3.2
5.5 + 3.2 = 8.7
Real-World Analogy: Like a vending machine: you input money (data), and it outputs a snack (result).
Practice Tips
-
Experiment: Modify the examples to read different data types or perform other calculations (e.g., multiply instead of add).
-
Test Code: Use an online Java compiler (e.g., Repl.it) to run and tweak programs.
-
Common Mistake: Don’t forget to import java.util.Scanner or close the Scanner.
-
Quiz Yourself: What happens if you use next() instead of nextLine() for a sentence? (Answer: Only the first word is read.)
Summary
-
Output: Use System.out.println() or System.out.print() to display text or variables.
-
Input: Use the Scanner class to read strings (nextLine, next), integers (nextInt), or decimals (nextDouble).
-
Best Practices: Clear newlines after nextInt/nextDouble, and close the Scanner.
-
Next Steps: Try combining input/output with operators (e.g., +, -) for more interactive programs.
You’re now ready to create interactive Java programs! Keep practicing, and happy coding! ![]()
.png)