Output Statements in Java
Java provides several methods to display output to the console. These methods are part of the System.out object.
1. System.out.print()
Prints text without adding a new line at the end. The cursor remains on the same line.
System.out.print("Hello ");
System.out.print("World");
// Output: Hello World
2. System.out.println()
Prints text and moves cursor to the next line. This is the most commonly used output method.
System.out.println("Hello");
System.out.println("World");
// Output:
// Hello
// World
3. System.out.printf()
Provides formatted output using format specifiers. Useful for precise control over output formatting.
String name = "Alice";
int age = 25;
double marks = 85.5;
System.out.printf("Name: %s, Age: %d, Marks: %.2f%n", name, age, marks);
// Output: Name: Alice, Age: 25, Marks: 85.50
Input Statements in Java
Java provides various ways to read input from the user. The most common approach is using the Scanner class.
Why Scanner Class?
- Simple and easy to use
- Supports various data types
- Part of Java's standard library (java.util package)
- Provides methods for different input types
Using Scanner Class
The Scanner class is used to get user input from various sources like keyboard, files, etc.
Basic Steps:
- Import the Scanner class
- Create Scanner object
- Use appropriate method to read input
- Close the Scanner object
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
// Step 1: Create Scanner object
Scanner sc = new Scanner(System.in);
// Step 2: Read different types of input
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.print("Enter your height (in cm): ");
double height = sc.nextDouble();
// Step 3: Display the input
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Height: " + height + " cm");
// Step 4: Close the scanner
sc.close();
}
}
Scanner Class Methods
| Method | Description | Return Type | Example |
|---|---|---|---|
| nextInt() | Reads an integer value | int | int age = sc.nextInt(); |
| nextDouble() | Reads a double value | double | double price = sc.nextDouble(); |
| nextFloat() | Reads a float value | float | float temp = sc.nextFloat(); |
| next() | Reads a single word (till space) | String | String word = sc.next(); |
| nextLine() | Reads a complete line | String | String line = sc.nextLine(); |
| nextBoolean() | Reads a boolean value | boolean | boolean flag = sc.nextBoolean(); |
| nextLong() | Reads a long value | long | long bigNum = sc.nextLong(); |
| nextShort() | Reads a short value | short | short smallNum = sc.nextShort(); |
Practical Examples
Example 1: Student Information
import java.util.Scanner;
public class StudentInfo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("=== Student Information ===");
System.out.print("Enter student name: ");
String name = sc.nextLine();
System.out.print("Enter roll number: ");
int rollNo = sc.nextInt();
System.out.print("Enter marks in Math: ");
int mathMarks = sc.nextInt();
System.out.print("Enter marks in Science: ");
int scienceMarks = sc.nextInt();
System.out.print("Enter marks in English: ");
int englishMarks = sc.nextInt();
// Calculate total and average
int total = mathMarks + scienceMarks + englishMarks;
double average = total / 3.0;
// Display results
System.out.println("\n--- Student Report ---");
System.out.println("Name: " + name);
System.out.println("Roll No: " + rollNo);
System.out.println("Total Marks: " + total + "/300");
System.out.println("Average: " + average + "%");
sc.close();
}
}
Example 2: Temperature Converter
import java.util.Scanner;
public class TemperatureConverter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("=== Temperature Converter ===");
System.out.println("1. Celsius to Fahrenheit");
System.out.println("2. Fahrenheit to Celsius");
System.out.print("Enter your choice (1 or 2): ");
int choice = sc.nextInt();
if(choice == 1) {
System.out.print("Enter temperature in Celsius: ");
double celsius = sc.nextDouble();
double fahrenheit = (celsius * 9/5) + 32;
System.out.printf("%.2f°C = %.2f°F%n", celsius, fahrenheit);
} else if(choice == 2) {
System.out.print("Enter temperature in Fahrenheit: ");
double fahrenheit = sc.nextDouble();
double celsius = (fahrenheit - 32) * 5/9;
System.out.printf("%.2f°F = %.2f°C%n", fahrenheit, celsius);
} else {
System.out.println("Invalid choice!");
}
sc.close();
}
}
Common Issues and Solutions
Issue 1: nextLine() after nextInt()
When using nextLine() after nextInt(), the nextLine() might read the leftover newline character.
// Problem
System.out.print("Enter age: ");
int age = sc.nextInt();
System.out.print("Enter name: ");
String name = sc.nextLine(); // This might skip input
// Solution
System.out.print("Enter age: ");
int age = sc.nextInt();
sc.nextLine(); // Consume the leftover newline
System.out.print("Enter name: ");
String name = sc.nextLine();
Issue 2: Input Mismatch Exception
Occurs when the input doesn't match the expected data type.
import java.util.InputMismatchException;
import java.util.Scanner;
public class SafeInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.print("Enter an integer: ");
int number = sc.nextInt();
System.out.println("You entered: " + number);
} catch(InputMismatchException e) {
System.out.println("Invalid input! Please enter an integer.");
}
sc.close();
}
}
Best Practices
- Always close the Scanner to prevent resource leaks
- Use appropriate data types for the input you expect
- Handle exceptions when dealing with user input
- Provide clear prompts to guide the user
- Validate input before processing it
- Use meaningful variable names for input values
Summary
Key Points Covered:
- Output Methods: print(), println(), printf()
- Input Methods: Scanner class and its various methods
- Data Types: Different methods for different data types
- Common Issues: Input mismatch and newline problems
- Best Practices: Resource management and error handling