0
0
Javaprogramming~20 mins

Best practices in Java - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Java Best Practices 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 code snippet?

Consider the following Java code. What will it print when run?

Java
public class Test {
    public static void main(String[] args) {
        int x = 5;
        int y = 10;
        int result = x > y ? x : y;
        System.out.println(result);
    }
}
A5
BRuntime exception
C10
DCompilation error
Attempts:
2 left
πŸ’‘ Hint

Look at the ternary operator and which value it selects.

🧠 Conceptual
intermediate
1:30remaining
Which practice improves code readability in Java?

Which of the following is considered a best practice to improve code readability in Java?

AUsing meaningful variable names like <code>totalPrice</code> instead of <code>tp</code>
BWriting all code in one long method without comments
CUsing single-letter variable names for all variables
DAvoiding indentation to save space
Attempts:
2 left
πŸ’‘ Hint

Think about what helps someone else understand your code easily.

πŸ”§ Debug
advanced
2:00remaining
What error does this Java code produce?

Examine the code below. What error will occur when compiling?

Java
public class Demo {
    public static void main(String[] args) {
        final int number;
        System.out.println(number);
    }
}
ARuntime exception: NullPointerException
BCompilation error: variable number might not have been initialized
CCompilation error: cannot assign a value to final variable number
DNo error, prints 0
Attempts:
2 left
πŸ’‘ Hint

Consider what happens if a final variable is declared but not assigned before use.

πŸ“ Syntax
advanced
1:30remaining
Which option correctly declares a Java record?

Which of the following is the correct syntax to declare a record named Person with fields String name and int age?

Apublic record Person { String name; int age; }
Bpublic class Person(String name, int age) {}
Crecord Person { String name; int age; }
Dpublic record Person(String name, int age) {}
Attempts:
2 left
πŸ’‘ Hint

Recall the syntax introduced in Java 16 for records.

πŸš€ Application
expert
2:30remaining
How many items are in the resulting Map after running this code?

What is the size of the map after executing the following Java code?

Java
import java.util.*;
public class MapTest {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("a", 1);
        map.put("b", 2);
        map.put("a", 3);
        map.put("c", 4);
        map.put("b", 5);
        System.out.println(map.size());
    }
}
A3
B5
C4
D2
Attempts:
2 left
πŸ’‘ Hint

Remember how keys behave in a Map when duplicated.