Java Static Initializer Block

Sort by

recency

|

1448 Discussions

|

  • + 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

  • + 0 comments

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

    public class Solution {

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

    }

  • + 0 comments

    import java.util.*;

    public class Solution {

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

    }