Beginner quizzes – Java classes and objects

The following Java exercise(s) are designed for beginner level programmers. If the level is too hard, then I recommend reading my article about this topic, which offers a theoretical explanation including more exercises. Read More: Java Classes And Objects.

classes-and-objects-green

 

Quiz 1: Creating worker objects

What happens when the following program is compiled and run?

class Worker
{
  String name;
  int age;
  double wage;
  
  Worker(String name, int age, double wage)
  {
    this.name = name;
    this.age = age;
  }
  public static void main(String[] args)
  {
    Worker mc = new Worker("Peter", 25, 235.0);
    Worker mc2 = new Worker("Alan", 64, 434.0);
    Worker mc3 = new Worker("Emily", 36, 320.0);
    System.out.print(
            mc3.age + ", " +
            mc2.wage + ", " +
            mc2.name);
  }
}

Select the correct answer.


Quiz 2: Object instantiation

What happens when the following program is compiled and run?

public class MyClass {

    int m = 2;
    int n = 3;
    String s = "b";

    MyClass(int m, int n, String s) {
        this.n = n;
        this.s = s;
        System.out.print("-"+m+"-"+n+"-"+s);
    }
    void method(int m, int n, String s) {
        this.m = m;
        this.n = n;
        this.s = s;
    }
    public static void main(String[] args) {
        MyClass mc = new MyClass(4, 6, "h");
        mc.method(7, 9, "w");
    }
}

Select the correct answer.



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!

5 Comments

Add a Comment
  1. Darlington Chigumbu

    true wage is missing inside the constructor

    1. That is also the reason that wage remains as 0.0.

  2. mc2’s wage is definitely not 0.0… isn’t d correct for the first question?

    1. The correct answer is actually b. There is a trick here! The statement this.wage = wage; is missing inside the constructor. That means the value of the parameter is never assigned to the instance variable wage. unlike the values of the variables name and age.

    2. d is not the correct answer, because the wage is missing inside the constructor. To change the wage the constructor should be as following.

      Worker(String name, int age, double wage)
      {
      this.name = name;
      this.age = age;
      this.wage = wage;
      }

Leave a Reply

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