Write a Program about THIS keyword in Java

I have discussed earlier about the this keyword with you. Now we will do a programming to how to use this keyword practically. It will surely clear your doubts and make your concept about this keyword more strong.

There will be a series of this program around 4 programs. You will need to read all the 4 this program to understand the concept.

Program 1: – (In this program, I didn’t use this keyword)

class th1
{
int a,b;
th1(int a, int b)
{
a=a;
b=b;
}
public void show()
{
System.out.println(a);
System.out.println(b);
}
public static void main(String[] ar)
{
new th1(10, 20).show();
}
}

Create a particular folder on the drive like myjava and save this file as “th1.java”

Now open command prompt to compile and run the program. You can also click run and type cmd. It will open a command prompt.

If you are going to compile the java program for the first time then you will need to set the path of the java for whenever you open the command prompt. Its very easy process. When you installed the jdk software of any version probably in c drive then it gets a path like it is installed under program files in the c drive. Click the program files and click the java and then click the jdk software and then click the bin. Now in the address bar, check out the path and copy it and paste in the command prompt like I did

c:\java>set path=C:\j2sdk1.4.0\bin

Also check out the screen shot

After that compile the program by writing this code

javac th1.java

If there is no error then run the program by writing the code

java th1

When you compile and run this program, you will get a output of

0

0

as shown in screen shot

Hows the result is 0,0

Here in this program, we have two variables as data members int a and int b. Another is the constructor paramertised variable int a and int b.

In the main method, we passed the value 10 and 20 (  new th1(10, 20).show();) to the respective varible of the constuctor paramter int a and int b.

Now in this statement: -

a=a;
b=b;

the value of constructor int a is replaced by the data member int a.

the value of constructor int b is replaced by the data member int b.

So when the program is run, the output is shown as the defaut value of data members.


Share this Post[?]
        

No Comments

Leave a reply