non static variable 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: what is static variable

The static variable is used to refer to the common property of all objects 
(that is not unique for each object), 
e.g., The company name of employees, college name of students, etc. 
Static variable gets memory only once in the class area at the time of 
class loading. Using a static variable makes your program more 
memory efficient (it saves memory). Static variable belongs to the class 
rather than the object.

Tags:

Misc Example