
- Java Tutorial
- Java - Home
- Java - Overview
- Java - Environment Setup
- Java - Basic Syntax
- Java - Object & Classes
- Java - Constructors
- Java - Basic Datatypes
- Java - Variable Types
- Java - Modifier Types
- Java - Basic Operators
- Java - Loop Control
- Java - Decision Making
- Java - Numbers
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Date & Time
- Java - Regular Expressions
- Java - Methods
- Java - Files and I/O
- Java - Exceptions
- Java - Inner classes
- Java Object Oriented
- Java - Inheritance
- Java - Overriding
- Java - Polymorphism
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java Advanced
- Java - Data Structures
- Java - Collections
- Java - Generics
- Java - Serialization
- Java - Networking
- Java - Sending Email
- Java - Multithreading
- Java - Applet Basics
- Java - Documentation
- Java Useful Resources
- Java - Questions and Answers
- Java - Quick Guide
- Java - Useful Resources
- Java - Discussion
- Java - Examples
Class and Static Variables in Java
Class variables are also known as static variables, and they are declared outside a method, with the help of the keyword ‘static’.
Static variable is the one that is common to all the instances of the class. A single copy of the variable is shared among all objects.
Example
public class Demo{ static int my_count=2; public void increment(){ my_count++; } public static void main(String args[]){ Demo obj_1=new Demo(); Demo obj_2=new Demo(); obj_1.increment(); obj_2.increment(); System.out.println("The count of first object is "+obj_1.my_count); System.out.println("The count of second object is "+obj_2.my_count); } }
Output
The count of first object is 4 The count of second object is 4
A class named Demo defines a static variable, and a function named ‘increment’ that increments the value of the static variable. The main function creates two instances of the class, and the increment function is called on both the object. The count is printed on the screen. It shows that static variable is shared between objects.
- Related Articles
- Class and Static Variables in C#
- Declare static variables and methods in an abstract class in Java
- Class or Static Variables in Python?
- Static and non static blank final variables in Java
- Static variables in Java
- Final static variables in Java
- Demonstrate static variables, methods and blocks in Java
- Static class in Java
- What are class variables, instance variables and local variables in Java?
- Can we serialize static variables in Java?
- Are static local variables allowed in Java?\n
- Templates and Static variables in C++
- Interface variables are static and final by default in Java, Why?
- What is the difference between class variables and instance variables in Java?
- Kotlin static methods and variables

Advertisements