IT234 Object Oriented Programming with Java

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:

  • Scanner class reads formatted input from sources like System.in, File, or String.
  • Math class provides mathematical functions (trigonometry, rounding, constants) without object creation.
  • Random class generates pseudo-random numbers for simulations, games, or security tokens.
  • System class manages standard I/O streams (in, out, err) and system properties.
  • Arrays utility class simplifies array operations (sorting, searching, filling).
  • StringTokenizer and StringJoiner parse 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

  1. Create a Scanner object linked to an input source.
  2. Use methods like nextInt(), nextDouble(), nextLine() to read input.
  3. 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

  1. Create a Random object (seeded for reproducibility).
  2. Use methods like nextInt(), nextDouble(), or nextBoolean().
  3. 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:

  1. Short Questions (5-10 marks):

    • Define Scanner, Math.random(), or Arrays.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();
  2. Programming Questions (20-30 marks):

    • Write a complete program to:
      • Read 5 integers and find the largest using Scanner and Math.max().
      • Generate 10 random numbers between 1 and 100.
      • Sort an array and print it using Arrays.sort().
    • Trace execution of a given code snippet (e.g., Arrays.binarySearch).
  3. Application-Based Questions (10-15 marks):

    • Explain how Random is used in online gaming (e.g., loot boxes).
    • Describe how StringTokenizer helps in parsing CSV files (e.g., bank transactions).
    • Compare System.out and System.err in error logging.

Common Pitfalls:

  • Forgetting to close Scanner when reading from files.
  • Using Math.random() without multiplying by range (e.g., random * 100 for 0-100).
  • Confusing nextLine() (reads entire line) with next() (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:

  1. Import statement (import java.util.Scanner;).
  2. Class and main method.
  3. Scanner initialization (Scanner scanner = new Scanner(System.in);).
  4. Input reading (int a = scanner.nextInt();).
  5. Sum calculation (int sum = a + b + c;).
  6. Output (System.out.println("Sum: " + sum);).
  7. Scanner close (scanner.close();).

In the Real World

  1. 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).
  2. Pathao (Ride-Hailing App):

    • Generates unique ride codes using Random.nextInt() for security.
    • Sorts driver locations with Arrays.sort() to optimize ride assignments.
  3. Nepse (Stock Exchange):

    • Calculates dividend yields using Math.pow() for compound interest projections.
    • Logs system errors to System.err for real-time monitoring.
  4. Khalti (Digital Wallet):

    • Parses transaction logs with StringTokenizer to extract UserID and Amount.
    • Joins multiple payments into a single string for reporting using StringJoiner.
  5. NTC (Telecommunications):

    • Uses Arrays.binarySearch() to quickly locate subscriber data in sorted databases.
    • Logs network errors to System.err for debugging.

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…