Java Static Initializer Block

  • + 27 comments

    Refer to this stackoverflow question if you'd like help understanding the difference between a static block and specific static initializers.

    http://stackoverflow.com/questions/9379426/java-when-is-a-static-initialization-block-useful

    I found this useful in comparison to the droves of wordy, example-less explanations (I'm looking at you, Oracle Docs.)

    • + 4 comments

      Clean and Clear. Perfect. Thanks. Yea, Oracle Docs has a lot to read.

      • + 1 comment

        here is problem solution in java programming. https://programs.programmingoneonone.com/2021/02/hackerrank-java-static-initializer-block-solution.html

        • + 0 comments

          updated solution is here

          https://www.thecscience.com/2021/05/HackerRank-java-static-initializer-block-problem-solution.html

      • + 0 comments

        Check my solution here: https://shreshth141999.wixsite.com/notaprogrammer/post/hackerrank-java-solutions-easy

      • + 27 comments

        My solution.

        import java.io.*;
        import java.util.*;
        import java.text.*;
        import java.math.*;
        import java.util.regex.*;
        
        public class Solution {
        
        static Scanner scan = new Scanner(System.in);
        static int B = scan.nextInt();
        static int H = scan.nextInt();
        static boolean flag = true;
        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);
            }
        
        }
        public static void main(String[] args){
        		if(flag){
        			int area=B*H;
        			System.out.print(area);
        		}
        		
        	}//end of main
        
        }//end of class
        
        • + 0 comments

          thank u mate for the answer

        • + 6 comments

          how the flag condition will work without calling main() function. Main function contains calculation part.

          • + 0 comments

            Flag is a static variable, which invokes at the time of class loading, so boolean flag is having value 'true' before execution of main() method.

          • + 0 comments

            first of all static variables will get the memory while execution, so the boolean flag is initialized with true value, so the condition become true and it will gives the result of area by taking inputs.

          • + 0 comments

            main is a Static method and the thing about static is they are executed when the class is loaded :D

          • + 0 comments

            It works because a static block is called first then whatever code is in the main method runs second

          • + 0 comments

            the static block executes before the main function; after that main function is imlpicitly invoked by the comiler. Here flag and B-H are global variables (For Solution Class only). As they are static so we didn't have to create an object to use them.

          • + 0 comments

            because it's declared statically so it doesn't require any reference object for it to be called.

        • + 0 comments

          but how the class is loaded and how it calls the b and h valuess

        • [deleted]
          + 0 comments

          thanks

        • + 0 comments

          is yours working?

        • [deleted]
          + 0 comments

          Why static used here.

        • + 0 comments

          My code alost looks like this, except my try-catch is called if the flag is false. The logic is as follows, "If the flag is false, try to throw an exception, and catch it" This passes only two testCases why?

        • + 0 comments

          showing error

        • + 0 comments

          This assignment is all about the Static Initialization Block, not just for Static Varialbles.

        • + 0 comments

          end class error

        • + 0 comments

          can u pls explain a bit about static block?

        • + 0 comments

          Why cant we use static variable declaration inside static block?? Like -

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

          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

          can you please answer why is it necessary to write scan.next() when the variable is declared static ????

          • + 0 comments

            static declaration of a variable or a function just says that that method doesn't require any object for its implementation and to take the user input we did that scan.next() ....

        • + 1 comment

          can we do this same within main class ??

          • + 0 comments

            then it won't be called static initializer of a block

        • + 0 comments

          Why do I get 'illegal start of type' error if i do not enclose the 'try--catch' inside curly braces?

        • + 0 comments

          First tine I hear about static block initialization.. Very interesting.. I understood that they are required in case if you want to initialize (static) class variable without creating an object. Thankx for the solution.. understood more than before :D

        • + 0 comments

          Doing small correction to above code with which i faced error and it is rectified now.

          try{ if(B <= 0 || H <= 0){ flag = false; throw new Exception("Breadth and height must be positive"); } else flag=true;

        • + 0 comments

          why we are using boolean ?

        • + 0 comments

          Very helpful, thanks

        • + 1 comment
          class static1{
          

          static boolean flag = true; static int B,H; static {
          try{Scanner s= new Scanner(System.in); boolean flag ; B = s.nextInt(); H = s.nextInt(); if(B<=0 || H<=0) { System.out.println("java.lang.Exception: Breadth and height must be positive"); }else if(B<=100 || H<=100) { flag =true; } }catch(Exception e){ System.out.println(e);

          } }

          • + 0 comments

            this code is not working can you tell me now?

        • + 0 comments

          why everything is static here?

        • + 0 comments

          bro why we use all static memebers and fuction, what when we not use them?

        • + 0 comments

          Well mate, it has clearly mentioned to print that exception statement. Not to throw any exception.

        • + 0 comments

          Its not working for me -

          Solution.java:12: error: Illegal static declaration in inner class Solution.Solution2 static Scanner scan = new Scanner(System.in);

      • + 1 comment

        Anyone tell why static keyword is used here and also tell me that what is the use of try and catch block?????

        • + 0 comments

          static - when a parameter or variable is used many many times then we put static in it. SO that it is not created multiple times when objects are created.

          try and catch are used to prevent crashes. Like put some code in the try{} block if it crashes then system will rollback and go to catch{} block and run that code. So we can try some code and if it throws exception (crash report) then we catch it.

          For details refer to geeksforgeeks

    • + 0 comments

      Really helpful. Thanks.

    • + 0 comments

      thanks.

    • + 0 comments

      I generally avoid coming here to discussions as people post answers! But when all seemed lost and there was no hope left for humanity. You came in my friend! ALL HAil our lord and saviour Stefank!

    • + 0 comments

      thanku so much ..... it clears all doubt

    • + 0 comments

      Thanks for this link. It helped me to understand this concept in more better way

    • + 0 comments

      thank u bro..now I got the point.

    • + 0 comments

      Thanks!It's very useful and helpful.

    • + 5 comments

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

      why did we add static? couldn't get.I am new for Java.

      • + 1 comment

        becz since it is a static block all fields(variables) should be static it is similar to using static variables in static methods

        • + 0 comments

          Can you paste a link?

      • + 0 comments

        when we use static then we have not need to make a object .static functions invoke itself in java.

      • + 0 comments

        we use static because if we define our variables not in main class and we have to call them in it then we use static before our declaration.

      • + 7 comments

        static boolean flag = true; static int B,H;

        static{

        Scanner scan = new Scanner(System.in); B = scan.nextInt(); scan.nextLine(); H = scan.nextInt(); scan.close(); if(B>0 && H>0){ flag = true;

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

        }

        • + 0 comments

          What is the point of the elseif? what is the difference with the ouput of else? In this exercice, there is no need to differentiate if one element is negative or both of them.

        • + 3 comments

          why all code is written in static block plz explain(static{ ...........})

          • [deleted]
            + 3 comments

            Static block is used to run code when a class is intialized or you can say before static void main function is called the static block will be run. so any calculations needed before the main funcation can be done in there. Hope this helps

            • + 1 comment

              tq

              • + 0 comments

                Static initialization blocks are executed when the class is loaded, and you can initialize static variables in those blocks.

                It's time to test your knowledge of Static initialization blocks. You can read about it here.

                You are given a class Solution with a main method. Complete the given code so that it outputs the area of a parallelogram with breadth and height . You should read the variables from the standard input.

                If or , the output should be "java.lang.Exception: Breadth and height must be positive" without quotes.

                Input Format

                There are two lines of input. The first line contains : the breadth of the parallelogram. The next line contains : the height of the parallelogram.

                Constraints

                Output Format

                If both values are greater than zero, then the main method must output the area of the parallelogram. Otherwise, print "java.lang.Exception: Breadth and height must be positive" without quotes.

                Sample input 1

                1 3 Sample output 1

                3 Sample input 2

                -1 2 Sample output 2

                java.lang.Exception: Breadth and height must be positive

            • + 0 comments

              thanks a lot

            • + 0 comments

              Thanks for the gud reply.

          • + 0 comments

            no object need to access members

          • + 0 comments

            In java every class is stored in seperate memory.If we use static all can be stored in same memory location and we can use wherever we want.

        • + 4 comments

          yorgie7, I think below is a simpler if-else logic.

          static boolean flag = true; static int B,H;

          static{ Scanner sc = new Scanner(System.in);

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

          }

          • + 1 comment

            I think the if/else can be even more simple like: static boolean flag = true; static int B,H; static { Scanner input = new Scanner(System.in); B = input.nextInt(); H = input.nextInt(); if (B > 0 && H > 0) { flag = true; } else { System.out.print("java.lang.Exception: Breadth and height must be positive"); }

            • + 0 comments

              thanks... but two errors... you missed one } at the end of the code. and we have assign flag=false in else part..

              thank you :3

          • + 0 comments

            what is the use of System.exit(0); here plz explain........

          • + 0 comments

            what is the use of Sysetem.exit(0); here ????

          • + 0 comments

            It is the only correct solution for above cases otherwise each every solution throwing error... thank yu so much for this help

        • + 1 comment

          how did you know flag is a boolean?

          • + 1 comment

            because you just have to return true for flag to print the area

            • + 0 comments

              But it can be int also. flag=1 or flag=0. Why boolean only??

        • + 0 comments

          can u pls explain why did u write scan,nextLine() after taking input of B?? (new to java)

    • [deleted]
      + 0 comments

      thanks

    • + 0 comments

      That explains it.

    • [deleted]
      + 0 comments

      cool

    • + 24 comments

      static boolean flag = true; static int B,H;

      static{

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

      }

      • + 1 comment

        @above No that code is too complicated. The else if statement is not neccessary (just need an else statement). You just need to set flag = true when both are greater than 0. (Lengths can't be negative)

        • + 0 comments

          https://stackoverflow.com/questions/2070293/why-doesnt-java-allow-to-throw-a-checked-exception-from-static-initialization-b

      • + 5 comments

        You have a error in else if() block

        Here is the actual answer

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

        • + 1 comment
          [deleted]
          • + 0 comments

            your program is correct but how i am not able to understand the logic behind this if ((B<0 && H<0)&&(B>=0&&H>=0)) suppose :we will give input 1and 3 then it shoud go to false block because B<0 && H<0 =false B>=0&& H>=0=True false && true false should come

        • + 6 comments

          why so many comparison operator dude. Simply below would work just fine.

          static boolean flag = true; static int B, H; static Scanner sc = new Scanner(System.in);

          static { B = sc.nextInt(); H = sc.nextInt();

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

            What if B and H are Both 0?

            Better be B<0 || H<0.

            • + 0 comments

              If both are 0, there should be an Exception, it's written in the task:

              1. if both values are greater than zero => output the area
              2. otherwise => java.lang.Exception
          • + 0 comments

            it doesn't works fine. it gives some expression error bcoj u use static keyword before Scanner class.....

          • + 3 comments

            This works

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

            • + 1 comment

              why did we keep the whole loop in a static block

              • + 1 comment

                it doesn't matter

                • + 0 comments

                  if not, it is throwing an error

            • + 0 comments

              i am not able to get area output

            • + 0 comments

              You can simplify the if condition and remove extra checks like this: (B > 0 && H > 0) && (B != 100 && H != 100)

          • + 0 comments

            you are right bro

          • + 0 comments

            it give error

        • + 1 comment

          what is the use of nextLine() bro

          • + 0 comments

            It is just to clear the previous String or we can say to clear the String garbage.

        • + 1 comment

          This one is the correct code you have written if block wrong. static int B,H; static boolean flag=true; static{ Scanner scan = new Scanner(System.in); B = scan.nextInt(); scan.nextLine(); H = scan.nextInt(); scan.close(); if(B>0 && H>0){ flag = true;

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

        • + 0 comments

          correct code:

          static boolean flag = true; static int B,H;

          static{

          Scanner scan = new Scanner(System.in); B = scan.nextInt(); scan.nextLine(); H = scan.nextInt(); scan.close(); if(B>0 && H>0){ flag = true;

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

          else { flag=false; System.out.println("java.lang.Exception: Breadth and height must be positive"); } }

      • + 0 comments

        It won't give the correct answer. you need to remove the less than condition from the first if. other than that there is no need of second if else only else is needed.

      • + 1 comment

        can you explain how you directly used B,H as variables instead specifying any datatypes for that.

        • + 0 comments

          He used int .Read carefully you can find it.

      • + 2 comments

        It was not passing two test cases so i did some modification

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

        }else{ flag=false; System.out.println("java.lang.Exception: Breadth and height must be positive"); } }

        • + 0 comments

          thanks..this is giving correct answer. I was missing to update the flag as false in else loop.

        • + 0 comments

          bro it still not passing both the test cases. for stdin 1,3 it is giving the output as '0' where as the expected output is '3'. plz help!!

      • + 1 comment

        static boolean flag = true; static int B,H;

        static{

        Scanner scan = new Scanner(System.in); B = scan.nextInt(); scan.nextLine(); H = scan.nextInt(); scan.close(); if(B>0 && H>0){ flag = true;

        }else{ flag=false; System.out.println("java.lang.Exception: Breadth and height must be positive"); } }

        • + 1 comment

          static boolean flag = true; static int B,H;

          static{ Scanner s=new Scanner(System.in); B=s.nextInt(); s.nextLine(); H=s.nextInt(); s.close(); if(H<=0 || B<=0){ flag=false; System.out.println("java.lang.Exception: Breadth and height must be positive"); } }

          • + 1 comment

            After reading this, I just realized that the whole point of using static is that this line below are running before the main class is called (I made the code more readable here below:)

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

              value of B,H is reset to under main .

      • + 0 comments

        static boolean flag = true; static int B,H; 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"); }else flag=true; }

            #this is the actual output
        
            your output fails in two of the given test cases
        
      • + 0 comments

        why we should keep in static block?

      • + 0 comments

        yr god has got some errors here is the errorless code

        /............................................./ static boolean flag = true; static int B,H;

        static {

        Scanner scan = new Scanner(System.in); B = scan.nextInt(); scan.nextLine(); H = scan.nextInt(); scan.close(); if(B>0 && H>0) { flag = true;

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

      • + 1 comment

        Your If and else if conditions are wrong. keep it simple silly.

        if(B>0 && H>0){ flag = true;

        }else { flag=false; System.out.println("java.lang.Exception: Breadth and height must be positive"); }

        • + 0 comments

          your solution satisfies only problem's requirements but my solution covers all possibilities.

      • + 1 comment

        Why we use static block here

        • + 0 comments

          This is because we have been told to use static block in this problem.

      • + 0 comments

        thanks bro

      • + 1 comment

        static boolean flag = true; static int B,H; please explain this.....

        • + 0 comments

          Here i've just declared B,H as static variables because static methods involve use of static variables. flag is just initialized to default boolean value which can either be set as true or false doesn't make a difference.

      • + 1 comment

        this is not satisfying few test cases even

        • + 1 comment

          It should, it worked fine for me which is why i posted my code.

          • + 0 comments

            ok!!thanku

      • + 1 comment

        Your code gives wrong answer in some test case insted do this :-

        if(B>0 && H>0){ flag = true;

        }else{ flag=false; System.out.println("java.lang.Exception: Breadth and height must be positive"); }

        • + 0 comments

          yes!!there r few cases which r not satisfying...but mild changes can be done the some code

      • + 0 comments

        // Much simpler one.

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

      • + 0 comments

        In this testcas 3 and 6 become failed.

      • + 0 comments

        What's the reason for usage of scan.nextLine() here? will you please explain !

      • + 0 comments

        the statement in if is unnecessary tho(greater than or equal to is not needed because it says to output area if only both are greater than 0, so its just better with B>0 && H>0)also the else if is unnecessary too. i use else there and it works just fine.

      • + 0 comments

        static int B; static int H; static boolean flag;

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

        }

      • + 0 comments

        if((B>0)&&(H>0)){ flag = true; }else ....

      • + 0 comments

        bro y u used so much coonditions in if statment if(B>=0 && H>=0){ flag = true;

        }else{ flag=false; System.out.println("java.lang.Exception: Breadth and height must be positive"); it can be done by this also simple

        }

      • + 0 comments

        Two test cases fail when this code is run. If we have just if(B>0 && H>0){

        } else{

        }
        This code has just one test case failure.

    • + 1 comment

      What's missing from all these explanations is they all focus on "how it works" and not "why you would want to do it" which remains still partiallly a mystery to me. Apart from allowing one to run commands out of sequence - and why would you want to do that? - the best explanation of what it's for that I could find is...

      "The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable. So, you kind of get more flexibility with a private static method in comparison to the corresponding static initialization block. This should not mislead that a 'public' static method can't do the same. But, we are talking about a way of initializing a class variable and there is hardly any reason to make such a method 'public'. "

      http://www.jusfortechies.com/java/core-java/static-blocks.php

      • + 0 comments

        Agree, especially with such a simplistic example, the motivation for using this made so little sense to me.

    • + 0 comments

      thanks for your cooperation

    • + 1 comment

      thanks bro..

      public class Solution { static boolean flag=false; static int B,H; 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"); } }

      • + 0 comments

        Isn't this incorrect? The if statement is going to give a false positive and allow a zero area. It should just be > not >=. I mean, it works with the test cases, I think, but it's not what the algorithm asked for.

        I did it this way, too (using B > 0 && H > 0) but after reading everyone else's answers here initializing the flag to true and using B <= 0 || H <= 0 I realized that's technically more efficient because it wouldn't have to evaluated the second conditional statement if the first failed whereas using && will always require two comparisons.

        Am I being crazy? XD

    • + 0 comments

      that's so intersting....

    • + 0 comments

      Thanks, helped a lot.

    • + 0 comments

      Thank you! Oracle Docs is no help at all, so I also went to Stack Overflow.

    • + 0 comments

      Thank you! I get it now!

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

      Thanks

    • + 0 comments

      ****import java.io.; import java.util.; import java.text.; import java.math.; import java.util.regex.*;

      ***public class Solution { static boolean flag=false; static int B,H; static{ Scanner in= new Scanner(System.in); B=in.nextInt(); H=in.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.print(area); }

      }//end of main
      

      }//end of class

    • + 0 comments

      here is the solution for this problem Static initialization blocks

    • + 0 comments

      why arent there examples in oracle docs. Java is the most frustrating language ever