Bird
Raised Fist0
Javaprogramming~20 mins

Classes and objects in Java - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
πŸŽ–οΈ
Java Classes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of method call on object
What is the output of this Java program?
Java
public class Car {
    String brand;
    int year;

    public Car(String brand, int year) {
        this.brand = brand;
        this.year = year;
    }

    public void displayInfo() {
        System.out.println(brand + " " + year);
    }

    public static void main(String[] args) {
        Car myCar = new Car("Toyota", 2015);
        myCar.displayInfo();
    }
}
A2015 Toyota
BToyota 2015
CCar@15db9742
DCompilation error
Attempts:
2 left
πŸ’‘ Hint
Look at what the displayInfo method prints.
🧠 Conceptual
intermediate
2:00remaining
Understanding object reference assignment
What will be the output of this Java code snippet?
Java
class Box {
    int size;

    Box(int size) {
        this.size = size;
    }
}

public class Test {
    public static void main(String[] args) {
        Box b1 = new Box(5);
        Box b2 = b1;
        b2.size = 10;
        System.out.println(b1.size);
    }
}
A10
B5
CCompilation error
DRuntime error
Attempts:
2 left
πŸ’‘ Hint
Remember that b1 and b2 refer to the same object.
πŸ”§ Debug
advanced
2:00remaining
Identify the error in constructor usage
What error will this Java code produce when compiled?
Java
public class Person {
    String name;
    int age;

    public Person() {
        name = "Unknown";
        age = 0;
    }

    public Person(String name) {
        this.name = name;
    }

    public static void main(String[] args) {
        Person p = new Person("Alice", 30);
        System.out.println(p.name + " " + p.age);
    }
}
ACompilation error: no constructor Person(String, int)
BRuntime error: NullPointerException
COutput: Alice 0
DOutput: Unknown 30
Attempts:
2 left
πŸ’‘ Hint
Check the constructors defined and the one used in main.
πŸ“ Syntax
advanced
2:00remaining
Identify the syntax error in class definition
Which option correctly fixes the syntax error in this Java class?
Java
public class Animal {
    String type
    int age;

    public Animal(String type, int age) {
        this.type = type;
        this.age = age;
    }
}
ARemove the constructor
BChange int age to Integer age
CAdd a constructor return type: public void Animal(String type, int age)
DAdd a semicolon after String type: String type;
Attempts:
2 left
πŸ’‘ Hint
Look carefully at the variable declarations.
πŸš€ Application
expert
2:00remaining
Determine the number of objects created
How many objects are created when this Java program runs?
Java
public class Node {
    int value;
    Node next;

    public Node(int value) {
        this.value = value;
        this.next = null;
    }

    public static void main(String[] args) {
        Node first = new Node(1);
        Node second = new Node(2);
        first.next = second;
        Node third = second;
    }
}
A1
B3
C2
D0
Attempts:
2 left
πŸ’‘ Hint
Count how many times 'new' is used.

Practice

(1/5)
1. What is the main purpose of a class in Java?
easy
A. To serve as a blueprint for creating objects
B. To execute the program's main method
C. To store data permanently on disk
D. To perform input and output operations

Solution

  1. Step 1: Understand the role of a class

    A class defines the structure and behavior that objects created from it will have.
  2. Step 2: Identify the correct purpose

    Classes are not for running programs or storing data on disk; they are blueprints for objects.
  3. Final Answer:

    To serve as a blueprint for creating objects -> Option A
  4. Quick Check:

    Class = blueprint for objects [OK]
Hint: Classes define objects' structure and behavior [OK]
Common Mistakes:
  • Confusing classes with methods
  • Thinking classes store data permanently
  • Believing classes execute the program
2. Which of the following is the correct way to create an object of class Car in Java?
easy
A. Car myCar = new Car;
B. Car myCar = Car();
C. Car myCar = new Car();
D. new Car myCar = Car();

