Showing posts with label javajvms. Show all posts
Showing posts with label javajvms. Show all posts

Monday, 16 March 2015

this keyword in java

this keyword in java

There can be a lot of usage of java this keyword. In java, this is areference variable that refers to the current object.

Usage of java this keyword

Here is given the 6 usage of java this keyword.
  1. this keyword can be used to refer current class instance variable.
  2. this() can be used to invoke current class constructor.
  3. this keyword can be used to invoke current class method (implicitly)
  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 keyword can also be used to return the current class instance.
Suggestion: If you are beginner to java, lookup only two usage of this keyword.
java this keyword


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

If there is ambiguity between the instance variable and parameter, 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 Student10{  
    int id;  
    String name;  
      
    student(int id,String name){  
    id = id;  
    name = name;  
    }  
    void display(){System.out.println(id+" "+name);}  
  
    public static void main(String args[]){  
    Student10 s1 = new Student10(111,"Karan");  
    Student10 s2 = new Student10(321,"Aryan");  
    s1.display();  
    s2.display();  
    }  
}  
Output:0 null
       0 null
In the above example, parameter (formal arguments) and instance
variables are same that is why we are using this keyword to
distinguish between local variable and instance variable.

Solution of the above problem by this keyword

//example of this keyword   class Student11{       int id;       String name;              Student11(int id,String name){       this.id = id;       this.name = name;       }       void display(){System.out.println(id+" "+name);}       public static void main(String args[]){       Student11 s1 = new Student11(111,"Karan");       Student11 s2 = new Student11(222,"Aryan");       s1.display();       s2.display();   }   }  
Output111 Karan
       222 Aryan
this keyword

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

class Student12{       int id;       String name;              Student12(int i,String n){       id = i;       name = n;       }       void display(){System.out.println(id+" "+name);}       public static void main(String args[]){       Student12 e1 = new Student12(111,"karan");       Student12 e2 = new Student12(222,"Aryan");       e1.display();       e2.display();   }   }  
Output:111 Karan
       222 Aryan

2) this() can be used to invoked current class constructor.

The this() constructor call can be used to invoke the current class
constructor (constructor chaining). This approach is better
if you have many constructors in the class and
want to reuse that constructor.
//Program of this() constructor call (constructor chaining)      class Student13{       int id;       String name;       Student13(){System.out.println("default constructor is invoked");}              Student13(int id,String name){       this ();//it is used to invoked current class constructor.       this.id = id;       this.name = name;       }       void display(){System.out.println(id+" "+name);}              public static void main(String args[]){       Student13 e1 = new Student13(111,"karan");       Student13 e2 = new Student13(222,"Aryan");       e1.display();       e2.display();      }   }  
Output:
       default constructor is invoked
       default constructor is invoked
       111 Karan
       222 Aryan

Where to use this() constructor call?

The this() constructor call should be used to reuse the constructor in 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.
  class Student14{       
int id;       
String name;       
String city;              
Student14(int id,String name){       
this.id = id;      
 this.name = name;       }       
Student14(int id,String name,String city){       this(id,name);//now no need to initialize id and name       
this.city=city;       }       
void display(){System.out.println(id+" "+name+" "+city);}              public static void main(String args[]){       
Student14 e1 = new Student14(111,"karan");       Student14 e2 = new Student14(222,"Aryan","delhi");      
 e1.display();       
e2.display();     
 }  
}  
Output:111 Karan null
       222 Aryan delhi

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

class Student15{       int id;       String name;       Student15(){System.out.println("default constructor is invoked");}              Student15(int id,String name){       id = id;       name = name;       this ();//must be the first statement       }       void display(){System.out.println(id+" "+name);}              public static void main(String args[]){       Student15 e1 = new Student15(111,"karan");       Student15 e2 = new Student15(222,"Aryan");       e1.display();       e2.display();      }   }  
Output:Compile Time Error

3)The this keyword can be used to invoke current class method (implicitly).

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
this keyword
class S{  
  void m(){  
  System.out.println("method is invoked");  
  }  
  void n(){  
  this.m();//no need because compiler does it for you.  
  }  
  void p(){  
  n();//complier will add this to invoke n() method as this.n()  
  }  
  public static void main(String args[]){  
  S s1 = new S();  
  s1.p();  
  }  
}  
Output:method is invoked

4) this keyword can be passed 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: class S2{     void m(S2 obj){     System.out.println("method is invoked");     }     void p(){     m(this);     }          public static void main(String args[]){     S2 s1 = new S2();     s1.p();     }   }  
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.

