Instance vs Static Variables
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 15 of 87.
So far, every field we've created belongs to a specific object. Each BankAccount has its own balance, and each Product has its own name. These are instance variables - they exist separately for each instance of a class.
But what if you need data that's shared across all objects? That's where static variables (also called class variables) come in. A static variable belongs to the class itself, not to any particular object.
public class Student {
private String name; // Instance variable - unique per student
private static int totalCount; // Static variable - shared by all students
public Student(String name) {
this.name = name;
totalCount++; // Increments the shared counter
}
public static int getTotalCount() {
return totalCount;
}
}When you create multiple students, each has their own name, but they all share the same totalCount:
Student s1 = new Student("Alice");
Student s2 = new Student("Bob");
System.out.println(Student.getTotalCount()); // Output: 2Notice how we access the static variable through the class name (Student.getTotalCount()) rather than through an object. This emphasizes that static members belong to the class, not to instances.
Use instance variables for data that varies between objects (like a student's name). Use static variables for data that should be shared (like counting how many objects exist).
Challenge
EasyLet's build a Book inventory system that tracks both individual book details and the total number of books across your entire collection using instance and static variables.
You'll create two files to organize your code:
Book.java: Create a Book class that tracks individual book information while also keeping count of all books ever created:- An instance variable
title(String) - unique to each book - An instance variable
price(double) - unique to each book - A static variable
totalBooks(int) - shared across all Book objects, tracking how many books have been created - A constructor that takes the title and price, and increments the total book count
- A getter
getTitle()for the title - A getter
getPrice()for the price - A static method
getTotalBooks()that returns the total number of books created
- An instance variable
Main.java: Create multiple Book objects and demonstrate how the static counter tracks all instances. You'll receive three book titles and three prices as inputs. After creating all three books, print four lines:- The title and price of each book in the format:
[title]: $[price](price formatted to 2 decimal places) - The total number of books using the static method:
Total books: [count]
- The title and price of each book in the format:
You will receive six inputs in order: title1, price1, title2, price2, title3, price3.
Remember to access the static method through the class name (Book.getTotalBooks()) rather than through an object instance. For formatting prices, use String.format("%.2f", price).
Cheat sheet
A static variable (also called a class variable) belongs to the class itself and is shared across all instances of that class, unlike instance variables which are unique to each object.
Declare a static variable using the static keyword:
public class Student {
private String name; // Instance variable - unique per student
private static int totalCount; // Static variable - shared by all students
public Student(String name) {
this.name = name;
totalCount++; // Increments the shared counter
}
public static int getTotalCount() {
return totalCount;
}
}Access static variables and methods through the class name rather than through an object instance:
Student s1 = new Student("Alice");
Student s2 = new Student("Bob");
System.out.println(Student.getTotalCount()); // Output: 2Use instance variables for data that varies between objects. Use static variables for data that should be shared across all instances.
Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read inputs for three books
String title1 = scanner.nextLine();
double price1 = Double.parseDouble(scanner.nextLine());
String title2 = scanner.nextLine();
double price2 = Double.parseDouble(scanner.nextLine());
String title3 = scanner.nextLine();
double price3 = Double.parseDouble(scanner.nextLine());
// TODO: Create three Book objects using the inputs above
// TODO: Print each book's title and price in format: [title]: $[price]
// Use String.format("%.2f", price) for formatting the price to 2 decimal places
// TODO: Print the total number of books using the static method
// Format: Total books: [count]
// Remember to access static method through class name: Book.getTotalBooks()
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System