Java | Static Method

03 min read

 Static Methods:

  • Can only directly call other static methods.
  • Can only directly access static data.
  • Cannot refer to 'this' or 'super' in any way.

Static Block (or) Static initializer:

  • Not a method.
  • A static block can be declared inside a class which will get executed exactly once when the class is first loaded into the JVM.
  • Executed in the order in which they appear textually in the source file.
  1. Used to initialize all static members, at once.
  2. Used to load drivers & other items into the namespace. (eg) class.forName("org.Driver"); ---> will be studied later
  3. Useful for some database operations like creating prepared SQL statements.

Example:

class sample
{
static int a=3, b;
static void method1 (int x)
{
System.out_println(x + " "+a+ " "+b);
}
static ---> static block
{
System.out.println("Static block initalized");
b = a * 4;
}
public static void main(String[ ] args)
{
method 1 ( 10);
}

As soon as the 'sample' class is loaded into the JVM, all of the static statements are run first. (i) a is set to 3. (ii) static block executes which sets b to a*4. (iii) method1( ) although static, should be invoked from elsewhere. Thus, main( ) method is called third, which in turn calls method1( ), by passing 10 to x.

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error