Java Static Initializer Block

Sort by

recency

|

1456 Discussions

|

  • + 0 comments

    import java.util.*;

    public class Solution {

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

    }

  • + 0 comments
    public static void main (String[] args) throws Exception {
           Scanner scanner = new Scanner(System.in);
           int b = scanner.nextInt();
           int h = scanner.nextInt();
           
            if (b <= 0 || h <= 0){
            System.out.println(new Exception("Breadth and height must be positive"));
            return;
           }
           
           System.out.println(b * h);
        }
    
  • + 0 comments

    private String message; Solution(String message) { this.message=message; } @Override public String getMessage() { return message; }

    public static void main(String[] args) {
       Scanner sc=new Scanner(System.in);
       int b=sc.nextInt();
       sc.nextLine();
       int h=sc.nextInt();
       sc.close();
       if(b>0 && h>0)
       {
        System.out.println(b*h);
       }
       else
       {
        try{
            throw new Solution("java.lang.Exception: Breadth and height must be positive");
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }
       }
    }
    
  • + 0 comments

    ****Java logic for initializing a static block

      static  int B;
      static  int H;
           static  Scanner scan =  new Scanner(System.in);
    
        static{
            B  = scan.nextInt();
            H = scan.nextInt();
    				scan.close();
            if(B>0 && H>0)
            {
                System.out.println(B*H);
                
            }
            else{
                System.out.println("java.lang.Exception: Breadth and height must be positive");
            }
        }
    
  • + 0 comments
    import java.io.*;
    import java.util.*;
    
    public class Solution {
        static int a;
        static int b;
    
        static {
            Scanner sc = new Scanner(System.in);
            a = sc.nextInt();
            b = sc.nextInt();
            sc.close();
            if (a <= 0 || b <= 0) {
                System.out.println("java.lang.Exception: Breadth and height must be positive");
                throw new RuntimeException("numero negativo");
            }
        }
    
        public static void main(String[] args) {
            int area = a * b;
            System.out.println(area);
        }
    }