Saturday, August 20, 2022

Java ‘This’ Keyword: Tutorial With Code Examples

 

Java ‘This’ Introduction

The reference ‘this’ is generally termed as ‘this pointer’ as it points to the current object. The ‘this pointer’ is useful when there is some name for the class attributes and parameters. When such a situation arises, the ‘this pointer’ eliminates the confusion as we can access parameters using ‘this’ pointer.

this pointer

In this tutorial, we will discuss the usage of ‘this’ pointer in various situations along with examples.

When To Use ‘this’ In Java?

In Java the term ‘this’ has the following uses:

  • The reference ‘this’ is used to access the class instance variable.
  • You can even pass ‘this’ as an argument in the method call.
  • ‘this’ can also be used to implicitly invoke the current class method.
  • If you want to return the current object from the method, then use ‘this’.
  • If you want to invoke the current class constructor, ‘this’ can be used.
  • The constructor can also have ‘this’ as an argument.

Let us now look into each of these uses separately.

Access Instance Variable Using ‘this’

Instance variables of class and method parameters may have the same name. ‘this’ pointer can be used to remove the ambiguity that arises out of this.

The Java program below demonstrates how ‘this’ can be used to access instance variables.

class this_Test
{
     int val1;
     int val2;
 
    // Parameterized constructor
    this_Test(int val1, int val2)
    {
        this.val1 = val1 + val1;
        this.val2 = val2 + val2;
    }
 
   void display()
    {
          System.out.println("Value val1 = " + val1 + " Value val2 = " + val2);
    }
}
 
class Main{
 
       public static void main(String[] args)
       {
            this_Test object = new this_Test(5,10);
            object.display();
       }
}

Output:

Access instance variable using ‘this’ Output

In the above program, you can see that the instance variables and method parameters share the same names. We use ‘this’ pointer with instance variables to differentiate between the instance variables and method parameters.

‘this’ Passed As The Method Parameter

You can also pass this pointer as a method parameter. Passing this pointer as a method parameter is usually required when you are dealing with events. For Example, suppose you want to trigger some event on the current object/handle, then you need to trigger it using this pointer.

Given below is a programming exhibit wherein we have passed this pointer to the method.

class Test_method
{
    int val1;
    int val2;
 
    Test_method()
    {
        val1 = 10;
        val2 = 20;
    }
 
    void printVal(Test_method obj)
    {
             System.out.println("val1 = " + obj.val1 + "  val2 = " + obj.val2);
    }
 
    void get()
    {
           printVal(this);
    }
}
 
class Main{
    public static void main(String[] args)
    {
        Test_method object = new Test_method();
        object.get();
    }
}

Output:

‘this’ passed as the method parameter OutPut

In this program, we create an object of the class Test_method in the main function and then call get() method with this object. Inside the get () method, ‘this’ pointer is passed to the printVal () method that displays the current instance variables.

Invoke The Current Class Method With ‘this’

Just as you can pass ‘this’ pointer to the method, you can also use this pointer to invoke a method. If at all you forget to include this pointer while invoking the method of the current class, then the compiler adds it for you.

An example of invoking the class method with ‘this’ is given below.

class Test_this {
 
    void print()
    {
        // calling fuctionshow()
       this.show();
 
       System.out.println("Test_this:: print");
    }
 
    void show() {
        System.out.println("Test_this::show");
    }
}
 
class Main{   
    public static void main(String args[]) {
        Test_this t1 = new Test_this();
        t1.print();
    }
}

Output:Invoke the current class method with ‘this’ output

In this program, the class method print () calls the show() method using this pointer when it is invoked by the class object in the main function.

Return With ‘this’

If the return type of the method is the object of the current class, then you can conveniently return ‘this’ pointer. In other words, you can return the current object from a method using ‘this’ pointer.

Given below is the implementation of returning an object using ‘this’ pointer.

class Test_this
{
   int val_a;
   int val_b;
 
    //Default constructor
   Test_this()
    {
        val_a = 10;
        val_b = 20;
    }
 
   Test_this get()
    {
        return this;
    }
 
   void display()
    {
         System.out.println("val_a = " + val_a + "  val_b = " + val_b);
    }
}
 
class Main{
    public static void main(String[] args)
    {
        Test_this object = new Test_this();
        object.get().display();
    }
}

Output:

Return with this output

The above program shows the method get () that returns this which is an object of class Test_this. Using the current object returned by the get() method, the method display is in turn called.

Using ‘this’ To Invoke The Current Class Constructor

You can also use ‘this’ pointer to invoke the constructor of the current cla.ss. The basic idea is to reuse the constructor. Again if you have more than one constructor in your class, then you can call these constructors from one another resulting in constructor chaining.

Consider the following Java program.

class This_construct
{
     int val1;
     int val2;
 
    //Default constructor
    This_construct()
    {  
        this(10, 20);
        System.out.println("Default constructor \n");
    }
 
    //Parameterized constructor
   This_construct(int val1, int val2)
    {
        this.val1 = val1;
        this.val2 = val2;
        System.out.println("Parameterized constructor");
    }
}
 
class Main{
    public static void main(String[] args)
    {
         This_construct object = new This_construct();
    }
}

