Java Static Initializer Block

  • [deleted]
    + 1 comment
    public static Scanner sc = new Scanner(System.in);
    public static int B = sc.nextInt();
    public static int H = sc.nextInt();
    public static boolean flag = init2();
    
    
    private static boolean init2(){
        if(B<=0 || H<=0){
            System.out.println("java.lang.Exception: Breadth and height must be positive");
            return false;
        }
        return true;
    }
    

    Without try-catch block

    • + 0 comments

      static int B; static int H; static boolean flag=true; static { Scanner sc=new Scanner(System.in); B=sc.nextInt(); sc.nextLine(); H=sc.nextInt(); sc.close(); while(H<=0 || B<=0) { flag = false;

         System.out.println("java.lang.Exception: Breadth and height must be positive");
             break;
      }
      

      }

      This is more easy and working well.