Java quiz 22: Handling inner classes

  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 
>

This code shows handeling inner classes in Java. You have to store the whole code
in one file with the name Outer.

Java quiz 22: Handling inner classes

Level: Normal

What happens if the following code is compiled and run?

Outer.java

public class Outer
{
  int x;
  int y;
  
  Outer(int x, int y)
  {
    x += 2;
    y += 3;
    System.out.print("x" + this.x);
    System.out.print(", ");
    System.out.print("y" + this.y);
    System.out.print(", ");
  }
  
  class Inner
  {
    Inner()
    {
      x += 3;
      y += 2;
      System.out.print("x" + x);
      System.out.print(", ");
      System.out.print("y" + y);
    }
  }
  
  public static void main(String[] args)
  {
    new Outer(4, 5).new Inner();
  }
}
Author: Sar Maroof

Select the correct answer.


Answer explanation

  1. The statement new Outer(4, 5) calls the two argument constructor of the Outer class.
  2. The statement x += 2; and y += 3; incremnts the value of the parameters x and y by 2 and 3 respectively.
  3. The statement System.out.print(“x” + this.x + “, ” + “y” + this.y + “, “); writes the values of the instance variables x and y to the standard output, which are respectively 0 and 0. Therefore the statement writes x0, y0 to the standard output.
  4. The statments x += 3; and y += 2; increments the values of the instance variables x and y by 3 and 2 respectively.
  5. The statement System.out.print(“x” + x + “, ” + “y” + y); writes the values of the instance variables x and y to the standard output, So, it writes x3, y2 to the standard output.

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 *