What is a static variable in Java

public class Person(){
private static int population = 0;
private String name;
private String surname;

public Person(String name, String surname){
population++;
this.name=name;
this.surname=surname;
}

/**
* A member variable that returns the specific
* object's full name.
*/

public String getFullName(){
return name+" "+surname;
}

/**
* A static method that returns the total
* amount of person objects created.
*/

public static int getPopulation(){
return population;
}
}
// Static variable
private static int population = 0;
// member variables
private String name;
private String surname;
public Person(String name, String surname){
population++;
this.name=name;
this.surname=surname;
}
// create a STATIC method that returns the STATIC population value
public static int getPopulation(){
return population;
}
// by calling this STATIC METHOD
// we get the population of the Person class

print(Person.getPopulation())
// it is the same as calling the STATIC VARIABLE
// we get the population of the Person class
print(Person.population);
p1 = new Person("Ioannis", "Anifantakis");
print(p1.getFullName()) // print result: Ioannis Anifantakis
print(Person.getPopulation()); // print result: 1
p2 = new Person("Eleni", "Fragioudaki");
print(p2.getFullName()) // print result: Eleni Fragioudaki
print(Person.getPopulation()); // print result: 2

/*
you observe that the member method "getFullName()" which is called in object level, returns the values of name and surname for that specific instance (object) of Person.
While the static method getPopulation() which is called in class level, returns a value that is shared among all objects, and its not object specific (does not belong to a specific person instance, but to all persons).
*/
// to print the full name of a specified object
// we use the object itself as reference
// output -> "Ioannis Anifantakis"
print(p1.getFullName());
// to print the population that belongs to the entire class
// we use the class itself as a reference
// output -> 2
print(Person.population);

Static Variables and Methods vs Member Variables and Methods

TL;DR

--

--

--

MSc Computer Science. — Software engineer and programming instructor. Actively involved in Android Development and Deep Learning.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ioannis Anifantakis

Ioannis Anifantakis

MSc Computer Science. — Software engineer and programming instructor. Actively involved in Android Development and Deep Learning.

More from Medium

Interfaces and Abstract classes

macOS: Running IntelliJ IDEA with JDK 17 for Better Render Performance with Metal

EFiVyl

Replace Text in Word Documents in Java

How to Build Java Applications Today #62