bing
Flat 10% & upto 50% off + Free additional Courses. Hurry up!

this Keyword in Java

 

this keyword

It can be used inside the constructor or method in the class. It works as a reference to current object which constructor or method is being invoked. It performs following operations –

 

1. It is used to call the current constructor of class.

public class Intellipaat {

Intellipaat() {

this("Hello"); // Call parameterized constructor

System.out.println("Default Constructor");

}

 

Intellipaat(String s) {

System.out.println("Parameterized Constructor: " + s);

}

public static void main(String[] args) {

Intellipaat obj = new Intellipaat();

}

}

Output

Parameterized Constructor: Hello

Default Constructor

 

2. It can be used to call another method of class.

e.g.

 class Intellipaat{

void a(){

System.out.println("Method a");

}

void b(){

this.a(); /* if you not use ‘this’ then comiler automatically add this keyword while invoking method  */

}

void c(){

b();//compiler will add this to invoke n() method as this.n()

}

public static void main(String args[]){

Intellipaat in = new Intellipaat();

in.c();

}

}

Output

Method a

 

3. It can be passed as parameter in method.

e.g.

class Intellipaat{

void sample(Intellipaat i){

System.out.println("Hello Intellipaat");

}

void sample1(){

sample(this);

}

public static void main(String args[]){

Intellipaat i1 = new Intellipaat();

i1.sample1();

}

}

Output

Hello Intellipaat

 

4. It is used to refer current class instance variable.

e.g.

public class Employee{

int id;

String e_name;

Employee(int id,String e_name){

this.id = id;

this.e_name = e_name;

}

void show(){

System.out.println("Id and name of Employee:"+id+" "+e_name);

}

public static void main(String args[]){

Employee e1 = new Employee (1,"abc");

Employee e2 = new Employee (2,"xyz");

e1.show();

e2.show();

}

}

Output

Id and name of Employee:1 abc

Id and name of Employee:2 xyz

If you want to use same variable then it is needed to use this keyword. If you do not use this keyword then it will give null value.

Learn more about Cross-Platform Mobile Technology for Android and iOS using Java in this insightful blog now!

"0 Responses on this Keyword in Java"

Training in Cities

Bangalore, Hyderabad, Chennai, Delhi, Kolkata, UK, London, Chicago, San Francisco, Dallas, Washington, New York, Orlando, Boston

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.

top

Sales Offer

  • To avail this offer, enroll before 04th December 2016.
  • This offer cannot be combined with any other offer.
  • This offer is valid on selected courses only.
  • Please use coupon codes mentioned below to avail the offer
offer-june

Sign Up or Login to view the Free this Keyword in Java.