java static method code example

Example 1: what is static method

A static method belongs to the class rather than the object.
There is no need to create the object to call the static methods.
A static method can access and change the value of the static variable

Example 2: static in java

static keyword is a non-access modifier. static keyword can be used with 
class level variable, block, method and inner class or nested class.

Example 3: do i have to use static methods in java main

Use a static method 
when you want to be able to access the method 
without an instance of the class

Example 4: how to call a static method in java

class scratch{
	public static hey(){
		System.out.println("Hey");
    }
	public static void main(String[] args){
		hey();
        //print Hey to the console
    }

Example 5: Static method in java

We can declare a method as static by adding keyword “static” before method name.
Let’s see example on static method in java.

public class StaticMethodExample
{
   static void print()
   {
      System.out.println("in static method.");
   }
   public static void main(String[] args)
   {
      StaticMethodExample.print();
   }
}

Example 6: static data and static methods in java

class JavaExample{
   private static String str = "BeginnersBook";

   //Static class
   static class MyNestedClass{
	//non-static method
	public void disp() {

	   /* If you make the str variable of outer class
	    * non-static then you will get compilation error
	    * because: a nested static class cannot access non-
	    * static members of the outer class.
	    */
	   System.out.println(str); 
	}

   }
   public static void main(String args[])
   {
       /* To create instance of nested class we didn't need the outer
	* class instance but for a regular nested class you would need 
	* to create an instance of outer class first
        */
	JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
	obj.disp();
   }
}