static Method and variable in java, static variable increment using methods

Java Programming Language Class, Object and Methods in java (Article) Class, Object and Methods in java (Program)

3047

Program:

 public class StaticDemo{
   public static void main(String args[]){
     Student s1 = new Student();
     s1.showData();
     Student s2 = new Student();
     s2.showData();
     //Student.b++;
     //s1.showData();
  }
}

class Student {
int a; //initialized to zero
static int b; //initialized to zero only when class is loaded not for each object created.

  Student(){
   //Constructor incrementing static variable b
   b++;
  }

   public void showData(){
      System.out.println("Value of a = "+a);
      System.out.println("Value of b = "+b);
   }
//public static void increment(){
//a++;
//}

}

Output:

Value of a = 0
Value of b = 1
Value of a = 0
Value of b = 2
Press any key to continue . . .

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.