0
0
Javaprogramming~15 mins

Static blocks in Java - Cheat Sheet & Quick Revision

Choose your learning style8 modes available
overviewRecall & Review
beginner
What is a static block in Java?
A static block is a block of code inside a class that runs once when the class is loaded. It is used to initialize static variables or perform setup tasks.
touch_appClick to reveal answer
beginner
When does a static block execute in Java?
A static block executes only once when the class is first loaded into memory, before any objects are created or static methods are called.
touch_appClick to reveal answer
intermediate
Can a class have multiple static blocks? If yes, in what order do they execute?
Yes, a class can have multiple static blocks. They execute in the order they appear in the source code, from top to bottom.
touch_appClick to reveal answer
advanced
What happens if an exception occurs inside a static block?
If an exception occurs inside a static block and is not caught, it causes an ExceptionInInitializerError, preventing the class from loading properly.
touch_appClick to reveal answer
intermediate
Why use static blocks instead of initializing static variables directly?
Static blocks allow complex initialization code that can't be done in a single statement, such as loops, conditionals, or try-catch for error handling.
touch_appClick to reveal answer
When is a static block executed in Java?
AEvery time an object is created
BWhen the class is loaded
CWhen a method is called
DWhen the program ends
Can a Java class have more than one static block?
ANo, only one static block is allowed
BYes, but they execute randomly
CNo, static blocks are not allowed in Java
DYes, and they execute in the order they appear
What happens if an exception is thrown inside a static block and not caught?
AThe program ignores it
BThe exception is converted to a runtime exception
CThe class fails to load with ExceptionInInitializerError
DThe exception is logged but the program continues
Which of these is a good reason to use a static block?
ATo initialize static variables with complex logic
BTo initialize instance variables
CTo execute code every time an object is created
DTo replace constructors
Static blocks run before which of the following?
AAll of the above
BBefore main method runs
CBefore any object is created
DBefore any static method or variable is accessed
Explain what a static block is and when it runs in Java.
Describe how multiple static blocks behave in a Java class.