Java Coding Interview Question and Answers 1

 

Question

Answer

Java Code Example

What is a ConcurrentModification Exception?

It occurs when one attempts to modify a collection while iterating over it.

List<String> list = new ArrayList<>(Arrays.asList("one", "two")); for(String s : list) { list.remove(s); } This will throw ConcurrentModificationException

How can you invoke a method using the Reflection API?

The Reflection API allows invoking a method using the invoke method.

Java Class<?> clazz = String.class; Method method = clazz.getMethod("substring", int.class); String str = "hello"; String result = (String) method.invoke(str, 2); System.out.println(result); // llo

What is a Record?

In Java, a record is a type declaration that defines a transparent carrier for immutable data. It can be thought of as a nominal tuple.

Java record Person(String name, int age) {}; Person person = new Person("John", 25); System.out.println(person.name());

What is an atomic variable?

Atomic variables support lock-free thread-safe programming on single variables. They can be used in scenarios where atomicity is required for variable operations.

Java AtomicInteger atomicInt = new AtomicInteger(0); atomicInt.incrementAndGet();

What is a short-circuit method?

Short-circuiting is the act of not executing certain expressions if earlier expressions in a series guarantee the result. && and `




Question

Answer

Java Code Example

What is a Constructor?

A constructor in Java is a block of code that initializes an object. It has the same name as the class and looks like a method but has no return type.

Java public class MyClass { public MyClass() { System.out.println("Constructor called!"); } } MyClass obj = new MyClass(); // Outputs: Constructor called!

When should you use ? extends T?

? extends T is used for upper-bounded wildcards. It restricts the unknown type to be a subtype of T. Useful when you want to read items from a structure, but you don't know the exact type.

Java public static <T> void process(List<? extends T> list) { for (T item : list) { // ... } }

What is an annotation?

Annotations provide metadata about the program that is not part of the program itself. They have no direct effect on the operation of the code they annotate.

Java @Override public String toString() { return "MyClass"; }

How can you model a concurrent task in Java?

Java provides the Runnable and Callable interfaces to model tasks that can be executed concurrently using threads.

Java Runnable task = () -> { System.out.println("Running task in thread: " + Thread.currentThread().getName()); }; Thread thread = new Thread(task); thread.start();

Comparing Doubles with a comparator of Numbers?

Comparing Doubles should take into account precision. The Comparator interface can be used to compare them.

Java Comparator<Number> numberComparator = (n1, n2) -> Double.compare(n1.doubleValue(), n2.doubleValue());




Question

Answer

Java Code Example

Difference between toList() and Collectors.toList()?

toList() is a method in the Stream interface while Collectors.toList() returns a Collector to accumulate the input elements into a new List.

Java List<String> list = Stream.of("A", "B", "C").collect(Collectors.toList());

What is the difference between a Collection and a List?

A Collection is a root interface in the collection hierarchy. A List is an ordered collection and an extension of Collection.

Java Collection<String> collection; List<String> list = new ArrayList<>();

Creating an instance of a Class using the Reflection API?

You can use the Class class's newInstance method or the Constructor class's newInstance method.

Java Class<?> clazz = MyClass.class; MyClass obj = (MyClass) clazz.getDeclaredConstructor().newInstance();

What is a deadlock?

Deadlock is a situation where two or more threads are blocked forever, each waiting for the other to release a lock.

// Hard to represent in a short code. Usually happens with two threads trying to acquire two locks in opposite order.

What list can you pass to a method that takes a List of Number?

You can pass any list that contains objects of a type which is a subclass of Number (e.g., Integer, Double, Float).

Java public void processList(List<? extends Number> numbers) { // ... } List<Integer> intList = Arrays.asList(1, 2, 3); processList(intList);




Question

Answer

Java Code Example

Difference between toList() and Collectors.toList()?

toList() is from the Stream itself. Collectors.toList() helps turn a Stream into a List.

Java List<String> list = Stream.of("A", "B", "C").collect(Collectors.toList());

What is the difference between a Collection and a List?

Collection is a big category, like "vehicles." List is a specific type in that category, like "cars."

Java Collection<String> collection; List<String> list = new ArrayList<>();

Creating an instance of a Class using the Reflection API?

It's like making an object from a class, but in a dynamic way.

Java Class<?> clazz = MyClass.class; MyClass obj = (MyClass) clazz.getDeclaredConstructor().newInstance();

What is a deadlock?

It's when two threads are stuck, each waiting for the other to move.

// A bit complex for a short code. Imagine two people trying to pass a narrow hallway, but neither wants to step back.

What list can you pass to a method that takes a List of Number?

Any list with things like Integer, Double, etc. because they all come under Number.

Java public void processList(List<? extends Number> numbers) { // ... } List<Integer> intList = Arrays.asList(1, 2, 3); processList(intList);



Question

Answer

Java Code Example

How can you model a concurrent task in Java?

You use something like Runnable to do tasks at the same time.

Java Runnable task = () -> { System.out.println("Task is running."); }; Thread thread = new Thread(task); thread.start();

Comparing Doubles with a comparator of Numbers?

You can use a tool called Comparator to see which number is bigger.

Java Comparator<Number> compareNumbers = (a, b) -> Double.compare(a.doubleValue(), b.doubleValue());

What is an annotation?

Annotations are special notes in the code that give extra information.

Java @Override public String toString() { return "MyClass"; }

What is a Constructor?

A constructor makes a new object from a class.

Java public class Dog { public Dog() { System.out.println("A new dog!"); } } Dog myDog = new Dog(); // Prints: A new dog!

When should you use ? extends T?

When you want a list of items that are a certain type or related to that type.

Java public void showList(List<? extends Number> numbers) { // ... }





Question

Answer

Java Code Example

Difference between an intermediate and a terminal operation?

Intermediate operations make a new stream and don't finish the task. Terminal operations finish the task and give a result.

Java Stream.of(1, 2, 3).filter(num -> num > 1).collect(Collectors.toList()); // filter is intermediate, collect is terminal

What does passing by value mean?

It means you're giving a copy of the thing, not the original thing itself.

Java int x = 10; changeValue(x); // x is still 10 after this method

How can you declare a generic type on a static method?

You can use special symbols like <T> before the method to say it can work with any type.

Java public static <T> void showItem(T item) { System.out.println(item); }

How can you update a field using the Reflection API?

Reflection lets you look at and change the insides of objects, even the hidden parts.

Java MyClass obj = new MyClass(); Field field = obj.getClass().getDeclaredField("myField"); field.setAccessible(true); field.set(obj, "newValue");

How can you join Strings with a separator?

You can use the join method to put strings together with something in between.

Java String result = String.join("-", "Hello", "World"); // result is "Hello-World"


Question

Answer

Java Code Example

How is Set.of() working?

It makes a set with the things you give it, and this set can't change after that.

Java Set<String> fruits = Set.of("apple", "banana");

How can you remove elements from a Stream?

You can use filter to keep only the things you want.

Java Stream.of(1, 2, 3).filter(num -> num != 2); // This keeps 1 and 3

How can you stop a Thread?

There's no direct "stop" button, but you can ask it nicely to stop using a volatile flag.

Java volatile boolean keepRunning = true; Thread t = new Thread(() -> { while (keepRunning) {} }); t.start(); keepRunning = false; // This asks the thread to stop

What is a generic type?

It's a way to tell Java a method or class can work with many types, like numbers, strings, etc.

Java List<String> names = new ArrayList<>(); List<Integer> numbers = new ArrayList<>();



Question

Answer

Java Code Example

How is synchronization working?

It's like a rule that says only one person can use something at a time.

Java synchronized(myObject) { // Only one thread can use myObject here }

What is the difference between map() and flatMap()?

map() changes each item in a list. flatMap() can change each item and also combine lists together.

Java List.of(1,2,3).map(n -> n * 2); // gives [2,4,6] List.of(List.of(1,2), List.of(3,4)).flatMap(l -> l.stream()); // gives [1,2,3,4]

What is the difference between Runnable and Thread?

Runnable is a job to do. Thread is like a worker that does the job.

Java Runnable job = () -> System.out.println("Doing job!"); Thread worker = new Thread(job);

How can you start a Thread?

You tell the worker (Thread) to start(), and it begins the job.

Java Thread worker = new Thread(() -> System.out.println("Job started!")); worker.start(); // This begins the job




public class SynchronizedExample {


    // Shared object to use for synchronization

    private final Object myLock = new Object();


    public static void main(String[] args) {

        SynchronizedExample example = new SynchronizedExample();


        // Create and start multiple threads to demonstrate synchronization

        Thread thread1 = new Thread(() -> example.performTask());

        Thread thread2 = new Thread(() -> example.performTask());


        thread1.start();

        thread2.start();

    }


    public void performTask() {

        synchronized(myLock) {

            System.out.println(Thread.currentThread().getName() + " is inside the synchronized block.");

            

            // Simulate some work inside the synchronized block

            try {

                Thread.sleep(1000);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

            

            System.out.println(Thread.currentThread().getName() + " is leaving the synchronized block.");

        }

    }

}

When you run this code, you'll notice that one thread fully enters and exits the synchronized block before the other thread can enter. This ensures that only one thread can execute the synchronized block at a time, using myLock as the synchronization lock.



Question

Answer

Java Code Example

How is List.of() working?

It makes a list with the things you give it. This list can't be changed later.

Java List<String> colors = List.of("red", "blue");

What is a sealed type in Java?

It's like a boss class that says only certain classes can be its children.

Java sealed class Animal permits Dog, Cat {} class Dog extends Animal {} class Cat extends Animal {}

How can you find duplicates in a list?

You can use a set to help see which things appear more than once.

Java List<String> items = List.of("a", "b", "a"); Set<String> uniqueItems = new HashSet<>(); items.forEach(item -> { if (!uniqueItems.add(item)) System.out.println(item + " is a duplicate!"); });

What is the class named Class?

It's a special class in Java that has info about other classes.

Java Class<?> stringClass = String.class; System.out.println(stringClass.getName()); // Prints: java.lang.String




Absolutely, let's continue simplifying these concepts:

Question

Answer

Java Code Example

How can you create a File with Java I/O?

You can tell Java to make a new file in a certain place on your computer.

Java File newFile = new File("path/to/your/file.txt"); try { boolean wasCreated = newFile.createNewFile(); } catch (IOException e) { System.out.println("Error making file!"); }

How can you create an unmodifiable list?

You can make a list that can't be changed once you create it.

Java List<String> fixedList = List.of("apple", "banana");

What is the var keyword in Java?

It's a shortcut. Java will guess what type something is without you saying it.

Java var name = "John"; // Java knows 'name' is a String

Can you cite some methods from the Stream API?

Yes, the Stream API has methods to work on lists of things, like filtering or changing items.

Java List<Integer> numbers = List.of(1, 2, 3); numbers.stream().filter(num -> num > 1).map(num -> num * 2); // Uses filter and map methods




Question

Answer

Java Code Example

How is Arrays.asList() working?

It turns an array into a list. But remember, the size of this list can't be changed later.

Java String[] colors = {"red", "blue"}; List<String> colorList = Arrays.asList(colors);

How does a Set know that it already contains an element?

A Set uses methods called equals() and hashCode() to check if it already has the same thing inside.

Java Set<String> names = new HashSet<>(); names.add("John"); boolean hasJohn = names.contains("John"); // This is true

What is the maximum length of a String in Java?

A String in Java can have as many characters as the biggest value of an int. That's 2,147,483,647 (over 2 billion) characters!

Java // No direct code for this, but it's a fact about the String class!

How many objects can you put in a Collection?

Just like with String, a Collection can hold as many things as the biggest value of an int. Again, that's 2,147,483,647 objects!

Java // No direct code, but it's a fact about the Collection classes!





Question

Answer

Java Code Example

What are the four Java I/O base classes?

These are basic classes in Java for reading and writing data: InputStream, OutputStream (for bytes) and Reader, Writer (for characters).

Java // No direct code, but you can use these classes to read/write data.

What is an Iterator?

It's a tool to go through a list (or other collection) one item at a time.

Java List<String> names = Arrays.asList("Alice", "Bob"); Iterator<String> nameIterator = names.iterator(); while(nameIterator.hasNext()) { System.out.println(nameIterator.next()); }

What is an ExecutorService?

It's like a boss that manages workers (Threads). You give it tasks, and it tells the workers to do them.

Java ExecutorService boss = Executors.newFixedThreadPool(2); boss.submit(() -> System.out.println("Doing task!")); boss.shutdown();

What is the hash code of an object?

It's a special number for an object. Java uses it to quickly find and group objects.

Java Object obj = new Object(); int hash = obj.hashCode(); System.out.println(hash);








Question

Answer

Java Code Example

How does a SortedSet work?

SortedSet is like a list but always keeps items in order. When you add a new item, SortedSet puts it in the right place.

Java SortedSet<Integer> numbers = new TreeSet<>(); numbers.add(3); numbers.add(1); System.out.println(numbers); // Prints: [1, 3]

How can you print an array on the console?

You can use a helper method from the Arrays class to turn the array into a string and then print it.

Java int[] nums = {1, 2, 3}; System.out.println(Arrays.toString(nums)); // Prints: [1, 2, 3]

How can you open a file for reading binary data?

You use special classes from Java that can read data as 0s and 1s, not just text.

Java FileInputStream fileInput = new FileInputStream("path/to/file"); // Use fileInput to read bytes from the file.

Difference between a sorted and an ordered collection?

"Sorted" means items are in a specific order (like numbers from small to big). "Ordered" just means items have a set position, but not necessarily in a special order.

Java List<Integer> ordered = Arrays.asList(3, 1, 2); // Items have set positions SortedSet<Integer> sorted = new TreeSet<>(ordered); // Items are in order





Question

Answer

Java Code Example

How can you open a file for writing text?

You use a special Java class that lets you write text to a file.

Java FileWriter writer = new FileWriter("path/to/file.txt"); writer.write("Hello!"); writer.close();

Can you cite functional interfaces from before Java 8?

Yes! A functional interface has only one method. A common old one is Runnable.

Java Runnable task = new Runnable() { public void run() { System.out.println("Running!"); } };

How can you create a Comparator?

A Comparator is a tool for sorting. You tell it how to compare things.

Java Comparator<String> byLength = new Comparator<>() { public int compare(String a, String b) { return a.length() - b.length(); } };

What is the GoF?

GoF stands for "Gang of Four". They wrote a famous book about design patterns in programming.

Java // No code example, it's more about ideas in a book!



Question

Answer

Java Code Example

What is the difference between FIFO and LIFO?

FIFO means "First In, First Out". Think of a line at the store. First person in line is the first to leave. LIFO means "Last In, First Out". Think of a stack of plates. The last plate you put on top is the first you take off.

Java // For FIFO: Queue<Integer> queue = new LinkedList<>(); queue.add(1); queue.remove(); // For LIFO: Stack<Integer> stack = new Stack<>(); stack.push(1); stack.pop();

What is a groupingBy()?

It's a tool in Java to group items by some property. Like grouping people by age.

Java List<String> names = Arrays.asList("Anna", "Bob", "Charlie"); Map<Integer, List<String>> grouped = names.stream().collect(Collectors.groupingBy(String::length)); // Groups names by their length.

On what kind of source can you build a stream?

In Java, you can make a stream from lists, sets, maps, and more. A stream lets you handle data in steps, like a pipeline.

Java List<String> list = Arrays.asList("a", "b", "c"); Stream<String> stream = list.stream();

How can you tell that a String is an anagram of another String?

An anagram has the same letters, but in a different order. To check, make sure both words have the same letters and counts.

Java String str1 = "listen"; String str2 = "silent"; boolean areAnagrams = Arrays.equals(str1.chars().sorted().toArray(), str2.chars().sorted().toArray()); System.out.println(areAnagrams); // Prints: true





Question

Answer

Java Code Example

Do Streams and Collections have common methods?

Yes, they do. Both can handle groups of items. But Streams are like conveyor belts (they handle items one by one and then finish), while Collections are like boxes (they hold items).

Java List<String> list = Arrays.asList("a", "b", "c"); list.forEach(System.out::println); // Collection method Stream<String> stream = list.stream(); stream.forEach(System.out::println); // Stream method

What were the main features of Java 8?

Java 8 brought new things like Streams, Lambdas (shorter way to write code), and new date and time tools.

Java List<String> items = Arrays.asList("apple", "banana", "cherry"); items.stream().forEach(item -> System.out.println(item)); // Using Java 8's Stream and Lambda

How does finalize() work?

finalize() is a special method. Before Java cleans up an object (removes it to free up space), it calls this method if you have provided one.

Java @Override protected void finalize() { System.out.println("Object is being cleaned up!"); }

What is the difference between Collection and a Set?

Collection is a big group that can include List, Set, and others. Set is just one type of Collection that doesn't allow duplicate items.

Java Collection<String> collection; // Can be a list, set, etc. Set<String> set = new HashSet<>(); set.add("apple"); set.add("apple"); // This duplicate won't be added

What is a marker interface?

It's an interface with no methods. It just "marks" a class. Like putting a label on it. Serializable is one example.

Java public class MyClass implements Serializable { // No methods inside, but it's marked as Serializable! }



Question

Answer

Java Code Example

What is the signature of a method?

It's the method's name and the types of its parameters (the inputs). It doesn't include the return type (the output).

Java public int add(int a, int b) { return a + b; } // Signature: add(int, int)

What kind of method can you override?

In Java, if a method isn't marked as final, static, or private, you can change its behavior in a subclass. This is called overriding.

Java class Animal { void sound() { System.out.println("Some sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Bark"); } }

What is a JIT?

JIT stands for "Just-In-Time". It's a part of Java that turns your Java code into machine code just when you run it, making it faster.

Java // No direct code example for JIT, it works in the background!

What is a default method?

In interfaces, you usually can't have methods with bodies. But with default methods, you can! This lets you add new methods without breaking old code.

Java interface MyInterface { default void show() { System.out.println("Default method!"); } } class MyClass implements MyInterface { } // MyClass can now use show() without needing to define it.


Question

Answer

Java Code Example

Difference between String, StringBuffer, and StringBuilder?

String is a text that can't change. StringBuffer and StringBuilder can change. StringBuffer is older and safer for many tasks at once, while StringBuilder is faster but not as safe for many tasks.

Java String s = "apple"; StringBuffer sb = new StringBuffer("apple"); StringBuilder stb = new StringBuilder("apple");

How to make a class immutable?

Make it so nothing can change it after you create it. Make fields final, no setters, and only getters.

Java public final class ImmutableClass { private final int data; public ImmutableClass(int data) { this.data = data; } public int getData() { return data; } }

Explain finally.

finally is used with try-catch. No matter if there's an error or not, the code in finally always runs.

Java try { System.out.println("Trying something"); } catch(Exception e) { System.out.println("Error!"); } finally { System.out.println("This always runs."); }

What is an ArrayList?

It's like a stretchy array. You can add or remove items. It's part of the Java's built-in tools.

Java ArrayList<String> fruits = new ArrayList<>(); fruits.add("apple"); fruits.add("banana");




Question

Answer

Java Code Example

What is a Map?

It's like a dictionary. It holds pairs: a key and a value. You use the key to get the value.

Java Map<String, Integer> ages = new HashMap<>(); ages.put("John", 25); int age = ages.get("John");

Difference between overriding and overloading?

Overriding is giving a new version of a method in a child class. Overloading is having many methods with the same name but different inputs in one class.

Java class Animal { void sound() {} } class Dog extends Animal { void sound() { System.out.println("Bark"); } // Overriding } class MathHelper { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } // Overloading }

What is a functional interface?

It's an interface with just one method (excluding default and static methods). They're used a lot with lambdas.

Java @FunctionalInterface interface MyFunc { int operate(int a, int b); }

How can you reverse a String?

Use the StringBuilder and its reverse() method.

Java String word = "apple"; String reversed = new StringBuilder(word).reverse().toString(); System.out.println(reversed); // prints: elppa





Question

Answer

Java Code Example

How can you duplicate an array?

You can copy an array using Java's built-in tools.

Java int[] original = {1, 2, 3}; int[] copy = Arrays.copyOf(original, original.length);

What about equals() and hashCode()?

equals() checks if two objects are the same in content. hashCode() gives a number for an object. If two objects are the same using equals(), their hashCode() should be the same.

Java String s1 = new String("hello"); String s2 = new String("hello"); boolean isEqual = s1.equals(s2); // true int code = s1.hashCode();

What is the difference between == and equals()?

== checks if two things point to the same place in memory. equals() checks if their content is the same.

Java String s1 = new String("hello"); String s2 = new String("hello"); boolean check1 = s1 == s2; // false boolean check2 = s1.equals(s2); // true

What is the main characteristic of the String class?

Strings can't change (they're "immutable"). If you do something to a String, you get a new one.

Java String s1 = "hello"; String s2 = s1.toUpperCase(); // s2 is "HELLO", s1 is still "hello"

How can you sort an array?

Use Java's built-in tools to sort arrays.

Java int[] numbers = {3, 1, 2}; Arrays.sort(numbers); // Now numbers is {1, 2, 3}






Question

Answer

Java Code Example

What is the JVM?

JVM stands for "Java Virtual Machine". It's a tool that lets Java programs run on any device.

No code for this, it's a concept.

How do you sum the elements of an array?

You can go through each number in the array and add them up.

Java int[] numbers = {1, 2, 3}; int sum = 0; for(int num : numbers) { sum += num; } // sum is 6

What differences between String and char[]?

String is a group of characters with methods. char[] is a simple list of characters.

Java String str = "hello"; char[] chars = {'h', 'e', 'l', 'l', 'o'};

Can you cite methods from the Object class?

Every class in Java comes from the Object class. It has methods like toString(), equals(), and hashCode().

Java Object obj = new Object(); String text = obj.toString();

What is the Object class?

It's the main class in Java. Every other class is a child of this class.

No code for this, it's a base concept.

What is Java?

Java is a programming language. You write commands in Java, and they can run on many devices.

No code for this, it's a general concept.





Comments

Popular posts from this blog

state government roles website

Follow these steps to install eksctl

SQL Tutorials 10 hours