Testdome Java Questions And Answers -

Alex is a junior developer preparing for a technical interview.
He opens TestDome to practice Java problems. Three questions appear.


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileHandler public static String readFirstLine(String path) try (BufferedReader br = new BufferedReader(new FileReader(path))) return br.readLine(); catch (IOException e) return "";

Why TestDome insists on this:


Question:
Implement classes Animal, Dog, and Cat. Animal has makeSound(). Dog prints "Woof", Cat prints "Meow". Create a method makeSound(Animal animal) that calls the appropriate sound.

Solution:

class Animal 
    public void makeSound() 
        System.out.println("Some sound");

class Dog extends Animal @Override public void makeSound() System.out.println("Woof");

class Cat extends Animal @Override public void makeSound() System.out.println("Meow");

public class Main public static void makeSound(Animal animal) animal.makeSound(); // polymorphic call

Key insight: TestDome checks if you correctly use @Override and runtime polymorphism. testdome java questions and answers


Sample Question:
Given a list of Product objects (name, price, category), return the sum of prices for all products in category "Electronics", but only if the price > 100. Use Java streams.

import java.util.HashSet;
import java.util.Set;

public class LongestConsecutive public static int longestConsecutive(int[] nums)

Why this passes TestDome checks:


Question:
Return indices of two numbers in an array that add up to a target. Assume exactly one solution. Optimize for time. Alex is a junior developer preparing for a

Solution (O(n) time, O(n) space):

import java.util.*;

public class TwoSum { public static int[] findTwoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) int complement = target - nums[i]; if (map.containsKey(complement)) return new int[] map.get(complement), i ; map.put(nums[i], i); return new int[] {}; // not reached given "exactly one solution" } }

Why TestDome likes it: