More than 3000 questions in repository. There are more than 900 unanswered questions. Click here and help us by providing the answer. Have a video suggestion. Click Correct / Improve and please let us know.
Ans. Both belong to the class as a whole and not to the individual objects. Static methods are explicitly called for execution whereas Static block gets executed when the Class gets loaded by the JVM.
Help us improve. Please let us know the company, where you were asked this question :
Methods , Variables , Initialization Blocks and Outer Classes and nested Classes.
Methods , Variables , Initialization Blocks and Outer Classes.
Methods , Variables , Initialization Blocks and nested Classes.
Q4. Will the static block be executed in the following code ? Why ?
class Test { static { System.out.println("Why I am not executing "); } public static final int param=20; }
public class Demo { public static void main(String[] args) { System.out.println(Test.param); } }
Ans. No the static block won't get executed as the referenced variable in the Test class is final. Compiler replaces the content of the final variable within Demo.main method and hence actually no reference to Test class is made.
Help us improve. Please let us know the company, where you were asked this question :
Ans. A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
static {
// whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
Help us improve. Please let us know the company, where you were asked this question :
public static void main(String[] args){
System.out.println("Main Method");
}
}
Static Block
Main Method
Static Block
Instance Initialization Block
Main Method
Static Block
Constructor
Main Method
Static Block
Instance Initialization Block
Constructor
Main Method
Q8. Can we initialize member variables within static block ?
Ans. Static block is like static method that gets executed upon class loading. The way static method allows accessing member variables ( using object references only ), the same static block can also access and initialize member variables.
Help us improve. Please let us know the company, where you were asked this question :