Core Java SQL Oracle PHP Examples JSP JDBC MORE

Java static keyword


Static keyword:

Static keyword belongs to the class than instance of the class .

Java static variable:

  1. The static variable to refer the common properties of all objects.
  2. Goto memory only once in class area at the time of class loading.
  3. Makes program memory efficient.

Example by using static variables

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();
}
}

Answer:

220 Divya BARABATI
330 Mitra BARABATI

Example by using with out static variable:

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();
}
}

Answer:

1
1
1

Java static method:

  1. It belongs to the class rather than object of class.
  2. It can be invoked without the need for creating an instance of an class.
  3. It can access static data member and can change the value of it.

Restriction of static method:

  1. Static method cannot use non-static data member or call non-static method directly.
  2. This and super cannot be used in static context.

Example by using 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();
}
}

Answer:

220 Divya BBSR
330 Mitra BBSR
440 Nirmal BBSR

Java static block:

  1. It is used to initialised the static data member.
  2. It is executed before main method at the time of class loading.

Example of static block:

class p
{
static
{
System.out.println("My name is Divya");
}
public static void main(String args[]){
System.out.println("Hello world");
}
}

Answer:

My name is Divya
Hello world