Static initialization blocks - Hacker Rank Solution.

Static initialization blocks are executed when the class is loaded, and you can initialize static variables in those blocks.

You are given a class Solution with a main method. Complete the given code so that it outputs the area of a parallelogram with breadth  and height . You should read the variables from the standard input.

If  or  , the output should be "java.lang.Exception: Breadth and height must be positive" without quotes.

Input Format

There are two lines of input. The first line contains : the breadth of the parallelogram. The next line contains : the height of the parallelogram.

Output Format

If both values are greater than zero, then the main method must output the area of the parallelogram. Otherwise, print "java.lang.Exception: Breadth and height must be positive" without quotes.

Sample input 1

1
3

Sample output 1

3

Sample input 2

-1
2

Sample output 2

java.lang.Exception: Breadth and height must be positive

SOLUTION: -
import java.util.Scanner;

public class Solution {
    static int B, H;
    static boolean flag;

    static {
        Scanner sc = new Scanner(System.in);
        B = sc.nextInt();
        H = sc.nextInt();
        if (B > 0 && H > 0) {
            flag = true;
        } else {
            flag = false;
            System.out.println("java.lang.Exception: Breadth and height must be positive");
        }
    }

    public static void main(String[] args) {
        if (flag) {
            int area = B * H;
            System.out.println(area);
        }
    }
}


How It Works:

  • B and H are static variables for breadth and height.

  • The static block runs once when the class is loaded, even before main().

  • Input is read inside the static block using a Scanner.

  • If the values are valid, flag is set to true, and the area is calculated in main().

  • If not, an exception message is printed directly from the static block.

Popular posts from this blog

When a method in a subclass overrides a method in superclass, it is still possible to call the overridden method using super keyword - Hacker Rank Solution.

Java's System.out.printf function can be used to print formatted output. The purpose of this exercise is to test your understanding of formatting output using printf. To get you started, a portion of the solution is provided for you in the editor; you must format and print the input to complete the solution.