static and non static methods in java code example

Example 1: static vs non static java

// Static vs Object Called
// Static Methods don't require you to call a constructor

// Initialize statically
public class MyClass {

  private static int myInt;

  static {
      myInt = 1;
  }

  public static int getInt() {
      return myInt;
  }
}

// Then call it
System.out.println(MyClass.getInt());

// VS Constructor

public class MyClass {
 
  private int myInt;
  
  public MyClass() {
    myInt = 1;
  }
  
  public int getInt() {
	return this.myInt;
  }
}
// Then call it
MyClass myObj = new MyClass();
System.out.println(myObj.getInt());

Example 2: 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 3: 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();
   }
}

Tags:

Misc Example