Java quiz 01: Passing parameters to constructors

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Quizzes    Green = Easy,  Blue = Normal,  Red = Hard
Select    01   02   03   04   05   06   07   08   09   10   11   12   13   14   15 
 16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   By title 

I would emphasize that understanding constructors helps you by initializing instance variables. In the following code, I try to make that concept clear. I use a trick to make it difficult to guess the result if you don’t understand the constructor block.

Java quiz 1: Passing parameters to constructors

Level: Normal

What is the output of the following program?

public class Student
  String name = "Emily";
  int age = 20;
  Student(String name, int age)
  { = name;
    this.age = 22;
  public static void main(String[] args)
    Student st = new Student("Oliver", 21);
    System.out.print(", " + st.age);
Author: Sar Maroof

Select the correct answer.

Answer explanation

  1. By creating the object st using the constructor of the Student class, we need to pass two parameters to the constructor.
  2. Inside the constructor we assign the name parameter to the class variable name by using the statement = name;. Therefore the name is Oliver.
  3. In the constructor the age parameter is not assigned to the variable age. No matter which age you pass to the constructor, the value 22 is assigned to the age. See the statement this.age = 22;.

The right answer is a. Oliver, 22

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