Solution

  1. Step 1: Recall object creation syntax

    In Java, objects are created using the new keyword followed by the class constructor with parentheses.
  2. Step 2: Check each option

    Car myCar = new Car(); uses correct syntax: Car myCar = new Car();. Others miss parentheses or have wrong order.
  3. Final Answer:

    Car myCar = new Car(); -> Option C
  4. Quick Check:

    Use new ClassName() to create objects [OK]
Hint: Use 'new ClassName()' to create objects [OK]
Common Mistakes:
  • Omitting parentheses after class name
  • Placing 'new' keyword incorrectly
  • Missing semicolon at the end
3. What will be the output of the following code?
class Dog {
  String name;
  void bark() {
    System.out.println(name + " says Woof!");
  }
}

public class Main {
  public static void main(String[] args) {
    Dog dog1 = new Dog();
    dog1.name = "Buddy";
    dog1.bark();
  }
}
medium
A. null says Woof!
B. Woof!
C. Compilation error
D. Buddy says Woof!

Solution

  1. Step 1: Understand object property assignment

    The object dog1 has its name set to "Buddy" before calling bark().
  2. Step 2: Analyze the bark method output

    The method prints the name followed by " says Woof!" so it prints "Buddy says Woof!".
  3. Final Answer:

    Buddy says Woof! -> Option D
  4. Quick Check:

    Object property used in method = Buddy says Woof! [OK]
Hint: Check object fields before method calls for output [OK]
Common Mistakes:
  • Assuming default null value prints
  • Forgetting to assign the name
  • Thinking method prints only 'Woof!'
4. Identify the error in the following code snippet:
class Person {
  String name;
  void setName(String name) {
    name = name;
  }
}

public class Main {
  public static void main(String[] args) {
    Person p = new Person();
    p.setName("Alice");
    System.out.println(p.name);
  }
}
medium
A. Missing semicolon after setName method
B. The method setName does not assign the parameter to the instance variable
C. Cannot print p.name directly
D. Class Person should be public

Solution

  1. Step 1: Analyze the setName method

    The assignment name = name; assigns the parameter to itself, not to the instance variable.
  2. Step 2: Understand instance variable shadowing

    To assign correctly, use this.name = name; to refer to the instance variable.
  3. Final Answer:

    The method setName does not assign the parameter to the instance variable -> Option B
  4. Quick Check:

    Use 'this' to assign instance variables [OK]
Hint: Use 'this.variable' to refer to instance variables [OK]
Common Mistakes:
  • Confusing parameter and instance variable names
  • Forgetting 'this' keyword
  • Assuming assignment works without 'this'
5. Given the class below, how can you create a method that returns a new Rectangle object with double the width and height of the current one?
class Rectangle {
  int width;
  int height;

  Rectangle(int w, int h) {
    width = w;
    height = h;
  }

  // Your method here
}
hard
A. Rectangle doubleSize() { return new Rectangle(width * 2, height * 2); }
B. void doubleSize() { width *= 2; height *= 2; }
C. Rectangle doubleSize() { width *= 2; height *= 2; return this; }
D. Rectangle doubleSize() { return new Rectangle(width + 2, height + 2); }

Solution

  1. Step 1: Understand the requirement

    The method should return a new Rectangle object with width and height doubled, without changing the current object.
  2. Step 2: Evaluate each option

    Rectangle doubleSize() { return new Rectangle(width * 2, height * 2); } creates and returns a new Rectangle with doubled dimensions. void doubleSize() { width *= 2; height *= 2; } changes current object and returns void. Rectangle doubleSize() { width *= 2; height *= 2; return this; } changes current object and returns it. Rectangle doubleSize() { return new Rectangle(width + 2, height + 2); } adds 2 instead of doubling.
  3. Final Answer:

    Rectangle doubleSize() { return new Rectangle(width * 2, height * 2); } -> Option A
  4. Quick Check:

    Return new object with doubled size = Rectangle doubleSize() { return new Rectangle(width * 2, height * 2); } [OK]
Hint: Return new object; don't modify current one [OK]
Common Mistakes:
  • Modifying current object instead of returning new
  • Adding instead of multiplying dimensions
  • Returning void instead of new object