0% found this document useful (0 votes)
23 views

Static Keyword

Uploaded by

yashuogirala
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Static Keyword

Uploaded by

yashuogirala
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

static keyword

The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to
the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable


If you declare any variable as static, it is known as a static variable.

 The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
 The static variable gets memory only once in the class area at the time of class
loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).


Understanding the problem without static variable

1. class Student{  
2.      int rollno;  
3.      String name;  
4.      String college="ITS";  
5. }  

Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and name,
so instance data member is good in such case. Here, "college" refers to the common property
of all objects. If we make it static, this field will get the memory only once.

Java static property is shared to all objects.

Example of static variable

1. //Java Program to demonstrate the use of static variable  
2. class Student{  
3.    int rollno;//instance variable  
4.    String name;  
5.    static String college ="ITS";//static variable  
6.    //constructor  
7.    Student(int r, String n){  
8.    rollno = r;  
9.    name = n;  
10.    }  
11.    //method to display the values  
12.    void display (){System.out.println(rollno+" "+name+" "+college);}  
13. }  
14. //Test class to show the values of objects  
15. public class TestStaticVariable1{  
16.  public static void main(String args[]){  
17.  Student s1 = new Student(111,"Karan");  
18.  Student s2 = new Student(222,"Aryan");  
19.  //we can change the college of all objects by the single line of code  
20.  //Student.college="BBDIT";  
21.  s1.display();  
22.  s2.display();  
23.  }  
24. }  

Test it Now

Output:

111 Karan ITS


222 Aryan ITS
Program of the counter without static variable

In this example, we have created an instance variable named count which is incremented in
the constructor. Since instance variable gets the memory at the time of object creation, each
object will have the copy of the instance variable. If it is incremented, it won't reflect other
objects. So each object will have the value 1 in the count variable.

1. //Java Program to demonstrate the use of an instance variable  
2. //which get memory each time when we create an object of the class.  
3. class Counter{  
4. int count=0;//will get memory each time when the instance is created  
5.   
6. Counter(){  
7. count++;//incrementing value  
8. System.out.println(count);  
9. }  
10.   
11. public static void main(String args[]){  
12. //Creating objects  
13. Counter c1=new Counter();  
14. Counter c2=new Counter();  
15. Counter c3=new Counter();  
16. }  
17. }  
Test it Now

Output:

1
1
1

Program of counter by static variable

As we have mentioned above, static variable will get the memory only once, if any object
changes the value of the static variable, it will retain its value.

1. //Java Program to illustrate the use of static variable which  
2. //is shared with all objects.  
3. class Counter2{  
4. static int count=0;//will get memory only once and retain its value  
5.   
6. Counter2(){  
7. count++;//incrementing the value of static variable  
8. System.out.println(count);  
9. }  
10.   
11. public static void main(String args[]){  
12. //creating objects  
13. Counter2 c1=new Counter2();  
14. Counter2 c2=new Counter2();  
15. Counter2 c3=new Counter2();  
16. }  
17. }  

Test it Now

Output:

1
2
3

2) Java static method


If you apply static keyword with any method, it is known as static method.

 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 A static method can access static data member and can change the value of it.

Example of static method


1. //Java Program to demonstrate the use of a static method.  
2. class Student{  
3.      int rollno;  
4.      String name;  
5.      static String college = "ITS";  
6.      //static method to change the value of static variable  
7.      static void change(){  
8.      college = "BBDIT";  
9.      }  
10.      //constructor to initialize the variable  
11.      Student(int r, String n){  
12.      rollno = r;  
13.      name = n;  
14.      }  
15.      //method to display values  
16.      void display(){System.out.println(rollno+" "+name+" "+college);}  
17. }  
18. //Test class to create and display the values of object  
19. public class TestStaticMethod{  
20.     public static void main(String args[]){  
21.     Student.change();//calling change method  
22.     //creating objects  
23.     Student s1 = new Student(111,"Karan");  
24.     Student s2 = new Student(222,"Aryan");  
25.     Student s3 = new Student(333,"Sonoo");  
26.     //calling display method  
27.     s1.display();  
28.     s2.display();  
29.     s3.display();  
30.     }  
31. }  

Test it Now
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Another example of a static method that performs a normal calculation

1. //Java Program to get the cube of a given number using the static method  
2.   
3. class Calculate{  
4.   static int cube(int a){  
5.   return a*a*a;  
6.   }  
7.   
8.   public static void main(String args[]){  
9.   int result=Calculate.cube(5);  
10.   System.out.println(result);  
11.   }  
12. }  

