Static keyword:
Static keyword belongs to the class than instance of the class .
Java static variable:
class Student{
int rollno;
String name;
static String field ="BARABATI";
Student(int p,String q){
rollno = p;
name = q;
}
void display (){System.out.println(rollno+" "+name+" "+field);}
public static void main(String args[]){
Student s1 = new Student(220,"Divya");
Student s2 = new Student(330,"Mitra");
s1.display();
s2.display();
}
}
220 Divya BARABATI
330 Mitra BARABATI
class TestCounter{
int count=0;
testCounter(){
count++;
System.out.println(count);
}
public static void main(String args[]){
test Counter c1=new test Counter();
test Counter c2=new test Counter();
test Counter c3=new test Counter();
}
}
1
1
1
Java static method:
Restriction of static method:
class Student{
int rollno;
String name;
static String college field = "BARABATI";
static void change(){
Place = "BBSR";
}
Student(int p, String q){
rollno = p;
name = q;
}
void display (){System.out.println(rollno+" "+name+" "+Place);}
public static void main(String args[]){
Student9.change();
Student s1 = new Student (220,"Divya");
Student s2 = new Student (330,"Mitra");
Student s3 = new Student (440,"Nirmal");
s1.display();
s2.display();
s3.display();
}
}
220 Divya BBSR
330 Mitra BBSR
440 Nirmal BBSR
Java static block:
class p
{
static
{
System.out.println("My name is Divya");
}
public static void main(String args[]){
System.out.println("Hello world");
}
}
My name is Divya
Hello world