Object Oriented Programming with JavaUnit 1213 min read
Java Utilities, Scanner, and System Classes
Unit 12 of Object Oriented Programming with Java covers the java.util package, Scanner class for input handling, and utility classes like Math, Random, and System. Learn how to read user input, generate random numbers, format output, and use built-in utilities for efficient programming.
TAKEAWAYS:
Scannerclass reads formatted input from sources likeSystem.in,File, orString.Mathclass provides mathematical functions (trigonometry, rounding, constants) without object creation.Randomclass generates pseudo-random numbers for simulations, games, or security tokens.Systemclass manages standard I/O streams (in,out,err) and system properties.Arraysutility class simplifies array operations (sorting, searching, filling).StringTokenizerandStringJoinerparse and format strings efficiently.
1. Introduction to Java Utilities
Java’s java.util package contains utility classes for common programming tasks. These classes are predefined and ready-to-use, saving time and reducing code complexity.
Key Utility Classes
| Class | Purpose |
|---|---|
Scanner |
Reads input from various sources (keyboard, files, strings). |
Math |
Provides mathematical functions (e.g., sin(), sqrt(), random()). |
Random |
Generates pseudo-random numbers. |
System |
Manages standard I/O streams and system properties. |
Arrays |
Simplifies array operations (sorting, searching). |
StringTokenizer |
Splits strings into tokens (e.g., by delimiters). |
StringJoiner |
Joins strings with a delimiter (e.g., "a,b,c"). |
2. Scanner Class: Reading Input
The Scanner class reads input from sources like System.in (keyboard), files, or strings. It supports primitive data types (int, double, boolean) and strings.
How Scanner Works
- Create a
Scannerobject linked to an input source. - Use methods like
nextInt(),nextDouble(),nextLine()to read input. - Close the scanner (if reading from a file) to free resources.
Example: Reading User Input
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Read from keyboard
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // Reads entire line
System.out.print("Enter your age: ");
int age = scanner.nextInt(); // Reads integer
System.out.println("Hello, " + name + "! You are " + age + " years old.");
scanner.close(); // Close scanner
}
}
Output:
Enter your name: Ram
Enter your age: 20
Hello, Ram! You are 20 years old.
Common Scanner Methods
| Method | Description | Example Input → Output |
|---|---|---|
nextInt() |
Reads an integer. | 42 → 42 |
nextDouble() |
Reads a double. | 3.14 → 3.14 |
nextLine() |
Reads an entire line (including spaces). | "Hello" → "Hello" |
next() |
Reads next token (stops at whitespace). | "Java" → "Java" |
hasNextInt() |
Checks if next token is an integer. | "123abc" → true |
Real-World Example: eSewa Transaction Input
eSewa uses Scanner-like input handling (via web forms or APIs) to:
- Read user-entered amounts (e.g.,
nextDouble()for transaction fees). - Validate phone numbers (e.g.,
nextLine()followed by regex checks). - Process payment details securely.
3. Math Class: Mathematical Operations
The Math class provides static methods for common mathematical operations. No object creation is needed.
Key Math Methods
| Method | Description | Example |
|---|---|---|
sqrt(x) |
Square root of x. |
Math.sqrt(16) → 4.0 |
pow(x, y) |
x raised to y. |
Math.pow(2, 3) → 8.0 |
random() |
Random double in [0.0, 1.0). |
Math.random() → 0.5488 |
round(x) |
Rounds x to nearest integer. |
Math.round(3.6) → 4 |
max(x, y) |
Returns the larger of x or y. |
Math.max(5, 10) → 10 |
sin(x) |
Sine of x (in radians). |
Math.sin(Math.PI/2) → 1.0 |
Example: Calculating Compound Interest
public class InterestCalculator {
public static void main(String[] args) {
double principal = 10000; // Initial amount
double rate = 5.0; // Annual interest rate (%)
int years = 10; // Time period
// Compound interest formula: A = P * (1 + r)^t
double amount = principal * Math.pow(1 + rate/100, years);
double interest = amount - principal;
System.out.printf("Total amount after %d years: %.2f%n", years, amount);
System.out.printf("Interest earned: %.2f%n", interest);
}
}
Output:
Total amount after 10 years: 16288.95
Interest earned: 6288.95
Real-World Tie-In: Nepal’s Nepse (Nepal Stock Exchange) uses similar calculations to compute dividend yields for investors. For example:
- If a stock pays 5% annual dividend,
Math.pow(1.05, 5)calculates its value after 5 years.
4. Random Class: Generating Random Numbers
The Random class generates pseudo-random numbers for simulations, games, or security tokens.
How Random Works
- Create a
Randomobject (seeded for reproducibility). - Use methods like
nextInt(),nextDouble(), ornextBoolean(). - Set a seed (optional) for consistent results in testing.
Example: Dice Roll Simulator
import java.util.Random;
public class DiceRoll {
public static void main(String[] args) {
Random random = new Random();
int roll = random.nextInt(6) + 1; // 1-6
System.out.println("You rolled: " + roll);
}
}
Output (example):
You rolled: 4
Real-World Example: Pathao Ride Allocation
Pathao uses Random-like algorithms to:
- Assign drivers to nearby riders (randomized but optimized).
- Generate unique ride codes (e.g.,
RANDOM_12345) for security.
5. System Class: Standard I/O and Properties
The System class provides access to:
- Standard I/O streams (
in,out,err). - System properties (e.g., OS name, Java version).
Key System Methods
| Method/Field | Description | Example |
|---|---|---|
System.out |
Standard output (console). | System.out.println("Hi"); |
System.in |
Standard input (keyboard). | Scanner scanner = new Scanner(System.in); |
System.err |
Standard error stream. | System.err.println("Error!"); |
System.exit(0) |
Terminates the program. | System.exit(0); |
getProperty("key") |
Gets system properties (e.g., OS name). | System.getProperty("os.name") → "Windows" |
Example: Printing to Error Stream
public class SystemExample {
public static void main(String[] args) {
System.out.println("This is standard output.");
System.err.println("This is an error message!");
System.out.println("Java version: " + System.getProperty("java.version"));
}
}
Output:
This is standard output.
This is an error message!
Java version: 17.0.1
Real-World Example: NTC Traffic Route Optimization
NTC (Nepal Telecommunications) uses System-like logging to:
- Track network errors (
System.err) in real-time. - Log system properties (e.g., server uptime) for maintenance.
6. Arrays Utility Class
The Arrays class provides static methods for array manipulation.
Key Arrays Methods
| Method | Description | Example |
|---|---|---|
sort(array) |
Sorts an array in ascending order. | Arrays.sort(arr); |
binarySearch(array, key) |
Searches for key in a sorted array. |
Arrays.binarySearch(arr, 5); |
toString(array) |
Returns a string representation of the array. | Arrays.toString(arr); |
fill(array, value) |
Fills all elements of array with value. |
Arrays.fill(arr, 0); |
Example: Sorting and Searching
import java.util.Arrays;
public class ArraysExample {
public static void main(String[] args) {
int[] numbers = {5, 2, 9, 1, 5};
Arrays.sort(numbers); // Sorts: [1, 2, 5, 5, 9]
System.out.println("Sorted array: " + Arrays.toString(numbers));
int index = Arrays.binarySearch(numbers, 5); // Returns 2 or 3
System.out.println("Index of 5: " + index);
}
}
Output:
Sorted array: [1, 2, 5, 5, 9]
Index of 5: 2
Real-World Example: Daraz Order Processing
Daraz uses Arrays-like sorting to:
- Rank products by sales (e.g.,
Arrays.sort(productsByPrice)). - Search inventory efficiently (e.g.,
Arrays.binarySearch(stock, "Laptop")).
7. StringTokenizer and StringJoiner
StringTokenizer: Splitting Strings
Splits a string into tokens based on a delimiter.
import java.util.StringTokenizer;
public class StringTokenizerExample {
public static void main(String[] args) {
String data = "Java,Programming,OOP";
StringTokenizer tokenizer = new StringTokenizer(data, ",");
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
}
}
Output:
Java
Programming
OOP
Real-World Example: Khalti Transaction Logs
Khalti parses transaction logs using StringTokenizer-like methods to:
- Split payment details (e.g.,
"UserID:123,Amount:500"→["123", "500"]).
StringJoiner: Combining Strings
Joins strings with a delimiter.
import java.util.StringJoiner;
public class StringJoinerExample {
public static void main(String[] args) {
StringJoiner joiner = new StringJoiner(", ");
joiner.add("Apple").add("Banana").add("Orange");
System.out.println(joiner); // "Apple, Banana, Orange"
}
}
Real-World Example: WhatsApp Group Messages
WhatsApp uses StringJoiner-like logic to:
- Format group mentions (e.g.,
@Ram, @Shyam, @Sita).
8. Exam Tip
What to Expect in TU/PU Exams:
Short Questions (5-10 marks):
- Define
Scanner,Math.random(), orArrays.sort(). - Write a single line of code to read an integer or generate a random number.
- Example:
"Write a line of code to read a double from the user using
Scanner." Answer:double num = scanner.nextDouble();
- Define
Programming Questions (20-30 marks):
- Write a complete program to:
- Read 5 integers and find the largest using
ScannerandMath.max(). - Generate 10 random numbers between 1 and 100.
- Sort an array and print it using
Arrays.sort().
- Read 5 integers and find the largest using
- Trace execution of a given code snippet (e.g.,
Arrays.binarySearch).
- Write a complete program to:
Application-Based Questions (10-15 marks):
- Explain how
Randomis used in online gaming (e.g., loot boxes). - Describe how
StringTokenizerhelps in parsing CSV files (e.g., bank transactions). - Compare
System.outandSystem.errin error logging.
- Explain how
Common Pitfalls:
- Forgetting to close
Scannerwhen reading from files. - Using
Math.random()without multiplying by range (e.g.,random * 100for 0-100). - Confusing
nextLine()(reads entire line) withnext()(reads until whitespace). - Not sorting an array before using
Arrays.binarySearch().
Model Answer Structure:
For a 10-mark question like "Write a program to read 3 integers and print their sum using Scanner," structure your answer as:
- Import statement (
import java.util.Scanner;). - Class and
mainmethod. - Scanner initialization (
Scanner scanner = new Scanner(System.in);). - Input reading (
int a = scanner.nextInt();). - Sum calculation (
int sum = a + b + c;). - Output (
System.out.println("Sum: " + sum);). - Scanner close (
scanner.close();).
In the Real World
eSewa (Nepal):
- Uses
Scanner-like input validation to ensure transaction amounts are numeric before processing payments. - Employs
Math.round()to format currency (e.g.,Rs. 500.999→Rs. 501).
- Uses
Pathao (Ride-Hailing App):
- Generates unique ride codes using
Random.nextInt()for security. - Sorts driver locations with
Arrays.sort()to optimize ride assignments.
- Generates unique ride codes using
Nepse (Stock Exchange):
- Calculates dividend yields using
Math.pow()for compound interest projections. - Logs system errors to
System.errfor real-time monitoring.
- Calculates dividend yields using
Khalti (Digital Wallet):
- Parses transaction logs with
StringTokenizerto extractUserIDandAmount. - Joins multiple payments into a single string for reporting using
StringJoiner.
- Parses transaction logs with
NTC (Telecommunications):
- Uses
Arrays.binarySearch()to quickly locate subscriber data in sorted databases. - Logs network errors to
System.errfor debugging.
- Uses
Visuals
1. Scanner Input Flow
flowchart TD
A["User Enters Input"] --> B["Scanner.nextInt()"]
B --> C["Stores in Variable"]
C --> D["Program Uses Value"]
D --> E["Scanner.close()"]2. Math.random() Range Calculation
flowchart TD
A["Math.random()"] --> B["0.0 ≤ x < 1.0"]
B --> C["Multiply by Range"]
C --> D["x * 100 → 0 ≤ x < 100"]
D --> E["Add Offset"]
E --> F["x + 1 → 1 ≤ x ≤ 100"]3. Arrays.sort() Before/After
4. StringTokenizer Example
5. System.out vs. System.err
flowchart TD
A["System.out"] --> B["Standard Output\nConsole"]
C["System.err"] --> D["Standard Error\nError Logs"]
B --> E["Used for Normal Output"]
D --> F["Used for Errors/Warnings"]Based on the TU BIM syllabus for Object Oriented Programming with Java (IT234), unit 12.
Discussion
Loading…