Java Static Initializer Block

Sort by

recency

|

1403 Discussions

|

  • + 0 comments

    For educational institutions, this data might reveal patterns of widespread academic dishonesty that can inform future curriculum changes or adjustments in test design. For gaming platforms, it might provide insights into which forms of cheating are most prevalent ai tool, allowing for more targeted interventions.

  • + 0 comments
    static boolean flag;
    static int B,H;
    

    static {

    Scanner sc=new Scanner(System.in);
    flag=true;
    B=sc.nextInt();
    H=sc.nextInt();
    try{
    if (B<=0 || H<=0) throw new Exception("Breadth and height must be positive");
    }
    catch(Exception e) {System.out.println(e); flag=false; }
    sc.close(); 
    

    }

  • + 0 comments

  • + 0 comments

    Static initialization blocks are really handy for setting up conditions before a class is used. In this scenario, they're perfect for checking the values of breadth and height before calculating the area windaddy com login

  • + 0 comments
    import java.io.*;
    import java.util.*;
    
    public class Solution {
    
        private static boolean flag = true;
        private static int B;
        private static int H;
    
        static {
            try (Scanner scanner = new Scanner(System.in)) {
                B = scanner.nextInt();
                H = scanner.nextInt();
    
                if (B <= 0 || H <= 0) {
                    throw new Exception("Breadth and height must be positive");
                }
            } catch (Exception exception) {
                flag = false;
                System.out.println(exception);
            }       
        }
    
        public static void main(String[] args) {
            if(flag) {
                    int p=B*H;
                    System.out.print(p);
                }
            }
    }