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.
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);
}
}
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);
}
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.
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");
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");
}
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.
staticbooleanflag=true;staticScannerin=newScanner(System.in);staticintB=in.nextInt();staticintH=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.
staticbooleanflag=true;staticScannerin=newScanner(System.in);staticintB=in.nextInt();staticintH=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!
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.
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);
}
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
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
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.
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.
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 :)
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
publicstaticintB=1;publicstaticintH=1;publicstaticbooleanflag=true;static{Scannerscan=newScanner(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");}}
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.
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);
}
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");}
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.
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 :)
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.
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.
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.
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 .
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.
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?
I don't think the try catch is necessary. Just use println is OK;
//Write your code herestaticbooleanflag=true;staticintB,H;static{Scannerscanner=newScanner(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);}}
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
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
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");}
publicstaticScannersc=newScanner(System.in);publicstaticintB=sc.nextInt();publicstaticintH=sc.nextInt();publicstaticbooleanflag=init2();privatestaticbooleaninit2(){if(B<=0||H<=0){System.out.println("java.lang.Exception: Breadth and height must be positive");returnfalse;}returntrue;}
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");
}
}
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.
Java Static Initializer Block
You are viewing a single comment's thread. Return to all 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{
}
Great example! :)
how multiplication result comes automatically?
static boolean flag=true;
static int B,H;
static {
}
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.
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
we cant use this as if both b & h are negative the condition will get true which should not be happen
if both b & h are negative the condition will get false and it throw the exception
why do we need flag in this to true can we use and operator insted of or .................................please help
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");
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();
}
This works fine.
Code is working but how you are calculating the area .
Area is calculated in the main method. Expand the code and you will find it! :)
thank you
cool...
Why can't we put boolean flag = true; and int B,H; in the static block??
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.
Note: variables inside the static block is not static.
why are we using the boolean variable flag?
alredy given flag in main function as a conditon for if so we should use flag
how to access the main class??
Click on arrow you will find the full part of main class.
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.
System.out.print(area); ?????
paste the same code,complied and tested and let me know!
i did the same thing but got an error class,enum or interface expected.pls help me
i also did exactly same but i am getting error
Do not close class before main. There is closing parenthesis for class after main.
Thanks a ton! It Worked for me.
its showing semicolan expected
thank u
I tried doing it that way but it went wrong, so I had to take the:
out of the block.
Why is it?
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.
Thanks, that helps a lot to understand how it works
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); }
}
end class erorr
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
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
kindly open main().
Expant main method.
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.
that was present in the main see
This problem does not require exceptions. It's actually way easier without them.
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.
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 :)
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
can you show me the way without exception?tks
Like this:
Your answer is fail to pass the 6th test case.!!
Sorry. It should be "if (B <= 0 || H <= 0)". You can try again.
It is the same thing. And Answer comes by this.
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.
@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.
No need to initialize variables B, H and flag.
I think we have to initialize flag...
thanks for the solution...also..no need to intialise....
what is the use of flag over here??
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?????"
just use if(flag==false) { System.out.println("java.lang.Exception: height and breadth must be positive"); }
thats it. :)
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); }
with out using exception
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");}
Very true.
Yes!
how multiplication result comes automatically?
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
hey I am new to JAVA but why we use static cant we do it without static?
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 :)
Exactly!
But why use try-catch?
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.
You can simply print out the error message using System.out.println("errorMessage");,
But for better learning try-catch is good practice.
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.
why do we use static in every line??
because main method is static ? See more : What is static keyword ?
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.
thanks,this cleared my doubt!!!!
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.
Can you please send me the link where I can learn about throwing exception in static block is no good..
nobody asked you
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 .
why we need static here
Read more : What is static keyword ?
what is the use of flag here?
how is this code giving the result of the parallelogram?
Do you want the code what can check it's a parallelogram ?
I thought static block was mainly used to initialize variables. It gives error if I add declaration in static block. Any Suggestions?
good one. help to identify improve on my sloution
sir i have a doubt as i m new to java ..... Exception is written class in java ... can we throw it tooo...??
we can throw Exception like
throw new Exception("text");
Thank you for helping.
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.
what if we don't use static flag variable?
Nice solution! Please elaborate the use of 'throw' keyword here..
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?
but its not running
I don't think the try catch is necessary. Just use println is OK;
bro where is the product (area of parallelogram ) shown
The area is printed in the main method. The flag variable is uesd to control the output of the area.
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
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
yaa ..thank you very much brother ..
Why do you need to use static for Scanner, boolean, and int?
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{
}
Without try-catch block
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;
}
This is more easy and working well.
why only try and catch blocks are used why we cant use if-else block can u plzz explain ??
I have used if else block ^^
okay
Why u used flag ?
what is the use of flag? not used any where
well defined and easy to understand try - catch, code. Thanks!
thanks , i am now clear with our logic
can u please explain why we should keep static for all the code?
yesssss a throw instead of a brainless print statment :9
can anyone explain about try,catch statements in java please; how they works
refer this to get complete demonstration on static initializer block https://hackerrankpractice.blogspot.com/2020/10/solution-for-static-initializer-block.html
why do you have to use a static block?
beginner here, i don't know much about try catch but this code of mine works just as much
myCode{
}
What happens to the scanner 'input' in this example? It's never closed.
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?
i simpy printed out the exception using system.out.println as there wasnt a method. thanks for the tip
6th test case is getting failed using the code above. what can be the issue?