We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importjava.io.*;importjava.util.*;importjava.text.*;importjava.math.*;importjava.util.regex.*;publicclassSolution{staticScannerscan=newScanner(System.in);staticintB=scan.nextInt();staticintH=scan.nextInt();staticbooleanflag=true;static{try{if(B<=0||H<=0){flag=false;thrownewException("Breadth and height must be positive");}}catch(Exceptione){System.out.println(e);}}publicstaticvoidmain(String[]args){if(flag){intarea=B*H;System.out.print(area);}}//end of main}//end of class
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.
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.
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?
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);
}
}
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() ....
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
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);
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.
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!
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");
}
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.
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
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
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);
}
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");
}
@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)
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
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");
}
}
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");
}
}
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.
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");
}
}
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:)
staticbooleanflag=true;staticintB,H;static{Scanners=newScanner(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");}}
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
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.
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");
}
}
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.
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;
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'. "
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");
}
}
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.
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");
}
}
Java Static Initializer Block
You are viewing a single comment's thread. Return to all 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.)
Clean and Clear. Perfect. Thanks. Yea, Oracle Docs has a lot to read.
here is problem solution in java programming. https://programs.programmingoneonone.com/2021/02/hackerrank-java-static-initializer-block-solution.html
updated solution is here
https://www.thecscience.com/2021/05/HackerRank-java-static-initializer-block-problem-solution.html
Check my solution here: https://shreshth141999.wixsite.com/notaprogrammer/post/hackerrank-java-solutions-easy
My solution.
thank u mate for the answer
how the flag condition will work without calling main() function. Main function contains calculation part.
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.
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.
main is a Static method and the thing about static is they are executed when the class is loaded :D
It works because a static block is called first then whatever code is in the main method runs second
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.
because it's declared statically so it doesn't require any reference object for it to be called.
but how the class is loaded and how it calls the b and h valuess
thanks
is yours working?
Why static used here.
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?
showing error
This assignment is all about the Static Initialization Block, not just for Static Varialbles.
end class error
can u pls explain a bit about static block?
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;
}
can you please answer why is it necessary to write scan.next() when the variable is declared static ????
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() ....
can we do this same within main class ??
then it won't be called static initializer of a block
Why do I get 'illegal start of type' error if i do not enclose the 'try--catch' inside curly braces?
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
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;
why we are using boolean ?
Very helpful, thanks
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);
} }
this code is not working can you tell me now?
why everything is static here?
bro why we use all static memebers and fuction, what when we not use them?
Well mate, it has clearly mentioned to print that exception statement. Not to throw any exception.
Its not working for me -
Solution.java:12: error: Illegal static declaration in inner class Solution.Solution2 static Scanner scan = new Scanner(System.in);
Anyone tell why static keyword is used here and also tell me that what is the use of try and catch block?????
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
Really helpful. Thanks.
thanks.
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!
thanku so much ..... it clears all doubt
Thanks for this link. It helped me to understand this concept in more better way
thank u bro..now I got the point.
Thanks!It's very useful and helpful.
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.
becz since it is a static block all fields(variables) should be static it is similar to using static variables in static methods
Can you paste a link?
when we use static then we have not need to make a object .static functions invoke itself in java.
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.
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"); }
}
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.
why all code is written in static block plz explain(static{ ...........})
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
tq
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
thanks a lot
Thanks for the gud reply.
no object need to access members
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.
yorgie7, I think below is a simpler if-else logic.
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"); }
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
what is the use of System.exit(0); here plz explain........
what is the use of Sysetem.exit(0); here ????
It is the only correct solution for above cases otherwise each every solution throwing error... thank yu so much for this help
how did you know flag is a boolean?
because you just have to return true for flag to print the area
But it can be int also. flag=1 or flag=0. Why boolean only??
can u pls explain why did u write scan,nextLine() after taking input of B?? (new to java)
thanks
That explains it.
cool
static boolean flag = true; static int B,H;
static{
}
@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)
https://stackoverflow.com/questions/2070293/why-doesnt-java-allow-to-throw-a-checked-exception-from-static-initialization-b
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"); } }
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
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();
What if B and H are Both 0?
Better be B<0 || H<0.
If both are 0, there should be an Exception, it's written in the task:
it doesn't works fine. it gives some expression error bcoj u use static keyword before Scanner class.....
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"); }
why did we keep the whole loop in a static block
it doesn't matter
if not, it is throwing an error
i am not able to get area output
You can simplify the if condition and remove extra checks like this: (B > 0 && H > 0) && (B != 100 && H != 100)
you are right bro
it give error
what is the use of nextLine() bro
It is just to clear the previous String or we can say to clear the String garbage.
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"); } }
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"); } }
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.
can you explain how you directly used B,H as variables instead specifying any datatypes for that.
He used int .Read carefully you can find it.
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"); } }
thanks..this is giving correct answer. I was missing to update the flag as false in else loop.
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!!
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"); } }
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"); } }
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:)
value of B,H is reset to under main .
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; }
why we should keep in static block?
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"); } }
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"); }
your solution satisfies only problem's requirements but my solution covers all possibilities.
Why we use static block here
This is because we have been told to use static block in this problem.
thanks bro
static boolean flag = true; static int B,H; please explain this.....
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.
this is not satisfying few test cases even
It should, it worked fine for me which is why i posted my code.
ok!!thanku
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"); }
yes!!there r few cases which r not satisfying...but mild changes can be done the some code
// 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"); } }
In this testcas 3 and 6 become failed.
What's the reason for usage of scan.nextLine() here? will you please explain !
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.
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;
}
if((B>0)&&(H>0)){ flag = true; }else ....
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
}
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.
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
Agree, especially with such a simplistic example, the motivation for using this made so little sense to me.
thanks for your cooperation
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"); } }
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
that's so intersting....
Thanks, helped a lot.
Thank you! Oracle Docs is no help at all, so I also went to Stack Overflow.
Thank you! I get it now!
Thanks
****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 class
here is the solution for this problem Static initialization blocks
why arent there examples in oracle docs. Java is the most frustrating language ever