Programming & Scripting Tutorials

Java: The "this" Keyword



The most common reason for using the this keyword is because a local variable name is shadowed by a method or constructor parameter.
For example this by itself outputs 21:

class ClassOne{
    int fish = 1;
  void PrintFish(int fish){
      System.out.println(fish);
  }

};

public class Main {
    public static void main(String[] args){

        ClassOne FishObject = new ClassOne();
        FishObject.PrintFish(21);

    }
}

It does this as the constructor/function variable is just its default, however we might have wanted to output the other variable 'fish'.
To do this we use the "this" keyword, for example this would output 21 and then 1:

class ClassOne{
    int fish = 1;
  void PrintFish(int fish){
      System.out.println(fish);
      System.out.println(this.fish);
  }
};

public class Main {

    public static void main(String[] args) {

        ClassOne FishObject = new ClassOne();
        FishObject.PrintFish(21);

    }
}


You can also set variable using the this keyword. For example this would output 123:


class ClassOne{
    int fish;
  void PrintFish(int fish){
      this.fish = 123;
      System.out.println(this.fish);

  }

};

public class Main {
    public static void main(String[] args) {

        ClassOne FishObject = new ClassOne();
        FishObject.PrintFish(21);
    }
}



This Java tutorial was written by


Back to Java

Advertisement: