What is static variable/method in Java - Java Interview Question

static =>
  • modifier. a single copy(only 1 copy) of a variable/method is created and shared by all the objects of that class
  • the class 'owns' the static member
  • static variable makes your program memory efficient ie it saves memory
  • Restrictions of static method: 
    • can't call non-static variables or methods directly in static method
    • can't use 'this' and 'super' keyword
public class Main {
public static void main(String[] args) {
Friend friend1 = new Friend("Sponegbob");
Friend friend2 = new Friend("Patrick");
Friend friend3 = new Friend("Patrick");
System.out.println(Friend.numberOfFriends);
        Friend.info();
}
}

public class Friend {
String name;
static int numberOfFriends;
Friend(String name){
this.name=name;
numberOfFriends++;
}
    static void info(){
        System.out.println('My Friends.....');
    }
}

Static Method vs Regular Method:

Regular Method: 
  • we need an object to call these methods
class Square(){
    public int getArea(int i){
        return i*i;
    }
}

Square s = new Square();
int area = s.getArea(5);

Static Method: 
  • don't require any Object
  • static methods are just part of Class not Object
  • we can call static methods without objects ie by Class Name [example:ClassName.methodName()]
class Square(){
    public static int getArea(int i){
        return i*i;
    }
}

int area = Square.getArea(5);


Static variable: 
  • not associated with objects
  • belongs to class
  • syntax: ClassName.variableName 
  • advantages: makes your program MEMORY EFFICIENT

Why the main() has static?
  • to call static method NO OBJECT is required
  • so, JVM need not create a separate object to call this main method
  • it can simply call it when the class loads

Popular posts from this blog

GOOGLEFINANCE attributes

Practice

Merge/join two or more video files using Python