Java Static Initializer Block

  • + 47 comments

    Remember, you need to either use a try catch block or add "throws (Exception)" to a method name in order to throw a checked exception. In this case, there is no method name for the static initializer block, so you must use a try catch!

    See code below:

    MyCode{

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

    }

    • + 1 comment

      Great example! :)

      • + 7 comments

        how multiplication result comes automatically?

        • + 7 comments

          static boolean flag=true;

          static int B,H;

          static {

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

          }

          • + 1 comment

            Instead of using or you can use multiplication i.e, if bh<0 the string is printed. This is better because, if we extend the code this format will be better to debug.

            • + 1 comment

              we should not use bh<0 condition because if b and h both are negative, then your code will set flag as true which is incorrect

              • + 1 comment

                we cant use this as if both b & h are negative the condition will get true which should not be happen

                • + 3 comments

                  image

                  if both b & h are negative the condition will get false and it throw the exception

                  • + 0 comments

                    why do we need flag in this to true can we use and operator insted of or .................................please help

                  • + 0 comments

                    I found twice repeating "java.lang.Exception:" in your code. Line 17 should be corrected as : throw new Exception("Breadth and height must be positive");

                  • + 0 comments

                    static int B,H; static boolean flag = true; static Scanner scan = new Scanner(System.in); static{ B = scan.nextInt(); scan.nextLine(); H = scan.nextInt(); scan.close();

                    if(B<= 0 || H<=0){
                        flag = false;
                        System.out.println("java.lang.Exception: Breadth and height must be positive");
                    }
                    

                    }

                    This works fine.

          • + 1 comment

            Code is working but how you are calculating the area .

            • + 2 comments

              Area is calculated in the main method. Expand the code and you will find it! :)

              • + 0 comments

                thank you

              • + 0 comments

                cool...

          • + 1 comment

            Why can't we put boolean flag = true; and int B,H; in the static block??

            • + 5 comments

              No You can't do that because we need to reference the variables in main method,as main method is non-editable.so the only option you have that while compiling, when JVM loads (.class) file in the memory intialize all those variables at the same time that can be done when you declare variables as static.

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

              Note: variables inside the static block is not static.

              • + 1 comment

                why are we using the boolean variable flag?

                • + 0 comments

                  alredy given flag in main function as a conditon for if so we should use flag

              • + 1 comment

                how to access the main class??

                • + 0 comments

                  Click on arrow you will find the full part of main class.

              • + 3 comments

                i have used the same code, still getting errors...

                .java:36: error: class, interface, or enum expected public static void main(String[] args){ ^ .java:39: error: class, interface, or enum expected System.out.print(area); ^ .java:40: error: class, interface, or enum expected } ^

                I'm not getting this error...plz help me out.

                • + 1 comment

                  System.out.print(area); ?????

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

                  paste the same code,complied and tested and let me know!

                  • + 1 comment

                    i did the same thing but got an error class,enum or interface expected.pls help me

                    • + 0 comments

                      i also did exactly same but i am getting error

                • + 1 comment

                  Do not close class before main. There is closing parenthesis for class after main.

                  • + 0 comments

                    Thanks a ton! It Worked for me.

              • + 0 comments

                its showing semicolan expected

              • + 0 comments

                thank u

          • + 1 comment

            I tried doing it that way but it went wrong, so I had to take the:

            Scanner scan = new Scanner(System.in);
            
            B = scan.nextInt();
            
            H = scan.nextInt();
            

            out of the block.

            Why is it?

            • + 1 comment

              No You can't do that because we need to reference the variables in main method,as main method is non-editable.so the only option you have that while compiling, when JVM loads (.class) file in the memory intialize all those variables at the same time that can be done when you declare variables as static.

              • + 0 comments

                Thanks, that helps a lot to understand how it works

          • + 0 comments

            It works vs this static Scanner input = new Scanner(System.in); static boolean flag = true; static int B = input.nextInt(); static int H = input.nextInt();

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

            }

          • + 0 comments

            end class erorr

          • + 0 comments

            why are we defining the B and H two times like first in the starting with static keyword and again in scanner? scan.nextInt() is also saying the same thing that B is of integer type, Please explain

        • + 0 comments

          if you hover you cursor at the bottom of the unmodifiable code, you'll see facing both left and right which you can expand. There you'll see the given multiplication

        • + 0 comments

          kindly open main().

        • + 0 comments

          Expant main method.

        • + 0 comments

          It doesn't come automatically. The code for multiplication to print the area is written in the Hidden Stub in the main function. You can expand and see the hidden code by clicking on the arrow that appears near line number.

        • + 0 comments

          that was present in the main see

    • + 4 comments

      This problem does not require exceptions. It's actually way easier without them.

      • + 1 comment

        Very true, but it asks us to display a message indicating that an exception has been thrown, which I think implies that we're supposed to use exceptions.

        • [deleted]
          + 0 comments

          The challenge explicitly asks for a particular message to be printed, which includes 'java.lang.Exception'. Absolutely terrible spec, but we should do what we're told :)

      • + 1 comment

        This problem would be way easier without the unrealistic restraints put on it. 6 years of programming and I've never once had to use a static block like this haha

        • + 5 comments

          can you show me the way without exception?tks

          • + 6 comments

            Like this:

            public static int B = 1;
            public static int H = 1;
            public static boolean flag = true;
            static {
            	Scanner scan = new Scanner(System.in);
            	B = scan.nextInt();
            	H = scan.nextInt();
            	scan.close();
            	if (B <= 0 || H <= 0) {
            		flag = false;
            		System.out.println("java.lang.Exception: Breadth and height must be positive");
            	}
            }
            
            • + 2 comments

              Your answer is fail to pass the 6th test case.!!

              image

              • + 1 comment

                Sorry. It should be "if (B <= 0 || H <= 0)". You can try again.

                • + 0 comments

                  It is the same thing. And Answer comes by this.

              • + 1 comment

                Test 6 is testing for the upper bound of < 100. If you look in the constraints you will see that the number entered must be greater than -100 and less than 100. The test is failing because it tests a height of 100. The crazy thing that is missing is they do not tell you what should display when this situation happens. But what it is expecting is the exception that you get when your height or breadth is negative.

                • + 0 comments

                  @catequil Thanks, you are right. But the constrains are actually: -100 <= B <= 100 -100 <= H <= 100

                  So the 100 should be included. I guess it's a mistake that Testcase 6 fails, when you take the input 100 for valid.

            • + 1 comment

              No need to initialize variables B, H and flag.

              • + 0 comments

                I think we have to initialize flag...

            • + 0 comments

              thanks for the solution...also..no need to intialise....

            • + 0 comments

              what is the use of flag over here??

            • + 0 comments

              public static int B = 1; public static int H = 1; public static boolean flag = true; static{ }

              "can u explain me plzz why have used this?????"

          • + 0 comments

            just use if(flag==false) { System.out.println("java.lang.Exception: height and breadth must be positive"); }

            thats it. :)

          • + 1 comment

            Scanner scn=new Scanner(System.in); int area; int B=scn.nextInt(); int H=scn.nextInt(); if(B<=0||H<=0){ System.out.println("java.lang.Exception: Breadth and height must be positive"); }else{ area=B*H; System.out.println(area); }

            • + 0 comments

              with out using exception

          • + 0 comments

            Scanner obj = new Scanner(System.in); int B = obj.nextInt(); int H = obj.nextInt(); if(B>0 && H>0){ int area=B*H; System.out.print(area); } else{System.out.print("java.lang.Exception: Breadth and height must be positive");}

      • + 0 comments

        Very true.

      • + 0 comments

        Yes!

    • + 1 comment

      how multiplication result comes automatically?

      • + 1 comment

        There is code they give you behind the scenes. If you look before and after the section you can type in your code, there is a Solution class and a main they give you. You can expand these to see their code by clicking the double sided blue arrow on the display.

        Hope this helps

        • + 1 comment

          hey I am new to JAVA but why we use static cant we do it without static?

          • + 1 comment

            No u cant do it without static. As static members load into memory before anything else. So if the flag variable is not declared static then main wont have any value of flag! and thus an error my friend :)

            • + 0 comments

              Exactly!

    • + 2 comments

      But why use try-catch?

      • + 0 comments

        I don't think you have to. I just did it this way since they insinutated at it with "java.lang.exception" in their desired string.

      • + 0 comments

        You can simply print out the error message using System.out.println("errorMessage");,

        But for better learning try-catch is good practice.

    • [deleted]
      + 0 comments

      Understood the problem but I felt like it lack explanition. Thank you for the example! Now I understand it clearly. I probably would've gotten it if I had known you could expand the code by clicking on the blue arrows.

    • + 3 comments

      why do we use static in every line??

      • + 0 comments

        because main method is static ? See more : What is static keyword ?

      • + 0 comments

        because we are not allowed to add code to the main method, and static blocks is a way in which we can run our code before main() executes and to modify variable through static block we need to make them static because static block cannot access non-static context directly.

    • + 0 comments

      thanks,this cleared my doubt!!!!

    • + 2 comments

      Mine is much simpler. I just print the string literally without throwing any exception XD. Because it doesn't make sense to throw an exception on a static block. It should be either in the constructor or in a method.

      I'm already an experienced developer and I found this while looking places to practice my coding skills. These challenges are too easy for me XD. But they are good to remember the basics.

      I've been coding in Python for a year or so. During this period I almost didn't touched Java. That's why I wanted to practice it a little bit.

      Sorry, this went totally out of topic... I just felt I had to say it.

      • + 0 comments

        Can you please send me the link where I can learn about throwing exception in static block is no good..

      • + 0 comments

        nobody asked you

    • + 0 comments

      i use try-with-resources to create new Scanner. ( like this try (Scanner scanner = new Scanner(System.in)) ) because Scanner may be need close for good practice .

    • + 1 comment

      why we need static here

      • + 0 comments

        Read more : What is static keyword ?

    • + 1 comment

      what is the use of flag here?

    • + 1 comment

      how is this code giving the result of the parallelogram?

      • + 0 comments

        Do you want the code what can check it's a parallelogram ?

    • + 0 comments

      I thought static block was mainly used to initialize variables. It gives error if I add declaration in static block. Any Suggestions?

    • + 0 comments

      good one. help to identify improve on my sloution

    • + 1 comment

      sir i have a doubt as i m new to java ..... Exception is written class in java ... can we throw it tooo...??

      • + 0 comments

        we can throw Exception like
        throw new Exception("text");

    • + 0 comments

      Thank you for helping.

    • + 0 comments

      Thanks, that helped out a lot. I did mine differently but I didn't know you had to define the variables outside of the static block for them to be static.

    • + 0 comments

      what if we don't use static flag variable?

    • + 0 comments

      Nice solution! Please elaborate the use of 'throw' keyword here..

    • + 0 comments

      we are declaring flag as static boolean flag=true. As it is static so it shouldn't make changes but when inside the static block we give flag=false,the flag becomes false.Why?

    • + 0 comments

      but its not running

    • + 1 comment

      I don't think the try catch is necessary. Just use println is OK;

      //Write your code here
      static boolean flag = true;
      static int B, H;
      static {
          Scanner scanner = new Scanner(System.in);
          B = scanner.nextInt();
          scanner.nextLine();
          H = scanner.nextInt();
          scanner.close();
          if (B <= 0 || H <=0){
              flag = false;
              System.out.println("java.lang.Exception: Breadth and height must be positive");
          }
          else {
              //System.out.println(B * H);
          }
      }
      
    • + 1 comment

      bro where is the product (area of parallelogram ) shown

      • + 0 comments

        The area is printed in the main method. The flag variable is uesd to control the output of the area.

    • + 1 comment

      can some body explain the role of flag in the above example ?? why do we need a flag , what does it do?i tried the code without the flag but it dosent work!please help

      • + 1 comment

        see the main method There it's written that print B*H (if and only if flag ==true) And since we know that static block gets initialised as soon a s the class is loaded, So, as soon as the class is loaded and the values of B and H are loaded it's checked that is flag still equal to true

        I HOPE THAT YOU GOT IT NOW But still if you have any doubt feel free to ask

        • + 0 comments

          yaa ..thank you very much brother ..

    • + 0 comments

      Why do you need to use static for Scanner, boolean, and int?

    • + 0 comments

      A shorter approach

      private static Scanner scan = new Scanner(System.in); private static boolean flag = false; private static int B = scan.nextInt(); private static int H = scan.nextInt();

      static{

      flag = (B>0 && H>0);
      
      if(!flag)
      {System.out.print("java.lang.Exception: Breadth and height must be positive");}
      

      }

    • [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.

    • + 1 comment

      why only try and catch blocks are used why we cant use if-else block can u plzz explain ??

      • [deleted]
        + 1 comment

        I have used if else block ^^

        • + 0 comments

          okay

    • + 0 comments

      Why u used flag ?

    • + 0 comments

      what is the use of flag? not used any where

    • + 0 comments

      well defined and easy to understand try - catch, code. Thanks!

    • + 0 comments

      thanks , i am now clear with our logic

    • + 0 comments

      can u please explain why we should keep static for all the code?

    • + 0 comments

      yesssss a throw instead of a brainless print statment :9

    • + 0 comments

      can anyone explain about try,catch statements in java please; how they works

    • + 0 comments

      refer this to get complete demonstration on static initializer block https://hackerrankpractice.blogspot.com/2020/10/solution-for-static-initializer-block.html

    • + 0 comments

      why do you have to use a static block?

    • + 0 comments

      beginner here, i don't know much about try catch but this code of mine works just as much

      myCode{

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

      }

    • [deleted]
      + 0 comments

      What happens to the scanner 'input' in this example? It's never closed.

    • [deleted]
      + 0 comments

      This doesn't exactly match the challenge's requirements, which is tp print the exception, including 'java.lang.Exception'. I think that's bad, but that's what's being asked.

      How is the scanner 'input' closed?

    • + 0 comments

      i simpy printed out the exception using system.out.println as there wasnt a method. thanks for the tip

    • + 0 comments

      6th test case is getting failed using the code above. what can be the issue?