Bird
Raised Fist0
Javaprogramming~20 mins

Class definition 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 Class Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Java class instantiation?
Consider the following Java class and main method. What will be printed when the program runs?
Java
public class Car {
    String brand;
    int year;

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

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

    public static void main(String[] args) {
        Car myCar = new Car("Toyota", 2020);
        myCar.printInfo();
    }
}
AToyota 2020
BCar@15db9742
Cnull 0
DCompilation error
Attempts:
2 left
πŸ’‘ Hint
Look at the constructor and the printInfo method to see what values are printed.
❓ Predict Output
intermediate
2:00remaining
What happens if you try to access a private field directly?
Given this Java class, what will happen if you try to compile and run the main method?
Java
public class Person {
    private String name;

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

    public static void main(String[] args) {
        Person p = new Person("Alice");
        System.out.println(p.name);
    }
}
ARuntime NullPointerException
BPrints: null
CCompilation error: name has private access in Person
DPrints: Alice
Attempts:
2 left
πŸ’‘ Hint
Check the access modifier of the field and where it is accessed.
❓ Predict Output
advanced
2:00remaining
What is the output of this Java class with static and instance variables?
Analyze the following Java code and determine what it prints when run.
Java
public class Counter {
    static int count = 0;
    int id;

    public Counter() {
        count++;
        id = count;
    }

    public void printId() {
        System.out.println("Counter id: " + id);
    }

    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();
        c1.printId();
        c2.printId();
        System.out.println("Total count: " + Counter.count);
    }
}
A
Counter id: 0
Counter id: 0
Total count: 0
B
Counter id: 2
Counter id: 2
Total count: 2
C
Counter id: 1
Counter id: 2
Total count: 2
DCompilation error
Attempts:
2 left
πŸ’‘ Hint
Static variables are shared among all instances, instance variables are unique per object.
❓ Predict Output
advanced
2:00remaining
What error does this Java class produce?
Look at this Java class code. What error will occur when compiling?
Java
public class Animal {
    String type;

    public Animal() {
        this.type = type;
    }
}
ARuntime NullPointerException
BNo error, compiles successfully
CCompilation error: variable type might not have been initialized
DCompilation error: cannot assign a variable to itself
Attempts:
2 left
πŸ’‘ Hint
Check what happens when you assign a field to itself in the constructor.
🧠 Conceptual
expert
2:00remaining
How many objects are created in this Java code?
Consider the following Java code snippet. How many objects are created when main runs?
Java
public class Box {
    int size;

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

    public static void main(String[] args) {
        Box b1 = new Box(5);
        Box b2 = b1;
        Box b3 = new Box(10);
    }
}
A2
B3
C1
D0
Attempts:
2 left
πŸ’‘ Hint
Remember that assigning one object reference to another does not create a new object.

Practice

(1/5)
1. What is a class in Java?
class Car { }
easy
A. A blueprint to create objects with data and actions
B. A type of variable that stores numbers
C. A method that runs automatically
D. A special kind of loop

Solution

  1. Step 1: Understand the role of a class

    A class defines a template or blueprint for creating objects that hold data and actions.
  2. Step 2: Match the definition to options

    A blueprint to create objects with data and actions correctly describes a class as a blueprint for objects.
  3. Final Answer:

    A blueprint to create objects with data and actions -> Option A
  4. Quick Check:

    Class = blueprint for objects [OK]
Hint: Remember: class = blueprint for objects [OK]
Common Mistakes:
  • Confusing class with variable
  • Thinking class is a method
  • Mixing class with loops
2. Which of the following is the correct way to define a class named Person in Java?
easy
A. Person class { }
B. class = Person { }
C. class Person { }
D. define class Person { }

Solution

  1. Step 1: Recall Java class syntax

    In Java, a class is defined using the keyword class followed by the class name and braces.
  2. Step 2: Check each option

    class Person { } matches the correct syntax: class Person { }. Others have incorrect order or keywords.
  3. Final Answer:

    class Person { } -> Option C
  4. Quick Check:

    Correct class syntax = class Name { } [OK]
Hint: Use 'class ClassName { }' to define a class [OK]
Common Mistakes:
  • Swapping 'class' and class name
  • Using '=' sign in class definition
  • Using wrong keywords like 'define'
3. What will be the output of this Java code?
class Dog {
  String name = "Buddy";
}

public class Main {
  public static void main(String[] args) {
    Dog d = new Dog();
    System.out.println(d.name);
  }
}
medium
A. Buddy
B. null
C. Dog
D. Compilation error

Solution

  1. Step 1: Understand object creation and field access

    The code creates a Dog object and accesses its field 'name' which is set to "Buddy".
  2. Step 2: Predict the printed output

    Printing d.name outputs the string "Buddy" stored in the object.
  3. Final Answer:

    Buddy -> Option A
  4. Quick Check:

    Object field value = Buddy [OK]
Hint: Access object fields with dot notation: object.field [OK]
Common Mistakes:
  • Expecting class name instead of field value
  • Thinking uninitialized fields print 'null'
  • Confusing syntax causing compile errors
4. Identify the error in this class definition:
class Animal {
  String type;
  void Animal() {
    type = "Mammal";
  }
}
medium
A. Class name should be lowercase
B. Constructor has void return type
C. Missing semicolon after type declaration
D. Field 'type' must be static

Solution

  1. Step 1: Check constructor syntax

    Constructors in Java must not have a return type, not even void.
  2. Step 2: Identify the error

    The method void Animal() is treated as a regular method, not a constructor, causing no constructor defined.
  3. Final Answer:

    Constructor has void return type -> Option B
  4. Quick Check:

    Constructor = no return type [OK]
Hint: Constructors never have a return type, not even void [OK]
Common Mistakes:
  • Adding void to constructor
  • Thinking semicolon needed after field
  • Believing class names must be lowercase
  • Assuming fields must be static
5. You want to create a class Book with a field title and a method printTitle() that prints the title. Which code correctly implements this?
hard
A. class Book { String title; void printTitle() { System.out.println("title"); } }
B. class Book { String title; void printTitle() { print(title); } }
C. class Book { String title; void printTitle() { System.out.print("title"); } }
D. class Book { String title; void printTitle() { System.out.println(title); } }

Solution

  1. Step 1: Check method to print field value

    Method should use System.out.println with the field variable title to print its value.
  2. Step 2: Evaluate each option

    Options printing the literal "title" (with or without newline) are incorrect. Calling undefined print(title) causes an error. Only System.out.println(title) correctly prints the field value.
  3. Final Answer:

    class Book { String title; void printTitle() { System.out.println(title); } } -> Option D
  4. Quick Check:

    Print field with System.out.println(field) [OK]
Hint: Use System.out.println(field) to print variable content [OK]
Common Mistakes:
  • Using print() instead of println()
  • Printing string literal instead of variable
  • Calling undefined print() method