Skip to main content

Practical-15

Write a java program which shows the use of Static Members.

Introduction

Static members are class level members in Java that are declared using the static keyword. They are created when the class is first loaded and can be shared by all the objects of that class. These members can be accessed directly using the class name and not the object of the class. They are mostly used to define and share constants among all the objects of a class.

Code

class Program{
// static variable
static int a = 10;

// non-static variable
int b = 20;

// a static method
// that increments
// the value of a
// static variable
static void increment(){
a = a + 1;
}

// a non-static method
// that increments the
// value of a non-static
// variable
void incrementNonStatic(){
b = b + 1;
}

public static void main(String args[]){
Program.increment();

Program obj = new Program();

obj.incrementNonStatic();

System.out.println(Program.a);
System.out.println(obj.b);
}
}

Output

11 21

Explanation

This code uses a simple program to demonstrate the use of static members in Java. It has a static variable "a" that is incremented by a static method "increment". The static variable can be accessed directly by class name, without having to create an object of the class. It has a non-static variable "b" too which is incremented by a non-static method "incrementNonStatic", which can only be accessed after creating an object of the class.