ADVERTISEMENT
ADVERTISEMENT

Java program for static variable and static method

Static Variable:

In java when a variable declared as static, it is called a class variable and all objects (instances) share the same variable.

Static Method:

A static method always accesses static data and it also belongs to class not instance. Hence the static method is called with the class name not object name. It cannot be referred to like this or super keyword.

Program:

// Java program to demonstrate example of 
// static variable and static method

import java.util.*;

class Item {
    private String itemName;
    private int quantity;
    private static int cnt = 0; //variable to count

    public void getItem() {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter item name: ");
        itemName = sc.next();
        System.out.print("Enter item quantity: ");
        quantity = sc.nextInt();

        //increment counter
        cnt++;
    }

    public void showItem() {
        System.out.println("Item Name: " + itemName + "\tQuantity: " + quantity);
    }

    public static int getCounter() {
        return cnt;
    }
}

public class StaticVar {
    public static void main(String[] s) {
        try {
            Item I1 = new Item();
            Item I2 = new Item();
            Item I3 = new Item();

            I1.getItem();
            I2.getItem();
            I3.getItem();

            I1.showItem();
            I2.showItem();
            I3.showItem();

            System.out.println("Total object created (total items are): " + Item.getCounter());
        } catch (Exception e) {
            System.out.println(e.toString());
        }

    }
}

Output:

Enter item name: Dove
Enter item quantity: 5
Enter item name: Rin
Enter item quantity: 10
Enter item name: Fenna
Enter item quantity: 20
Item Name: Dove	Quantity: 5
Item Name: Rin	Quantity: 10
Item Name: Fenna	Quantity: 20
Total object created (total items are): 3

private static int cnt - is a private member for class StaticVar and it is static too, it means the variable cnt can not be accessed outside of the class (due to private) and it is allocated once (due to static).

getCounter() - is a static method, which is calling with class name Item.

Java Static Variable, Class, Method & Block Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.