Demonstrate use of 'static' keyword

There are three kinds of variables in Java:
  • Local variables
  • Instance variables
  • Class/static variables
Local variables are declared in methods, constructors, or blocks. They are created when a method, constructor or block is entered and destroyed after exit from methods, constructors, or blocks.

Instance variables are declared in a class, but outside a method, constructor or any block. They are created and have allotted a memory when an object of class is created. Instance variables can be accessed by using object name like object-name.variable-name. In program x, y and z are instance variables. Whenever you create an object of class each copy of x, y, z will be created for that object separately.

Class/static variable are also known as static variables. They are declared using the static keyword in a class, but outside a method, constructor or a block. Static variables are created when the program starts and destroyed when the program stops. It create a single copy of variable which is common to all objects of class.

In the program numCircle is a static variable. Static variables can be accessed by calling the class name as shown below:
class-name.variable-name;

In this program, we have created static variable count and initialized it to zero which is incremented by one when new object is created. The output of this program is to display how many objects are created.


PROGRAM
public class StaticDemo {

 static int count=0;
 
 StaticDemo() {
  
  count++;
 }
 
 public static void main(String args[]) {
  
  StaticDemo s1 = new StaticDemo();
  StaticDemo s2 = new StaticDemo();
  StaticDemo s3 = new StaticDemo();
  System.out.println(count+" objects are created!");
 }
}
OUTPUT
C:\>javac StaticDemo.java
C:\>java StaticDemo
3 objects are created!

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative