Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

"this" and with out "this" Keyword

Status
Not open for further replies.

munnanext

Programmer
Aug 20, 2004
49
US
package p2;

public class Test1 {
boolean temp;
int i;
/** Creates a new instance of Test1 */
public Test1(int i) {
System.out.println(i);
this.i = i;
}

public static void main(String args[]){

Test1 objTest1 = new Test1(5);
System.out.println(objTest1.i);
}


}

This Program Prints 5 and 5

But when I do small modification to the above program (by removing this key word)

package p2;

public class Test1 {
boolean temp;
int i;
/** Creates a new instance of Test1 */
public Test1(int i) {
System.out.println(i);
i = i; // Here I removed this Key Word
}

public static void main(String args[]){

Test1 objTest1 = new Test1(5);
System.out.println(objTest1.i);
}


}

I am getting output as 5 and 0.

Can you explain me why this is happening. I am expecting 5 and 5 in both cases.

Tahnks
 
Within your Test1 constructor, the int "i" that is passed in is local to that method - ie it has nothing to do with the class level "i" variable. So when you say "i = i", all you are saying is "my local variable i = my local variable i".

When you add the "this" keyword, you are saying "my class variable i = my local variable i".

--------------------------------------------------
Free Database Connection Pooling Software
 
One handy thing to do is when you see the keyword "this", mentally say: "this instance of my class". It'll help you keep things straight in your head.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top