xxxxxxxxxx
// A static variable is shared among all instances of a class
// In example below, Slogan class has a static variable called
// count that was used to count the number of Slogan objects created.
public class Main {
public static void main(String[] args) {
Slogan slg1 = new Slogan("Talk is cheap");
Slogan slg2 = new Slogan("Live free or die");
System.out.println(Slogan.getCount());}
}
class Slogan {
private String phrase;
// Only one copy of variable count is created
// And it would be shared among all Slogan objects
private static int count = 0;
public Slogan(String phrase) {
this.phrase = phrase;
count++;}
public static int getCount() {
return count;}
}
xxxxxxxxxx
// Java program to demonstrate execution
// of static blocks and variables
class Test
{
// static variable
static int a = m1();
// static block
static {
System.out.println("Inside static block");
}
// static method
static int m1() {
System.out.println("from m1");
return 20;
}
// static method(main !!)
public static void main(String[] args)
{
System.out.println("Value of a : "+a);
System.out.println("from main");
}
}