5) The this keyword can be passed 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: class B{     A4 obj;     B(A4 obj){       this.obj=obj;     }     void display(){       System.out.println(obj.data);//using data member of A4 class     }   }      class A4{     int data=10;     A4(){      B b=new B(this);      b.display();     }     public static void main(String args[]){      A4 a=new A4();     }   }  
Output:10

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

We can return the 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

return_type method_name(){   return this;   }  

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

class A{   A getA(){   return this;   }   void msg(){System.out.println("Hello java");}   }      class Test1{   public static void main(String args[]){   new A().getA().msg();   }   }  
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. class A5{   void m(){   System.out.println(this);//prints same reference ID   }      public static void main(String args[]){   A5 obj=new A5();   System.out.println(obj);//prints the reference ID      obj.m();   }  
Output:A5@22b3ea59
       A5@22b3ea59

Java static keyword

Java static keyword

The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
The static can be:
  1. variable (also known as class variable)
  2. method (also known as class method)
  3. block
  4. nested class

1) Java static variable

If you declare any variable as static, it is known static variable.
  • The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
  • The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

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

Understanding problem without static variable

class Student{  
     int rollno;  
     String name;  
     String college="ITS";  
}  

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

Java static property is shared to all objects.

Example of static variable

//Program of static variable  
  
class Student8{  
   int rollno;  
   String name;  
   static String college ="ITS";  
     
   Student8(int r,String n){  
   rollno = r;  
   name = n;  
   }  
 void display (){System.out.println(rollno+" "+name+" "+college);}  
  
 public static void main(String args[]){  
 Student8 s1 = new Student8(111,"Karan");  
 Student8 s2 = new Student8(222,"Aryan");  
   
 s1.display();  
 s2.display();  
 }  
}  
Output:111 Karan ITS
       222 Aryan ITS

Program of 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 to other objects. So each objects will have the value 1 in the count variable.

class
 Counter{   int count=0;//will get memory when instance is created      Counter(){   count++;   System.out.println(count);   }      public static void main(String args[]){      Counter c1=new Counter();   Counter c2=new Counter();   Counter c3=new Counter();       }   }

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.

class Counter2{  
static int count=0;//will get memory only once and retain its value  
  
Counter2(){  
count++;  
System.out.println(count);  
}  
  
public static void main(String args[]){  
  
Counter2 c1=new Counter2();  
Counter2 c2=new Counter2();  
Counter2 c3=new Counter2();  
  
 }  
}  
  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 object of a class.
  • A static method can be invoked without the need for creating an instance of a class.
  • static method can access static data member and can change the value of it.

Example of static method

//Program of changing the common property of all objects(static field).      class Student9{        int rollno;        String name;        static String college = "ITS";                static void change(){        college = "BBDIT";        }           Student9(int r, String n){        rollno = r;        name = n;        }           void display (){System.out.println(rollno+" "+name+" "+college);}          public static void main(String args[]){       Student9.change();          Student9 s1 = new Student9 (111,"Karan");       Student9 s2 = new Student9 (222,"Aryan");       Student9 s3 = new Student9 (333,"Sonoo");          s1.display();       s2.display();       s3.display();       }   }  

Output:111 Karan BBDIT
       222 Aryan BBDIT
       333 Sonoo BBDIT

Another example of static method that performs normal calculation

//Program to get cube of a given number by static method      class Calculate{     static int cube(int x){     return x*x*x;     }        public static void main(String args[]){     int result=Calculate.cube(5);     System.out.println(result);     }   }  
Output:125

Restrictions for 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.
class A{    int a=40;//non static        public static void main(String args[]){     System.out.println(a);    }   }   

Output:Compile Time Error

Q) why java main method is static?

Ans) because object is not required to call static method if it were non-static method, jvm create 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 main method at the time of classloading.

Example of static block

class A2{     static{System.out.println("static block is invoked");}     public static void main(String args[]){      System.out.println("Hello main");     }   }  
Output:static block is invoked
       Hello main

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

Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
class A3{     static{     System.out.println("static block is invoked");     System.exit(0);     }   }  
Output:static block is invoked (if not JDK7)
In JDK7 and above, output will be:
Output:Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)