Java Static Initializer Block

Sort by

recency

|

1450 Discussions

|

  • + 0 comments

    Static✅+Exception handling✅

    import java.io.*;
    import java.util.*;
    
    public class Solution {
    
        static int B;
        static int H;
        static boolean flag;
    
        static {
            Scanner sc = new Scanner(System.in);
            B = sc.nextInt();
            H = sc.nextInt();
    
            try {
                if (B <= 0 || H <= 0) {
                    throw new Exception("Breadth and height must be positive");
                } else {
                    flag = true;
                }
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    
        public static void main(String[] args) {
            if (flag) {
                int area = B * H;
                System.out.println(area);
            }
        }
    }
    
  • + 0 comments
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    class myexp extends Exception{
        public myexp(String message){
            super(message);
        }
    }
    public class Solution{
        static void paralelo(int B,int H) throws myexp{
            if(B<=0 || H<=0){
               throw new myexp("Breadth and height must be positive"); 
            }
            int hei=B*H;
            System.out.println(hei);
            
        }
        public static void main(String[] args) {
            try{
                Scanner in = new Scanner(System.in);
                int a=in.nextInt();
                int b=in.nextInt();
                paralelo(a,b);
                }
            catch(myexp e){
                System.out.println("java.lang.Exception: "+e.getMessage());
            }
        }
    }
    
    
    
  • + 0 comments

    import java.io.; import java.util.;

    public class Solution {

    public static void main(String[] args) {
    
        Scanner sc=new Scanner(System.in);
        int x=sc.nextInt();
        int y=sc.nextInt();
    
        if(x>0 && y>0)
        {
             System.out.println(x*y); 
        }
    
        else
        {
            System.out.println("java.lang.Exception: Breadth and height must be positive");
        }
    }
    

    }

  • + 0 comments

    Here is my solution.

    -------------Static Code Block---------------------

    static int B, H; static boolean flag;

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

  • + 0 comments

    This exercise is a great way to understand how static initialization blocks work in Java. Cricketbuzz com login