CodeGym students' best friends are programming tasks, Java, and the task validator. Still, there comes a time when every padawan developer must begin to walk off the beaten path, invent his own mini-projects, and prepare himself for interviews. One would think that the interview would have the exact same practical Java tasks that are found in this course. And so it is in most cases, but some companies like to ask trick questions or something unfamiliar. To avoid getting rattled during a stressful interview, it's helpful to try solving similar Java tasks on your own at home.
In this article, we'll explore 5 such tricky tasks. We recommend that you first read the conditions and try solving them yourself. And one more thing: don't forget to do Java tasks in this course every day!

Task 1: Create an infinite loop from scratch

A block of code has been provided. Add to it to make the loop infinite.
class ToInfinity {
    public static void main(String[] args) {

// Insert code here

        for (int i = start; i <= start + 1; i++) {
             /* This should be an infinite loop, but don't change anything here */
        }
    }
}
"That's not hard," you say. You've more than likely found yourself in this scenario repeatedly: while completing a Java task, you created an infinite loop and had to think about how to get rid of it. Well, this is the other way around. Here's the tricky part: you can't change the loop itself or its exit conditions. There are only two iterations. But, they are enough to create an infinite loop. It looks like it should only execute for two iterations, but you can make it infinite using overflow. Have you already guessed how?

Solution

Due to overflow, Integer.MAX_VALUE is the maximum value that an int can store in Java. If you reach Integer.MAX_VALUE and increment this value, you roll back to Integer.MIN_VALUE, or rather, to the lowest possible Integer value. Thus, to complete this Java task, we simply need to assign 1 less than the maximum int value to the start variable. Java code for this task:
class ToInfinity {
    public static void main(String[] args) {
        int start = Integer.MAX_VALUE - 1;
        for (int i = start; i <= start + 1; i++) {
            // Infinite loop
            System.out.println(i); // Be sure we are in an infinite loop
        }
    }
}
What happens? We begin with start=2147483645 (Integer.MAX_VALUE-1). In the next iteration, the value becomes 2147483645, then 2147483646, then -2147483648, -2147483647... and so on.

Task 2: Create an executable comment

Well, here we are! From the very first lessons, we've heard that comments aren't executed. That's why they're called comments. We think that the solution to this task won't always be obvious to Java programmers, even experienced ones. However, there is one tricky (but "legal") way to make the JVM execute a comment. Can you sense where we're headed? Try to guess!

Solution

Java code for this task:
public class ExecutableComment {
    public static void main(String[] args) {
        // The comment below will be executed!
        // \u000d System.out.println("executable comment");
    }
}
If we enter this Java code into an IDE, here's what we'll get:
executable comment
This is because the Java compiler interprets the Unicode character \u000d as a new line, and reads our code like this: Java code for this task, as it is interpreted by the compiler:
public class ExecutableComment {
    public static void main(String[] args) {
        // The comment below will be executed!
        // \u000d
        System.out.println("comment executed");
    }
}

Task 3: Create a named loop

Here's another member of the series entitled "Practical Java Programming Problems for Spherical Cows". In the sense that it's unclear why this is even necessary: it's not likely that the loop will be offended by the fact that it hasn't been given a name. Anyway, it's important for another reason: the language lets you name a loop.

Solution

Note: these "names" are known to some people as "labels", and they are not recommended to use in practice. Java code for demonstrating a named loop
public class NamedLoop {
    public static void main(String[] args) {
        loop1:
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                if (i == 3)
                    break loop1;
                System.out.println("i = " + i + " j = " + j);
            }
        }
    }
}
Here's what will be output if you run the program:
i = 0 j = 0
i = 0 j = 1
i = 0 j = 2
i = 0 j = 3
i = 0 j = 4
i = 1 j = 0
i = 1 j = 1
i = 1 j = 2
i = 1 j = 3
i = 1 j = 4
i = 2 j = 0
i = 2 j = 1
i = 2 j = 2
i = 2 j = 3
i = 2 j = 4
You can also use the keyword continue to return to the beginning of a named loop. And if necessary, you can use break (or continue) in a nested if-else with a for loop to break up several loops using an if-else. This will help avoid creating up a large number of flags and checking them in an if-else statement to determine whether to continue or exit the inner loop.

