Study Guides/Computer Science/Static Keyword in Java
Study Guide ยท Computer Science

What is the 'static' Keyword in Java?

In Java programming, the static keyword is a highly important non-access modifier. It is primarily used for memory management and defines how variables and methods belong to a class.

Question (Click to Flip)

Can a local variable be static in Java?

Answer

No. Java does not allow you to declare a local variable (a variable inside a method) as static. Static variables must be declared at the class level.

Card 1 of 1 free previews

Key Facts

Memory for static variables is allocated only once in the class area at the exact time the class is loaded into the JVM memory, making it highly memory-efficient.

The Core Concept

Normally, in Object-Oriented Programming (OOP), if a class has a variable, that variable is created independently for every single object (instance) you create.

However, if you declare a variable or method as static, it means that it belongs to the Class itself, rather than to any specific object. There is only ONE copy of a static variable in memory, and all objects of that class share it.

1. Static Variables

Used for properties that are common to all objects. Example: If you create a Student class, studentName will be normal (different for each student). But collegeName can be static because all students share the exact same college. This saves memory.

2. Static Methods

A static method belongs to the class. The biggest advantage is that you do not need to create an object to call a static method. You can call it directly using the class name (e.g., Math.round()). Rule: A static method can only directly access other static variables/methods. It cannot use the this or super keywords.

Why is 'main' static?

Every Java program starts with public static void main(String[] args). It is static because the Java Virtual Machine (JVM) needs to call the main method to start the program before any objects are created. If it weren't static, the JVM wouldn't be able to run the program!

Questions and Answers

Can a local variable be static in Java?+

No. Java does not allow you to declare a local variable (a variable inside a method) as static. Static variables must be declared at the class level.

More in Computer Science

Study Smarter with Shinyu.ai

Turn this guide into revision flashcards, a practice exam, or an AI-generated podcast โ€” free, no signup required.