Challenge - 5 Problems
Java Classes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2: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(); } }
Attempts:
2 left
π‘ Hint
Look at what the displayInfo method prints.
β Incorrect
The displayInfo method prints the brand followed by the year separated by a space. So it prints "Toyota 2015".
π§ Conceptual
intermediate2: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); } }
Attempts:
2 left
π‘ Hint
Remember that b1 and b2 refer to the same object.
β Incorrect
Both b1 and b2 point to the same Box object. Changing size via b2 changes the same object that b1 points to, so b1.size is 10.
π§ Debug
advanced2: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); } }
Attempts:
2 left
π‘ Hint
Check the constructors defined and the one used in main.
β Incorrect
The class defines constructors with zero and one parameter, but main tries to call a constructor with two parameters which does not exist, causing a compilation error.
π Syntax
advanced2: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; } }
Attempts:
2 left
π‘ Hint
Look carefully at the variable declarations.
β Incorrect
The field declaration 'String type' is missing a semicolon, causing a syntax error. Adding the semicolon fixes it.
π Application
expert2: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; } }
Attempts:
2 left
π‘ Hint
Count how many times 'new' is used.
β Incorrect
Only two objects are created with 'new Node(1)' and 'new Node(2)'. The variable 'third' just references the existing second object.