0
0
Javaprogramming~10 mins

This keyword usage in Java - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to print the current object's name using this keyword.

Java
public class Person {
    String name;
    public Person(String name) {
        this.name = name;
    }
    public void printName() {
        System.out.println([1].name);
    }
}
Drag options to blanks, or click blank then click option'
Aobj
Bsuper
Cself
Dthis
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'super' instead of 'this' to access current object's fields.
Using undefined variable names like 'self' or 'obj'.
2fill in blank
medium

Complete the constructor to call another constructor in the same class using this keyword.

Java
public class Box {
    int width, height;
    public Box() {
        this(10, 20);
    }
    public Box(int width, int height) {
        this.width = width;
        this.height = height;
    }
    public void printSize() {
        System.out.println("Width: " + width + ", Height: " + height);
    }
}
Drag options to blanks, or click blank then click option'
Aself
Bsuper
Cthis
Dparent
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'super' to call constructors in the same class.
Calling constructor after other statements.
3fill in blank
hard

Fix the error by completing the code to correctly refer to the instance variable value when parameter name is the same.

Java
public class Counter {
    int value;
    public void setValue(int value) {
        [1].value = value;
    }
}
Drag options to blanks, or click blank then click option'
Athis
Bsuper
CCounter
Dself
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using parameter name directly causing assignment to itself.
Using 'super' or class name incorrectly.
4fill in blank
hard

Fill both blanks to complete the method that returns the current object's string representation using this keyword.

Java
public class Point {
    int x, y;
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public String toString() {
        return "Point(" + [1].x + ", " + [2].y + ")";
    }
}
Drag options to blanks, or click blank then click option'
Athis
Bsuper
Cself
Dobj
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'super' which refers to parent class.
Using undefined variables like 'self' or 'obj'.
5fill in blank
hard

Fill all three blanks to complete the constructor chaining and instance variable assignment using this keyword.

Java
public class Rectangle {
    int width, height;
    public Rectangle() {
        this([1], [2]);
    }
    public Rectangle(int width, int height) {
        [3].width = width;
        this.height = height;
    }
}
Drag options to blanks, or click blank then click option'
A10
B20
Cthis
Dsuper
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'super' instead of 'this' for constructor chaining.
Assigning instance variables without 'this' when shadowed.