Test it Now
Output:125

Restrictions for the static method

There are two main restrictions for the static method. They are:

1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.

1. class A{  
2.  int a=40;//non static  
3.    
4.  public static void main(String args[]){  
5.   System.out.println(a);  
6.  }  
7. }        

Test it Now
Output:Compile Time Error

Q) Why is the Java main method static?

Ans) It is because the object is not required to call a static method. If it were a non-static
method, JVM creates an object first then call main() method that will lead the problem of
extra memory allocation.

3) Java static block


 Is used to initialize the static data member.
 It is executed before the main method at the time of class loading.

Example of static block

1. class A2{  
2.   static{System.out.println("static block is invoked");}  
3.   public static void main(String args[]){  
4.    System.out.println("Hello main");  
5.   }  
6. }  

Test it Now
Output:static block is invoked
Hello main

Q) Can we execute a program without main() method?

Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK
1.7, it is not possible to execute a Java class without the main method.

1. class A3{  
2.   static{  
3.   System.out.println("static block is invoked");  
4.   System.exit(0);  
5.   }  
6. }  

Test it Now

Output:

static block is invoked

Since JDK 1.7 and above, output would be:

Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

this keyword in Java

There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.
Usage of Java this keyword
Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.

2. this can be used to invoke current class method (implicitly)

3. this() can be used to invoke current class constructor.

4. this can be passed as an argument in the method call.

5. this can be passed as argument in the constructor call.

6. this can be used to return the current class instance from the method.
1) this: to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.

Understanding the problem without this keyword

Let's understand the problem if we don't use this keyword by the example given below:

1. class Student{  
2. int rollno;  
3. String name;  
4. float fee;  
5. Student(int rollno,String name,float fee){  
6. rollno=rollno;  
7. name=name;  
8. fee=fee;  
9. }  
10. void display(){System.out.println(rollno+" "+name+" "+fee);}  
11. }  
12. class TestThis1{  
13. public static void main(String args[]){  
14. Student s1=new Student(111,"ankit",5000f);  
15. Student s2=new Student(112,"sumit",6000f);  
16. s1.display();  
17. s2.display();  
18. }}  

Test it Now

Output:

0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and instance variables are same. So, we
are using this keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword

1. class Student{  
2. int rollno;  
3. String name;  
4. float fee;  
5. Student(int rollno,String name,float fee){  
6. this.rollno=rollno;  
7. this.name=name;  
8. this.fee=fee;  
9. }  
10. void display(){System.out.println(rollno+" "+name+" "+fee);}  
11. }  
12.   
13. class TestThis2{  
14. public static void main(String args[]){  
15. Student s1=new Student(111,"ankit",5000f);  
16. Student s2=new Student(112,"sumit",6000f);  
17. s1.display();  
18. s2.display();  
19. }}  

Test it Now

Output:
111 ankit 5000.0
112 sumit 6000.0

If local variables(formal arguments) and instance variables are different, there is no need to
use this keyword like in the following program:

Program where this keyword is not required

1. class Student{  
2. int rollno;  
3. String name;  
4. float fee;  
5. Student(int r,String n,float f){  
6. rollno=r;  
7. name=n;  
8. fee=f;  
9. }  
10. void display(){System.out.println(rollno+" "+name+" "+fee);}  
11. }  
12.   
13. class TestThis3{  
14. public static void main(String args[]){  
15. Student s1=new Student(111,"ankit",5000f);  
16. Student s2=new Student(112,"sumit",6000f);  
17. s1.display();  
18. s2.display();  
19. }}  

Test it Now

Output:

111 ankit 5000.0


112 sumit 6000.0

It is better approach to use meaningful names for variables. So we use same name for
instance variables and parameters in real time, and always use this keyword.

2) this: to invoke current class method

You may invoke the method of the current class by using the this keyword. If you don't use
the this keyword, compiler automatically adds this keyword while invoking the method. Let's
see the example
1. class A{  
2. void m(){System.out.println("hello m");}  
3. void n(){  
4. System.out.println("hello n");  
5. //m();//same as this.m()  
6. this.m();  
7. }  
8. }  
9. class TestThis4{  
10. public static void main(String args[]){  
11. A a=new A();  
12. a.n();  
13. }}  

Test it Now

Output:

hello n
hello m

3) this() : to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor. It is used to
reuse the constructor. In other words, it is used for constructor chaining.

Calling default constructor from parameterized constructor:


1. class A{  
2. A(){System.out.println("hello a");}  
3. A(int x){  
4. this();  
5. System.out.println(x);  
6. }  
7. }  
8. class TestThis5{  
9. public static void main(String args[]){  
10. A a=new A(10);  
11. }}  

Test it Now

Output:

hello a
10

Calling parameterized constructor from default constructor:

1. class A{  
2. A(){  
3. this(5);  
4. System.out.println("hello a");  
5. }  
6. A(int x){  
7. System.out.println(x);  
8. }  
9. }  
10. class TestThis6{  
11. public static void main(String args[]){  
12. A a=new A();  
13. }}  

Test it Now

Output:
5
hello a

Real usage of this() constructor call

The this() constructor call should be used to reuse the constructor from the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see
the example given below that displays the actual use of this keyword.

1. class Student{  
2. int rollno;  
3. String name,course;  
4. float fee;  
5. Student(int rollno,String name,String course){  
6. this.rollno=rollno;  
7. this.name=name;  
8. this.course=course;  
9. }  
10. Student(int rollno,String name,String course,float fee){  
11. this(rollno,name,course);//reusing constructor  
12. this.fee=fee;  
13. }  
14. void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}  
15. }  
16. class TestThis7{  
17. public static void main(String args[]){  
18. Student s1=new Student(111,"ankit","java");  
19. Student s2=new Student(112,"sumit","java",6000f);  
20. s1.display();  
21. s2.display();  
22. }}  

Test it Now

Output:

111 ankit java 0.0


112 sumit java 6000.0

Rule: Call to this() must be the first statement in constructor.


1. class Student{  
2. int rollno;  
3. String name,course;  
4. float fee;  
5. Student(int rollno,String name,String course){  
6. this.rollno=rollno;  
7. this.name=name;  
8. this.course=course;  
9. }  
10. Student(int rollno,String name,String course,float fee){  
11. this.fee=fee;  
12. this(rollno,name,course);//C.T.Error  
13. }  
14. void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}  
15. }  
16. class TestThis8{  
17. public static void main(String args[]){  
18. Student s1=new Student(111,"ankit","java");  
19. Student s2=new Student(112,"sumit","java",6000f);  
20. s1.display();  
21. s2.display();  
22. }}  

Test it Now

Output:

Compile Time Error: Call to this must be first statement in constructor

4) this: to pass as an argument in the method

The this keyword can also be passed as an argument in the method. It is mainly used in the
event handling. Let's see the example:

1. class S2{  
2.   void m(S2 obj){  
3.   System.out.println("method is invoked");  
4.   }  
5.   void p(){  
6.   m(this);  
7.   }  
8.   public static void main(String args[]){  
9.   S2 s1 = new S2();  
10.   s1.p();  
11.   }  
12. }  

Test it Now

Output:

method is invoked

Application of this that can be passed as an argument:

In event handling (or) in a situation where we have to provide reference of a class to another
one. It is used to reuse one object in many methods.

5) this: to pass as argument in the constructor call

We can pass the this keyword in the constructor also. It is useful if we have to use one object
in multiple classes. Let's see the example:

1. class B{  
2.   A4 obj;  
3.   B(A4 obj){  
4.     this.obj=obj;  
5.   }  
6.   void display(){  
7.     System.out.println(obj.data);//using data member of A4 class  
8.   }  
9. }  
10.   
11. class A4{  
12.   int data=10;  
13.   A4(){  
14.    B b=new B(this);  
15.    b.display();  
16.   }  
17.   public static void main(String args[]){  
18.    A4 a=new A4();  
19.   }  
20. }  

Test it Now
Output:10

6) this keyword can be used to return current class instance

We can return this keyword as an statement from the method. In such case, return type of the
method must be the class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement

1. return_type method_name(){  
2. return this;  
3. }  

Example of this keyword that you return as a statement from the method

1. class A{  
2. A getA(){  
3. return this;  
4. }  
5. void msg(){System.out.println("Hello java");}  
6. }  
7. class Test1{  
8. public static void main(String args[]){  
9. new A().getA().msg();  
10. }  
11. }  

Test it Now

Output:

Hello java

Proving this keyword

Let's prove that this keyword refers to the current class instance variable. In this program, we
are printing the reference variable and this, output of both variables are same.
1. class A5{  
2. void m(){  
3. System.out.println(this);//prints same reference ID  
4. }  
5. public static void main(String args[]){  
6. A5 obj=new A5();  
7. System.out.println(obj);//prints the reference ID  
8. obj.m();  
9. }  
10. }  

Test it Now

Output:

A5@22b3ea59
A5@22b3ea59

You might also like