Menu Close

Static methods in Java

static user method:

  • Block of instructions that performs a task.
  • We define static methods using ‘static’ keyword.
  • Every method should have return type.
  • main() execute by JVM implicitly.
  • Other methods must be called manually.
  • We access static members using class name
class Test 
{
	public static void main(String[] args) 
	{
		System.out.println("Starts @ main...");
		Test.fun();
		System.out.println("Ends @ main...");
	}
	static void fun()
	{
		System.out.println("fun...");
	}
}
  • We can define members in any order.
  • In class execution JVM invokes static block first (if defined)
  • After static block – main executes
  • User methods executes only when we access.
class Test 
{
	static void fun()
	{
		System.out.println("fun...");
	}
	public static void main(String[] args) 
	{
		System.out.println("Main starts...");
		Test.fun();
		System.out.println("Main ends...");
	}
	static
	{
		System.out.println("Block starts..");
		Test.fun();
		System.out.println("Block ends...");
	}
}

Check the flow:

class Test 
{
	static void m1()
	{
		System.out.println(9);
	}
	static void m2()
	{
		System.out.println(2);
	}
	public static void main(String[] args) 
	{
		Test.m2();
		System.out.println(4);
	}
	static
	{
		System.out.println(7);
		Test.m2();
		System.out.println(5);
		Test.m1();
	}
}

We can call one method from definition of another method:

class Test 
{
	static void m1()
	{
		System.out.println("m1....");
	}
	static void m2()
	{
		System.out.println("m2....");
		Test.m1();
	}
	public static void main(String[] args) 
	{
		System.out.println("main...");
		Test.m2();
		System.out.println("end...");
	}
}

Check the output:

class Test 
{
	static void m1(){
		System.out.println(7);
	}
	static void m2(){
		Test.m1();
		System.out.println(9);
	}
	public static void main(String[] args) 
	{
		Test.m2();
		System.out.println(3);
		Test.m1();
	}
	static{
		Test.m1();
		System.out.println(5);
		Test.m2();
	}
}