Java Static Keyword, Variables and Methods

In this tutorial, you will learn about static variables and methods in java programming language.

You will learn what is static keyword, what is its use, how to create static variables and methods, how do they work, how do they differ from normal variables and methods in detail with example.

Source Code for Source Code for Parents.java

1 package oops;
2 
3 public class Parents {
4     String name;
5 }


Source Code for Source Code for Student.java

 1 package oops;
 2 
 3 public class Student {
 4     public String name;
 5     public int age;
 6     public static int nostudents = 0;
 7     
 8     public Student(){
 9         nostudents++;
10         System.out.println("This is the "+nostudents+"object created from this class");
11     }
12     
13     public static void howManyStudents(){
14         System.out.println("There are "+ nostudents+" students");
15         
16     }
17     
18     public void introduce(){
19         System.out.println("Hey i'm "+name+" and i'm "+age+" years old");
20         howManyStudents();
21     }
22     
23 }


Source Code for Source Code for Tutorials.java

 1 package oops;
 2 
 3 public class Tutorials {
 4 
 5     public static void main(String[] args) {
 6             
 7         System.out.println(Student.nostudents);
 8 
 9         Student anil = new Student();
10         Student shreesh = new Student();
11         
12         anil.name = "anil";
13         anil.age = 24;
14         
15         shreesh.name = "Shreesh";
16         shreesh.age = 25;
17         
18         anil.introduce();
19         shreesh.introduce();
20         
21         Student.howManyStudents();
22         
23     }
24 }

Watch this video to learn how this works