Output:

Using this to invoke the current class constructor Output

In the above program, we have two constructors in the class. We call the other constructor using ‘this’ pointer, from the default constructor of the class.

Using ‘this’ As The Argument To Constructor

You can also pass ‘this’ pointer as an argument to a constructor. This is more helpful when you have multiple classes as shown in the following implementation.

class Static_A
{
     Static_B obj;
 
     Static_A(Static_B obj)
    {
        this.obj = obj;
 
        obj.display();
    }
 }
 
class Static_B
{
    int x = 10;
 
    Static_B()
    {
          Static_A obj = new Static_A(this);
    }
 
    void display()
    {
          System.out.println("B::x = " + x);
    }
}
 
class Main{
     public static void main(String[] args) {
        Static_B obj = new Static_B();
    }
}

Output:

Using this as the argument to constructor Output

As shown in the above implementation, we have two classes and each class constructor calls the other class’s constructor. ‘this’ pointer is used for this purpose.


Frequently Asked Questions

Q #1) What is the difference between this and this () in Java?

Answer: In Java, this refers to the current object while this () refers to the constructor with matching parameters. The keyword ‘this’ works only with objects. The call “this ()’ is used to call more than one constructor from the same class.

Q #2) Is this keyword necessary in Java?

Answer: It is necessary especially when you need to pass the current object from one method to another, or between the constructors or simply use the current object for other operations.

Q #3) What is the difference between this () and super () in Java?

Answer: Both this () and super () are keywords in Java. While this () represents the constructor of the current object with matching parameters, super () represents the constructor of the parent class.

Q #4) Can you use both this () and super () in a constructor?

Answer: Yes, you can use it. The constructor this () will point to the current constructor while super () will point to the parent class constructor. Remember that both this () and super () should be the first statement.

Monday, August 15, 2022

Java Runtime class

 Java Runtime class is used to interact with java runtime environment. Java Runtime class provides methods to execute a process, invoke GC, get total and free memory etc. There is only one instance of java.lang.Runtime class is available for one java application.

The Runtime.getRuntime() method returns the singleton instance of Runtime class.

Important methods of Java Runtime class

No.MethodDescription
1)public static Runtime getRuntime()returns the instance of Runtime class.
2)public void exit(int status)terminates the current virtual machine.
3)public void addShutdownHook(Thread hook)registers new hook thread.
4)public Process exec(String command)throws IOExceptionexecutes given command in a separate process.
5)public int availableProcessors()returns no. of available processors.
6)public long freeMemory()returns amount of free memory in JVM.
7)public long totalMemory()returns amount of total memory in JVM.

Java Runtime exec() method

  1. public class Runtime1{  
  2.  public static void main(String args[])throws Exception{  
  3.   Runtime.getRuntime().exec("notepad");//will open a new notepad  
  4.  }  
  5. }  

How to shutdown system in Java

You can use shutdown -s command to shutdown system. For windows OS, you need to provide full path of shutdown command e.g. c:\\Windows\\System32\\shutdown.

Here you can use -s switch to shutdown system, -r switch to restart system and -t switch to specify time delay.


  1. public class Runtime2{  
  2.  public static void main(String args[])throws Exception{  
  3.   Runtime.getRuntime().exec("shutdown -s -t 0");  
  4.  }  
  5. }  

How to shutdown windows system in Java

  1. public class Runtime2{  
  2.  public static void main(String args[])throws Exception{  
  3.   Runtime.getRuntime().exec("c:\\Windows\\System32\\shutdown -s -t 0");  
  4.  }  
  5. }  

How to restart system in Java

  1. public class Runtime3{  
  2.  public static void main(String args[])throws Exception{  
  3.   Runtime.getRuntime().exec("shutdown -r -t 0");  
  4.  }  
  5. }  

Java Runtime availableProcessors()

  1. public class Runtime4{  
  2.  public static void main(String args[])throws Exception{  
  3.   System.out.println(Runtime.getRuntime().availableProcessors());  
  4.  }  
  5. }  

Java Runtime freeMemory() and totalMemory() method

In the given program, after creating 10000 instance, free memory will be less than the previous free memory. But after gc() call, you will get more free memory.

  1. public class MemoryTest{  
  2.  public static void main(String args[])throws Exception{  
  3.   Runtime r=Runtime.getRuntime();  
  4.   System.out.println("Total Memory: "+r.totalMemory());  
  5.   System.out.println("Free Memory: "+r.freeMemory());  
  6.     
  7.   for(int i=0;i<10000;i++){  
  8.    new MemoryTest();  
  9.   }  
  10.   System.out.println("After creating 10000 instance, Free Memory: "+r.freeMemory());  
  11.   System.gc();  
  12.   System.out.println("After gc(), Free Memory: "+r.freeMemory());  
  13.  }  
  14. }  
Total Memory: 100139008
Free Memory: 99474824
After creating 10000 instance, Free Memory: 99310552
After gc(), Free Memory: 100182832

techguruspeaks

  Core Java programming Introduction to Java Java Features Writing a Simple Java Program Java Keywords and Comments Variables, Identifiers ...