Topics

Java Programming Language Java History Java Features How Java Differs from C and C++ Java and Internet Java Characteristics: A Comprehensive Guide Basic Concept of OOP TCS Core Java Questions All Difference in Java Overview of Java Language Keywords in Programming Language Benefits of OOP Tokens in Java Escape sequences in Java Character Set in Java Basic Structure of Java Program Simple Program of Java- Hello World! Programming pattern Path Setting Installing and Configuring Download Java Development Kit -JDK JRE - Java Runtime Environment JDK - Java Development Kit JVM - Java Virtual Machine Compilation and Execution Process Programming Error DataTypes in java Introduction to Data type Java Data Type Conversion or Casting in Java double - Data Type in Java float - Data Type in Java long - Data Type in Java int - Data Type in Java short - Data Type in Java byte - Data Type in Java boolean - Data Type in Java Unicode System in Java char - Data Type in Java Type Casting with Objects in Java Variables in java Variable - in Java Variable initialization and Declaration - in Java Variable Types and Scope- in Java What is variable in programming? Constants in java Constants in Java Operators in java Operators in Java Arithmetic Operators Assignment Operators Relational Operators Conditional (Ternary) Operator in Java Logical Operators in Java Expression Evaluation in Java Bitwise Operators Operator precedence in Java Shift Operators instanceof operator in Java Decision Making in java Control flow in programming Decision Making in Java Introduction if statement in Java if else statement Control Flow in Programming Language if else Statement in Java Nested if Statement in Java if else if ladder in Java switch case in Java Assignment: Determine if a Number is Even or Odd Three Constructs That Govern Statement Flow Looping in java Loop Introduction in Java Language Why Do We Need Iterative Constructs in Programming? Types of loops in Java While Loop in Java Language While loop example in Java Infinite while loop in Java Do While Loop in Java Language Jump statements in Java Nested Loops in Java Language Labeled For Loop in Java Language Enhanced For Loop (For-Each Loop) in Java For each loop in Java Language For Loop in Java Language Java Loop MCQ Question Empty Loop in Java String in java Introduction in String Question 5 - Java MCQ Question 4 - Java MCQ Question 3 - Java MCQ Question 2 - Java MCQ Question 1 - Java MCQ StringBuilder in Java StringBuffer in Java Sub String in Java String comparision in Java Immutable Strings and Interned Strings in Java Question 6 - Java MCQ Question 7 - Java MCQ Array in java Array in java Array Introduction in Data Structure Need for Array Types of Array Array Declaration with Initialization Using Values - Java Read all elements of an array using Index Java Array fixed-size sequence/ same type Find the size of an array Read all elements of an array using Loops Enhanced For Loop (For-Each Loop) in Java Insert an Element in the Middle of an Array Delete an Element in the Middle of an Array 2D and Multi-Dimension Array in Java Java Array Error Finding the sum of all array elements Array with Function Sorting Bubble Sort Selection Sort Merge Sort Quick Sort Insertion Sort Bubble Sort Implementation in Java Heap sort Bucket sort Searching in Arrays (Java) Introduction to Searching in Java Linear Search Searching in Arrays (Java) Binary Search in Arrays (Java) Built-in Searching Methods in Java Class, Object and Methods in java Class and Object Concept in Java Impure Method in Java Pure Method in Java Recursion in Java finalize() method in java Covariant return types static Keyword in Java this Keyword in Java Methods Examples Java Constructor overloading Constructor in Java Methods Overloading Java Concept of Methods related to object In Java, Object is the superclass of all other classes Inheritance in java Inheritance in Java (IS-A) Aggregation in Java (HAS-A) super keyword in Java Instance initializer block static block in Java final keyword Garbage Collection in Java OOPs concept Java Wrapper Class in Java Nested Class In Java Command Line Argument Student Management System (Basic Version) Interface in java Introduction to Interface Interface and Inheritance in Java Abstract vs Interface Managing Errors and Exception Introduction to Exception Handling - Java try and catch Multiple catch block in java Nested try block in java Number Class in java Number Class Introduction Mathematical Library Methods in Java decrementExact() method cosh() method copySign() method cbrt(double a) method addExact(long x, long y) method addExact(int x, int y) method random() Method toRadians() Method toDegrees() Method atan2() Method getExponent(double d) method hypot(double x, double y) method toIntExact() method tanh() method sinh() method nextDown() method nextUp() method nextAfter() method negateExact() method multiplyExact() method incrementExact() method IEEEremainder(double f1,double f2) method atan() Method acos() Method rint() Method floor() Method ceil() Method abs() method parseInt() method toString() Method valueOf() method equals() method compareTo() method xxxValue () Method in Java round() Method in min() Method asin() Method tan() Method cos() Method sin() Method sqrt() Method pow() Method log10() method log() Method exp() Method max() Method Java Library Classes and Packages Java Library Classes and Packages Character Class in java Introduction to Character Class isLetter() isDigit() isWhitespace() isUpperCase() isLowerCase() toUpperCase() toLowerCase() toString() StringBuffer Class Methods length() Method reverse() Method insert() Method append() Method getChars() Method setCharAt() Method charAt() Method setLength() Method ensureCapacity() Method capacity() Method trim() method Project 1: Question and Solution Project Solution: Electricity Bill Calculator Project Question: Electricity Bill Calculator Project 2: Question and Solution Project Question: Hotel Booking System Project Solution: Hotel Booking System Vector in Java Vector Introduction Polymorphism in Java Polymorphism in Java Abstarct class and Methods in java Abstract class and method Packages in java Package Introduction in Java Access modifier Example 3 Access modifier Example 2 Access modifier Example 1 Encapsulation in Java Non Access Modifiers in Java Access Modifiers in Java static import in Java Sub Package in Java Access modifier Example 4 Multithreading in java Introduction to Multithreading Life Cycle of Thread Create Thread Applet Programming Applet Introduction Applet class and it's Skeleton Graphics in Applet Displaying Image in Applet Graphics Programming Java Networking Java Networking Computing and Ethics Computing and Ethics Java Programming Language MCQ Java Language Fundamental Array in Java String in Java Overriding and Overloading in Java Inheritance in Java MCQ Java Interfaces And Abstract Classes MCQ Java thread MCQ Java Exception MCQ Java Input Output MCQ Java Constructor and Methods Java Control Flow Java Data Types and Variables - MCQ Java Language Basics History of Java JVM and JRE - MCQ Java Compilation - MCQ Literals in Java - MCQ Declaration and Access Control in Java Operator in Java Java Interviews MCQs ICSE Computer Application - Class - X ICSE Computer Application - Class X - 2025 PYQ ICSE Computer Application - Class X - Selection Examination - 2024-25 - MCQ - CALCUTTA PUBLIC SCHOOL ICSE Computer Application - Class X - 2024 SPECIMEN QUESTION PAPER ICSE Computer Application - Class X - MCQ - CALCUTTA PUBLIC SCHOOL ICSE Computer Application - Class X - 2024 PYQ ICSE Computer Application - Class X - 2023 PYQ ICSE Computer Application - Class X - 2022 PYQ ICSE Computer Application - Class X - 2021 PYQ ICSE Computer Application - Class X - 2020 PYQ ICSE Computer Application - Class X - 2019 PYQ ICSE Computer Application - Class X - 2018 PYQ ICSE Computer Application - Class X - 2017 PYQ ICSE Computer Application - Class X - 2016 PYQ ICSE Computer Application - Class X - 2015 PYQ ICSE Computer Application - Class X - 2014 PYQ ICSE Computer Application - Class X - 2013 PYQ ICSE Computer Application - Class X - 2012 PYQ CSE Computer Application - Class X - 2011 PYQ ICSE Computer Application - Class X - 2010 PYQ ICSE Computer Application - Class X - 2025 SPECIMEN QUESTION PAPER Example 1: ATM Simulation Example 1: ATM Simulation Project 3: Question and Solution Project Question: Creating a Hollow Square with Diagonal Lines Project Solution: Creating a Hollow Square with Diagonal Lines Project 4: Question and Solution Project Assignment: Creating an X Pattern Project Solution: Generating an X Pattern in Java Project 5: Question and Solution Project Question: Hollow Square Pattern Project Solution: Hollow Square Pattern Project 6: Question and Solution Project Assignment: How to Implement Binary Search Project Solution: How to Implement Binary Search Project 7: Question and Solution Project Assignment: Determine the Best Performing Section in Final Exams Project Solution: Determine the Best Performing Section in Final Exams Project Bonus Task & Solution: Determine the Best Performing Section in Final Exams Project 8: Question & Answer Project Question: Number of boxes into cartons of capacities Project Answer: Number of boxes into cartons of capacities Project 9: Question & Answer Project Question: Matrix: input, rotate 270° anticlockwise, sum odds, error if invalid. Project Answer: Matrix: input, rotate 270° anticlockwise, sum odds, error if invalid. Project 10: Question & Answer Project Question: Check if a sentence has consecutive word lengths and ends with . or ?. Project Answer: Check if a sentence has consecutive word lengths and ends with . or ?.
Table of Contents

    Java 'this' Keyword: Usage and Examples

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

    Usage of java this keyword

    Here is given the 6 usages of java this keyword.

    1. this can be used to refer current class instance variable.
    2. this can be used to invoke current class method (implicitly)
    3. this() can be used to invoke the current class constructor.
    4. this can be passed as an argument in the method call.
    5. this can be passed as an argument in the constructor call.
    6. this can be used to return the current class instance from the method.

    1. this() keyword refer current class instance variable

    Understanding the problem without this keyword

    Let's understand the problem if we don't use this keyword by the example given below:

    class Employee{
    	int id;
    	String name;
    	float salary;
    
    	Employee(int id,String name,float salary){
    	id=id;
    	name=name;
    	salary=salary;
    	}
    
    void display(){
    	System.out.println(id+" "+name+" "+salary);
    	}
    }
    
    class ThisKeyword{
    	public static void main(String args[]){
    	Employee e1=new Employee(12121,"Dhinchak Pooja",50000f);
    	Employee e2=new Employee(112,"Hero Alom",60000f);
    	e1.display();
    	e2.display();
    	}
    }
    

    Output:

    0 null 0.0
    0 null 0.0
    Press any key to continue . . .
    

    In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.

    Solution of the above problem by this keyword

    class Employee{
    	int id;
    	String name;
    	float salary;
    
    	Employee(int id,String name,float salary){
    	this.id=id;
    	this.name=name;
    	this.salary=salary;
    	}
    
    void display(){
    	System.out.println(id+" "+name+" "+salary);
    	}
    }
    
    class ThisKeyword{
    	public static void main(String args[]){
    	Employee e1=new Employee(12121,"Dhinchak Pooja",50000f);
    	Employee e2=new Employee(112,"Hero Alom",60000f);
    	e1.display();
    	e2.display();
    	}
    }
    

    Output:

    12121 Dhinchak Pooja 50000.0
    112 Hero Alom 60000.0
    Press any key to continue . . .
    

    Program where this keyword is not required

    If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program:

    class Employee{
    	int id;
    	String name;
    	float salary;
    
    	Employee(int i,String j,float k){
    	 id=i;
    	 name=j;
    	 salary=k;
    	}
    
    void display(){
    	System.out.println(id+" "+name+" "+salary);
    	}
    }
    
    class ThisKeyword{
    	public static void main(String args[]){
    	Employee e1=new Employee(12121,"Dhinchak Pooja",50000f);
    	Employee e2=new Employee(112,"Hero Alom",60000f);
    	e1.display();
    	e2.display();
    	}
    }
    

    Output:

    12121 Dhinchak Pooja 50000.0
    112 Hero Alom 60000.0
    Press any key to continue . . .
    

    2. this can be used to invoke current class method

    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

    class TestClass{
    	void method1(){
    		System.out.println("This is method1");
    		}
    
    	void method2(){
    	System.out.println("This is method2");
    	//method1();//same as this.method1()
    	this.method1();
    	}
    }
    
    class ThisKeyword{
    	public static void main(String args[]){
    	TestClass a=new TestClass();
    	a.method2();
    	}
    }
    

    Output:

    This is method2
    This is method1
    Press any key to continue . . .
    

    3. this() can be used to invoke the current class constructor

    The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining.

    Calling default constructor from parameterized constructor:

    class Message{
     Message(){
    	 System.out.println("hello a");
    	 }
    
     Message(int p){
      this();
      System.out.println(""p);
     }
    }
    
    class ThisKeyword{
    	public static void main(String args[]){
    	Message a=new Message(12);
    	}
    }
    

    Output:

    hello a
    12
    Press any key to continue . . .
    

    Calling parameterized constructor from default constructor:

    class Message{
    	Message(){
    		this(5);
    		System.out.println("Not- parameterized Hello Bro");
    	}
    
    Message(int p){
     System.out.println("parameterized constructor "+p);
     }
    }
    
    class ThisKeyword{
    	public static void main(String args[]){
    	Message a=new Message();
    	}
    }
    

    Output:

    parameterized constructor 5
    Not- parameterized Hello Bro
    Press any key to continue . . .
    

    4. this can be passed as an argument in the method call.

    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 ThisKeyword{
    
      void method1(ThisKeyword obj){
      System.out.println("method is invoked");
      }
    
      void method2(){
      method1(this);
      }
    
      public static void main(String args[]){
      ThisKeyword s1 = new ThisKeyword();
      s1.method2();
      }
    }
    

    Output:

    method is invoked
    Press any key to continue . . .
    

    Another Example:

    class ThisKeyword2{
    
      int a = 12;
      void method1(ThisKeyword2 obj){
      	System.out.println("method is invoked");
      	System.out.println(obj.a);
      }
    
      void method2(){
      	method1(this);
      }
    
      public static void main(String args[]){
     	 ThisKeyword2 s1 = new ThisKeyword2();
         s1.method2();
      }
    }
    

    Output:

    method is invoked
    12
    Press any key to continue . . .
    

    5. this can be passed as an 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 classA{
      ThisClass obj;
      classA(ThisClass obj){
        this.obj=obj;
      }
      void display(){
        System.out.println(obj.data);//using data member of ThisClass class
      }
    }
    
    class ThisClass{
      int data=12;
      ThisClass(){
       classA b=new classA(this);
       b.display();
      }
      public static void main(String args[]){
       ThisClass a=new ThisClass();
      }
    }
    
    

    Output:

    12
    Press any key to continue . . .
    

    6. this can be used to return the current class instance from the method.

    We can return 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 classA{
    	classA getA(){
    	return this;
    	}
    
    void msg(){
    	System.out.println("java at atnyla");
    	}
    }
    
    class ThisKeyword{
    	public static void main(String args[]){
    	new classA().getA().msg();
    	}
    } 
    

    Output:

    java at atnyla
    Press any key to continue . . .
    

    Detail view

    When this( ) is executed, the overloaded constructor that matches the parameter list specified by arg-list is executed first. Then, if there are any statements inside the original constructor, they are executed. The call to this( ) must be the first statement within the constructor.
    To understand how this( ) can be used, let’s work through a short example. First, consider the following class that does not use this( ):

    class Smile{
    	int a;
    	int b;
    
    	// initialize a and b individually
    	Smile(int i, int j) {
    	a = i;
    	b = j;
    	}
    
    	// initialize a and b to the same value
    	Smile(int i) {
    	a = i;
    	b = i;
    	}
    
    	// give a and b default values of 0
    	Smile( ) {
    	a = 0;
    	b = 0;
    	}
    
    	void display(){
    		System.out.println("a = "+a+" and b = "+b);
    		}
    }
    class ThisKeyword{
    	public static void main(String args[]){
    	Smile sm = new Smile();
    	sm.display();
    	}
    } 
    

    Output:

    a = 0 and b = 0
    Press any key to continue . . .
    

    This class contains three constructors, each of which initializes the values of a and b. The first is passed individual values for a and b. The second is passed just one value, which is assigned to both a and b. The third gives a and b default values of zero.

    By using this( ), it is possible to rewrite MyClass as shown here:
    class Smile {
    	int a;
    	int b;
    
    	// initialize a and b individually
    	Smile(int i, int j) {
    		a = i;
    		b = j;
    	}
    
    	// initialize a and b to the same value
    	Smile(int i) {
    		this(i, i); // invokes Smilet(i, i)
    	}
    
    	// give a and b default values of 0
    	Smile() {
    		this(0); // invokes Smile(0)
    	}
    
    	void display(){
    		System.out.println("a = "+a+" and b = "+b);
    		}
    }
    
    class ThisKeyword{
    	public static void main(String args[]){
    	Smile sm = new Smile();
    	sm.display();
    	}
    } 
    

    Output:

    a = 0 and b = 0
    Press any key to continue . . .
    

    In this version of Smile, the only constructor that actually assigns values to the a and b fields is Smile(int, int). The other two constructors simply invoke that constructor (either directly or indirectly) through this( ). For example, consider what happens when this statement executes:

    class ThisKeyword{
    	public static void main(String args[]){
    	Smile sm = new Smile();
    	sm.display();
    	}
    }
    
    Smile sm = new Smile();
    a = 0 and b = 0
    Press any key to continue . . .
    
    In this case, this(0) is called. This causes Smile(0) to be invoked because it is the constructor with the matching parameter list. Of course, Smile(0) then calls Smile(0,0) as just described

    Now,

    class ThisKeyword{
    	public static void main(String args[]){
    	Smile sm = new Smile(10);
    	sm.display();
    	}
    }
    
    Smile sm = new Smile(10);
    a = 10 and b = 10
    Press any key to continue . . .
    
    The call to Smile(10) causes this(10, 10) to be executed, which translates into a call to this(10, 10), because this is the version of the Smile constructor whose parameter list matches the arguments passed via this( ). Now, consider the following statement, which uses the default constructor:


    Related Assignments


    Sponsored

    Learn Programming
    HTML, CSS, JavaScript beginner course.
    Practice MCQs
    10,000+ GK questions for exams.
    Dynamics 365 Course