Java Program for Static Variable and Static Method

Java program for static variable and static method

// 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
Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment