Java quiz 38: Using the keyword “this”

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Quizzes   Green = Easy,  Blue = Normal,  Red = Hard
Select    31   32   33   34   35   36   37   38   39   40   By title 

This quiz shows how you can initialize instance variables using constructors. It clearifies
also the usage of the keyword “this” to call a constructor from another one.

Java quiz 38: Using the keyword “this”

Level: Normal

What is the output of the following code?

public class Student
  String name;
  char gender = 'm'; // m male, f female
    this("Hannah", 'f');
  Student(String name, char gender)
    this.gender = 'm';
  public static void main(String[] args)
    Student st = new Student();
    Student st2 = new Student("Emily", 'f');
    st2 = st;
    System.out.print( + ", " +
Author: Sar Maroof

Select the correct answer.

a. This program writes “Hannah, m” to the standard output.
b. This program writes “Emily, f” to the standard output.
c. This program writes “Hannah, f” to the standard output.
d. This program writes “null, m” to the standard output.
e. This program writes “null, f” to the standard output.
f. Illegal at compile time.
g. Illegal at run time.

Answer explanation

  1. The statement Student st = new Student(); creates the object st.
  2. By calling the no-argument constructor the statement “this(“Hannah”, ‘f’);” is executed, which calls the two-argument constructor of the class Student.
  3. By calling the two-argument constructor the statement “this.gender = ‘m’;” is executed which assings the value ‘m’ to the gender.
  4. In the two argument constructor the value of the argument name is not assigned to the instance variable name. Therfore the initial value of the instance variable name remains, which is null.
  5. The statement st2 = st; means that the st2 refers to st.

The correct answer is: d.


The second edition of Learn Java and Master Writing Code is easy to understand, organized to learn Java voor beginners and it guides readers to master Java code by solving more than 100 exercises and assignments. This book explains each chapter properly before starting with the exercises and the assignments. Available on Amazon. See inside the book here!

Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *