Syntax of creating static variable-
access-modifier static data-type variable;
Example
static int counter;
Syntax of accessing static variable-
class-name.staticVariable; or object.staticVariable;
public class StaticExample { static int counter; public StaticExample() { counter++; } public static void main(String args[]) { System.out.println("No of objects = "+StaticExample.counter); StaticExample se = new StaticExample(); System.out.println("No of objects = "+se.counter); StaticExample se2 = new StaticExample(); se2.counter=5; System.out.println("No of objects = "+se.counter); } }
Output
No of objects = 0 No of objects = 1 No of objects = 5
Syntax
access-modifier static return-type methodName(parameters) { //code to be written inside method }
class Mathematics { public static int add(int n1, int n2) { return n1 + n2; } public static int sub(int n1, int n2) { return n1 - n2; } public static void main(String args[]) { System.out.println("Sum of 10 and 12 is "+Mathematics.add(10,12)); System.out.println("Subtraction of 10 and 12 is "+Mathematics.sub(10,12)); } }
Output
Sum of 10 and 12 is 22 Subtraction of 10 and 12 is -2
Syntax
static{ //code to initialize static variables }
public class Bonus { private static int reward; static{ reward = 10; } public static void main(String args[]) { System.out.println("Reward Point = "+Bonus.reward); } }
Output
Reward Point = 10
static method | instance method |
---|---|
A method that is declared static is called static method. | A method that is not declared without static keyword is called instance method. |
static method can be called by class name or an instance of the class. | Instance method can be only be called by object of the class. |
It cannot be access non-static members of the class. | Both static and non-static members can be access by instance methods. |