Java Static Initializer Block


Problem Overview

Original Problem: Java Static Initializer Block | Hackerrank

Difficulty: Easy

Category: Basics / Static Blocks

Description: We are given two numbers as input which are meant to be the breadth and height of a parallelogram. Our task is to calculate the area of the parellalogram and print it . If either the breadth or height values are less than 1, print an error.

Understanding the Problem

We’re asked to read in a pair of integers and either print the area a parallelogram with those dimensions would have, or print an error. All of this is to be carried out within a static block.

Input:

Two integers, where:

  • The first integer is the breadth of a parallelogram

  • The second integer is the height of a parallelogram

Output:

The area where the inputs are both greater than one, otherwise print “java.lang.Exception: Breadth and height must be positive”

Initial Reasoning

Since the problem is designed to make us work with static blocks, we must use static variables to hold the breadth and height values. We'll validate these inside a static block, and only compute the area in the main function if the values are valid.

Pseudocode

// Static block:
    Read breadth and height from input
    If breadth or height are less than one
        Print the error

// Main function:
    If no error
        Print the area of the parallelogram

Solution Code

// Note this is one of many possible solutions
import java.util.Scanner;

public class Solution {

    // Declare static variables
    static int breadth;
    static int height;
    static boolean isValid= true; // Flag used to check that there hasnt been an error in static block

    // Static block runs when the class is loaded
    static {
        Scanner scanner = new Scanner(System.in);
        breadth = scanner.nextInt();
        height = scanner.nextInt();
        scanner.close();

        // Validate the inputs
        if (breadth <= 0 || height <= 0) {
            isValid= false;  // Set flag to false to prevent area calculation
            System.out.println("java.lang.Exception: Breadth and height must be positive");
        }
    }

    public static void main(String[] args) {
        // Only compute area if flag is true (i.e., valid inputs)
        if (isValid) {
            int area = breadth * height;
            System.out.println(area);
        }
    }
}