Object Oriented Programming With JavaUnit 127 min read
Java Utilities, Scanner, and System Classes
Unit 12 of Object Oriented Programming With Java covers Java’s built-in utility classes (Math, Random, System), the Scanner class for input handling, and their practical applications in real-world programs.
Key Concepts in Java Utilities and Scanner Class
1. Java Utility Classes
Java provides several utility classes in the java.util and java.lang packages to simplify common programming tasks. The most important ones are:
1.1 Math Class
- Provides mathematical functions (trigonometric, exponential, rounding, etc.).
- All methods are static, so no object creation is needed.
double sqrt = Math.sqrt(25); // 5.0
double power = Math.pow(2, 3); // 8.0
double round = Math.round(3.7); // 4
1.2 Random Class
- Generates pseudo-random numbers.
- Use
nextInt(),nextDouble(), etc., to get different ranges.
Random rand = new Random();
int randomInt = rand.nextInt(100); // 0-99
double randomDouble = rand.nextDouble(); // 0.0-1.0
1.3 System Class
- Provides access to system-level operations.
- Key methods:
System.out.println()(standard output)System.exit(0)(terminate program)System.currentTimeMillis()(current time in milliseconds)
long startTime = System.currentTimeMillis();
// ... some code ...
long endTime = System.currentTimeMillis();
System.out.println("Time taken: " + (endTime - startTime) + " ms");
2. Scanner Class
- Used for reading input from the user or files.
- Requires
import java.util.Scanner; - Common methods:
nextInt()→ reads integernextDouble()→ reads doublenextLine()→ reads entire line (including spaces)
Example: Reading User Input
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Hello, " + name + "! You are " + age + " years old.");
scanner.close(); // Always close scanner to avoid memory leaks
}
}
Output:
Enter your name: Ram
Enter your age: 20
Hello, Ram! You are 20 years old.
3. File Handling with Scanner
- Can read from files using
FileandScanner.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileScannerExample {
public static void main(String[] args) {
try {
File file = new File("data.txt");
Scanner fileScanner = new Scanner(file);
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
System.out.println(line);
}
fileScanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
}
}
Example File (data.txt):
Apple
Banana
Mango
Output:
Apple
Banana
Mango
In the Real World
eSewa & Khalti (Nepal)
- Use
Randomclass to generate OTP (One-Time Password) for transactions. - Example: When you request a payment, eSewa generates a 6-digit OTP using
Random.nextInt(1000000).
- Use
Pathao (Ride-Hailing App)
- Uses
Scannerto read user location input (latitude/longitude) from GPS. - Example: When you enter a destination, the app reads coordinates via
Scanner(or equivalent APIs).
- Uses
NTC (Nepal Telecom) Billing System
- Uses
Mathclass to calculate call duration charges (e.g., rounding seconds to minutes). - Example: If a call lasts 3.7 minutes,
Math.round(3.7)→ 4 minutes (charged accordingly).
- Uses
Visualizing Key Concepts
1. How Scanner Reads Input
flowchart TD
A["User Input\n(e.g., '25 3.14')"] --> B["Scanner.nextInt()\nReads '25'"]
B --> C["Scanner.nextDouble()\nReads '3.14'"]
C --> D["Stored in variables\nint num = 25;\ndouble pi = 3.14"]2. Random Number Generation
flowchart TD
A["Random rand = new Random()"] --> B["rand.nextInt(100)\n(0-99)"]
B --> C["rand.nextDouble()\n(0.0-1.0)"]
C --> D["Used in games, OTPs, simulations"]3. Math Class Operations
flowchart TD
A["Math.sqrt(25)"] --> B["5.0"]
A --> C["Math.pow(2, 3)"] --> D["8.0"]
A --> E["Math.round(3.7)"] --> F["4"]Exam Tip
- Scanner is frequently tested → Know how to read
int,double, andStringinputs. - File handling with Scanner → Always use
try-catchforFileNotFoundException. - Math class → Memorize key methods (
sqrt,pow,round,abs). - Random class → Useful for simulations, games, and security (OTPs).
- System class →
System.out.println()andSystem.exit()are common in exams.
Worked Example: Bank Interest Calculator
Problem: A bank offers 5% annual interest. Write a program to calculate the amount after 3 years if the principal is ₹10,000.
Solution:
import java.util.Scanner;
public class BankInterest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter principal amount: ");
double principal = scanner.nextDouble();
System.out.print("Enter annual interest rate (%): ");
double rate = scanner.nextDouble();
System.out.print("Enter years: ");
int years = scanner.nextInt();
double amount = principal * Math.pow(1 + rate / 100, years);
System.out.printf("Amount after %d years: ₹%.2f\n", years, amount);
scanner.close();
}
}
Input:
Enter principal amount: 10000
Enter annual interest rate (%): 5
Enter years: 3
Output:
Amount after 3 years: ₹11576.25
Explanation:
Math.pow(1 + rate/100, years)calculates compound interest.printfformats output to 2 decimal places.
Comparison Table: Utility Classes
| Class | Key Methods | Use Case |
|---|---|---|
Math |
sqrt(), pow(), round() |
Mathematical calculations |
Random |
nextInt(), nextDouble() |
Generating random numbers (OTPs, games) |
System |
out.println(), exit() |
System operations, time measurement |
Scanner |
nextInt(), nextLine() |
Reading user/file input |
Common Mistakes to Avoid
❌ Forgetting to close Scanner → Causes memory leaks.
❌ Using nextInt() after nextLine() without consuming newline → Leads to skipped input.
❌ Not handling FileNotFoundException → Program crashes if file doesn’t exist.
❌ Using Math.random() instead of Random class → Less flexible.
Practice Questions (Exam Style)
- Write a program to generate a 6-digit random OTP using
Random. - Read a student’s name, roll number, and marks from
Scannerand display them. - Calculate the area of a circle using
Math.PIandMath.pow(). - Read a file
students.txtand print all lines usingScanner.
Final Note:
Java utilities (Math, Random, System) and Scanner are essential for input/output, calculations, and file handling. Master these for full marks in exams and real-world applications! 🚀
Based on the TU BITM syllabus for Object Oriented Programming With Java (IT234), unit 12.
Discussion
Loading…