The static keyword is mainly used for memory management only.
The static keyword can be used with.
- Variables
- Methods
- Block
- Nested Class
The property of the static is shared among all the objects.
class Student { int rno; String name; static String college ="JPS"; Student(int r, String n) { rno = r; name = n; } void show () { System.out.println(rno+" "+name+" "+college); } } class StaticVariable { public static void main(String args[]) { Student s1 = new Student(101,"Tanmay"); Student s2 = new Student(102,"Shivam"); s1.show(); s2.show(); } } Output: 101 Tanmay JPS 102 Shivam JPS
- Program of the counter with Static Variable.
class StaticCounter { static int count=0; StaticCounter() { count++; System.out.println(count); } public static void main(String args[]) { StaticCounter c1=new StaticCounter(); StaticCounter c2=new StaticCounter(); StaticCounter c3=new StaticCounter(); } } Output: 1 2 3
- Static Method :
class Student { int rno; String name; static String school = "JPS"; static void change() { school = "DPS"; } Student(int r, String n) { rno = r; name = n; } void show() { System.out.println(rno+" "+name+" "+school); } } class StaticMethod { public static void main(String args[]) { Student.change(); Student s1 = new Student(101,"Tanmay"); Student s2 = new Student(102,"Sanyam"); Student s3 = new Student(103,"Sanskar"); s1.show(); s2.show(); s3.show(); } } Output: 101 Tanmay DPS 102 Sanyam DPS 103 Sanskar DPS
- Static Block :
class StaticBlock { static { System.out.println("static block"); } public static void main(String args[]) { System.out.println("Hello main"); } } Output: static block Hello main