Any variable when declared with the keyword “static” is known as static variable or class variable in JAVA. Static variable is used to fulfill the common properties of all objects. For example: institute name of students is common for all students so it will be declared as static variable ...
In the above example, as static keyword is used inside the innerclass so it will be called as static class. The s variable is also declared as static so it can be called in the static class. Static Variable Any variable when declared with the keyword “static”, it is known as static ...
Static variable example in Java classVariableDemo{staticintcount=0;publicvoidincrement(){count++;}publicstaticvoidmain(Stringargs[]){VariableDemoobj1=newVariableDemo();VariableDemoobj2=newVariableDemo();obj1.increment();obj2.increment();System.out.println("Obj1: count is="+obj1.count);System....
The static keyword in Java is a non-access modifier. This keyword is used with variables, methods, blocks of code and classes. A class, method or variable declared with a static keyword belongs to the class itself rather than to any specific instance of the class. This means static members...
Example #3 This program demonstrates the static variable that becomes accessible for the static class if the fields are declared and defined with static as a modifier; otherwise, the scope of static won’t get satisfied, and it will throw compilation error like the earlier example. ...
publicclassStaticExample{staticint counter=0;staticvoidincrementCounter(){counter++;}publicstaticvoidmain(String[]args){StaticExample.incrementCounter();System.out.println("Counter: "+StaticExample.counter);}} In this example, the static variablecounteris shared among all instances of theStaticExamplecl...
publicclassMain{publicstaticvoidmain(String[]args){StaticVariableExample.increaseCount();System.out.println("Count in Main: "+StaticVariableExample.count);AnotherClassLoaderanotherClassLoader=newAnotherClassLoader();anotherClassLoader.loadClassWithSameClassLoader();}} ...
staticVar); // Output: Static variable: 10 MyClass obj = new MyClass(); System.out.println("Non-static variable: " + obj.nonStaticVar); // Output: Non-static variable: 20 } } In the example above, we have declared a static variable staticVar and a non-static variable nonStaticVar...
In this example, the static block is executed when the class StaticExample is loaded into memory, initializing the static variable num to 10. Static Nested Classes Inner classes can also be declared static. These classes belong to the outer class, not to any instance of the outer class. ...
Let’s see how to use static variable, method and static class in a test program.TestStatic.java package com.journaldev.misc; public class TestStatic { public static void main(String[] args) { StaticExample.setCount(5); //non-private static variables can be accessed with class name ...