0
0
Javaprogramming~10 mins

Best practices in Java - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a constant for the maximum number of users.

Java
public class Config {
    public static final int MAX_USERS = [1];
}
Drag options to blanks, or click blank then click option'
Afinal
B"100"
CmaxUsers
D100
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using quotes around numbers which makes them strings.
Trying to use variable names instead of values.
2fill in blank
medium

Complete the method to override the toString method properly.

Java
public class Person {
    private String name;
    @Override
    public String toString() {
        return [1];
    }
}
Drag options to blanks, or click blank then click option'
A"Person: " + name
Bname
Cname.toString()
Dsuper.toString()
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Returning just the variable without context.
Calling toString() on a String variable unnecessarily.
3fill in blank
hard

Fix the error in the method to properly close the resource using try-with-resources.

Java
public void readFile(String path) {
    try (BufferedReader reader = new BufferedReader(new FileReader([1]))) {
        System.out.println(reader.readLine());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Drag options to blanks, or click blank then click option'
AfilePath
B"path"
Cpath
Dreader
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using a string literal instead of the variable.
Using an undefined variable name.
4fill in blank
hard

Fill both blanks to create a for-each loop that prints each element in the list.

Java
List<String> items = List.of("apple", "banana", "cherry");
for ([1] : [2]) {
    System.out.println(item);
}
Drag options to blanks, or click blank then click option'
AString item
Bitems
Cint i
Ditem
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using an index variable instead of the element variable.
Using the wrong collection variable name.
5fill in blank
hard

Fill all three blanks to create a map comprehension that filters and transforms entries.

Java
Map<String, Integer> result = data.entrySet().stream()
    .filter(e -> e.getValue() [1] [2])
    .collect(Collectors.toMap(
        e -> e.getKey().toUpperCase(),
        e -> e.getValue() [3] 2
    ));
Drag options to blanks, or click blank then click option'
A>
B10
C*
D+
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using the wrong comparison operator.
Using addition instead of multiplication for transformation.