Task 4: Find a single duplicate in an array of integers

You are given an integer array (or an ArrayList, if you prefer) that contains every Integer from 1 to 100. The array has one, and only one, duplicate element. How do you find it? It is more common for a Java programmer to get this type of task than the previous three. Because it's about logic rather than your knowledge of rarely used subtleties of the language. Your first unbridled impulse to use brute force will pass rather quickly when your brain kicks in or you realize "I'm a programmer. I'm smart." The only problem is that during an interview, when you're under stress, this might not happen. So think now before you look at the solution!

Here's the algorithm

Calculate the sum of all numbers from 1 to 100. We think you know how you can do this (for example, using Gauss's famous method). Now calculate the sum of the elements in your array or ArrayList. And... subtract the first sum from the second. Bingo! The resulting number is the value of the duplicate element. Java code for this task using an ArrayList.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class FindDuplicate {
    private static void findDuplicate(List<Integer> elements) {

        int distinctSum = elements.stream().distinct().mapToInt(e -> e).sum();
// Find the sum of all list elements
        int totalSum = elements.stream().mapToInt(e -> e).sum();
        System.out.println("The repeated element is: " + (totalSum - distinctSum));
    }

    public static void main(String[] args) {
// Create a list of sequential elements in the interval [1..101).
        List <Integer> elements = IntStream.range(1, 101).boxed().collect(Collectors.toList());
// Add the value 23 at index 53
        elements.set(53, 23);
        findDuplicate(elements);
    }
}

Another solution

import java.util.List;
import java.util.ArrayList;

public class Duplicate {

    public int findDuplicateNumber(List<Integer> numbers) {

        int highestNumber = numbers.size() - 1;
        int total = getSum(numbers);
        int duplicate = total - (highestNumber * (highestNumber + 1) / 2);
        return duplicate;
    }

    public int getSum(List<Integer> numbers) {

        int sum = 0;
        for (int num : numbers) {
            sum = sum + num;
        }
        return sum;
    }

    public static void main(String a[]) {
        List <Integer> numbers = new ArrayList <Integer>();
        for (int i = 1; i < 100; i++) {
            numbers.add(i);
        }
        // Add a duplicate to the list
        numbers.add(25);
        Duplicate dn = new Duplicate();
        System.out.println("The repeated element is: " + dn.findDuplicateNumber(numbers));
    }
}

Task 5: Find a non-unique duplicate in an array of integers

If the previous task was too easy for you, try doing this one: You are given a list of integers from 1 to 100. There are duplicates in it (more than one). How do you find the elements that occur more than once (find the elements and indicate how many times they occur)?

Solution

Here the logical solution would be to use a something like a HashMap, because it stores the data in key-value pairs. Code for this task in Java:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class SomeDuplicates {
    private static void findDuplicates(List<Integer> elements) {
        HashMap <Integer, Integer> duplicates = new HashMap <>();
// Use the following rule to populate the Map duplicates:
// the key is the element value, and the value is the number of times it occurs
        elements.forEach(e -> duplicates.put(e, duplicates.get(e) == null ? 1 : duplicates.get(e) + 1));
// Remove any elements that don't occur more than once from the Map duplicates
// and store the result as a list (to make it easy to work with in the next step)
        List <Map.Entry <Integer, Integer> >
        result = duplicates.entrySet().stream().filter(d -> d.getValue() > 1).collect(Collectors.toList());
// Write the results for all elements to the result list
        result.forEach(e -> System.out.println(String.format("Element %d  occurs %d times", e.getKey(), e.getValue())));
    }

    public static void main(String[] args) {
        List <Integer> elements = IntStream.range(1, 101).boxed().collect(Collectors.toList());
        elements.set(97, 23);
        elements.set(27, 51);
        elements.set(99, 23);
        findDuplicates(elements);
    }
}

Conclusion

There are lots of different kinds of practical Java tasks, and you don't know what sort of puzzles the interviewer will ask you to solve. But, any sensible employer understands that your ability to complete real practical tasks, like the ones you'll encounter on the job, is much more important than your ability to solve trick questions. So do these as much as possible. That's why we created CodeGym. Material from geeksforgeeks was used to create this article.