Top 50 Tricky Java Interview Questions and Answers

Top 50 Tricky Java Interview Questions and Answers

Streamline hiring with effortless screening tools

Optimise your hiring process with HiPeople's AI assessments and reference checks.

In this article

Are you ready to conquer the challenges of Tricky Java Interview Questions? Whether you're aiming for that dream job or seeking to level up your Java skills, this guide has you covered.

Dive into the world of complex Java queries, unravel their intricacies, and emerge as a confident and proficient Java developer. Let's unravel the secrets to mastering those tricky interview questions!

What are Tricky Java Interview Questions?

Tricky Java interview questions are not your typical run-of-the-mill inquiries. These questions are designed to test your in-depth knowledge of Java, problem-solving skills, and ability to think critically under pressure. They often go beyond the basics and challenge you to demonstrate a deep understanding of the language, its nuances, and its application in real-world scenarios.

Characteristics of Tricky Java Interview Questions

  • Complexity: Tricky questions may involve intricate scenarios, multiple concepts, or unusual edge cases.
  • Problem-Solving: They often require creative problem-solving and the ability to devise efficient solutions.
  • Application: These questions may assess your ability to apply Java concepts to practical situations.
  • Critical Thinking: Expect questions that demand critical thinking and the ability to identify potential pitfalls.
  • Depth of Knowledge: Tricky questions may probe your understanding of advanced Java topics and best practices.

Importance of Java Interviews

Java interviews hold significant importance for both job seekers and employers.

For Job Seekers

  • Career Opportunities: Mastering Java can open doors to a wide range of job opportunities in software development, backend engineering, mobile app development, and more.
  • Higher Compensation: Companies often offer competitive salaries to skilled Java developers due to the language's widespread use and demand.
  • Skill Validation: Success in Java interviews validates your expertise and serves as a testament to your capabilities.

For Employers

  • Quality Talent Acquisition: Java interviews help companies identify and hire talented individuals who can contribute effectively to their projects.
  • Code Quality: Hiring skilled Java developers results in higher-quality code, which is critical for the success and maintainability of software systems.
  • Productivity: Experienced Java developers tend to be more productive and require less training, saving companies time and resources.

Preparing for Tricky Java Interviews

Preparing for tricky Java interviews requires a structured and focused approach. Here are some steps to help you get ready:

  • Review Core Concepts: Ensure your foundational knowledge of Java is strong, including object-oriented programming, data types, and control structures.
  • Explore Advanced Topics: Delve into advanced Java topics like multithreading, design patterns, and Java Virtual Machine (JVM) internals.
  • Practice Coding: Regularly practice coding exercises and challenges to sharpen your problem-solving skills.
  • Read Java Documentation: Familiarize yourself with the official Java documentation to understand standard libraries and best practices.
  • Mock Interviews: Consider participating in mock interviews to simulate real interview scenarios and receive feedback.
  • Stay Updated: Stay abreast of Java updates and industry trends to demonstrate your commitment to continuous learning.

Common Interview Formats

Java interviews come in various formats, each with its own focus and objectives. Here's an overview of common interview formats you might encounter:

  • Technical Assessment: You may be asked to complete coding challenges or technical tests online, focusing on your coding skills and problem-solving abilities.
  • Behavioral Interview: In this format, the interviewer evaluates your soft skills, teamwork, and how you handle various workplace scenarios.
  • Whiteboard Coding: You might need to solve coding problems on a whiteboard or explain your approach verbally, emphasizing problem-solving skills.
  • Panel Interview : Multiple interviewers assess your technical knowledge, problem-solving skills, and cultural fit within the company.
  • Take-Home Assignment: You receive a coding assignment to complete at home within a specified timeframe, demonstrating your coding proficiency and time management.

Understanding these interview formats can help you tailor your preparation to the specific requirements of your upcoming Java interview.

Core Java Concepts

Let's dive into the fundamental concepts of Java that are crucial for acing those tricky interviews.

Object-Oriented Programming Principles

Object-oriented programming (OOP) is the backbone of Java. It's essential to understand how objects and classes work together.

Classes and Objects

In Java, everything revolves around classes and objects. A class is a blueprint for creating objects, while objects are instances of classes. Here's a simple example:

class Car {    String brand;    int year;    void start() {        System.out.println("Car started!");    } } public class Main {    public static void main(String[] args) {        Car myCar = new Car();        myCar.brand = "Toyota";        myCar.year = 2020;        myCar.start();    } }

In this example, we define a Car class with attributes brand and year , along with a start method. We then create an instance of the Car class and use it to access the class's members.

Inheritance and Polymorphism

Inheritance allows one class to inherit the attributes and methods of another class. Polymorphism enables objects to take on multiple forms.

class Animal {    void makeSound() {        System.out.println("Some sound");    } } class Dog extends Animal {    @Override    void makeSound() {        System.out.println("Woof!");    } } public class Main {    public static void main(String[] args) {        Animal myDog = new Dog();        myDog.makeSound(); // Outputs "Woof!"    } }

Here, the Dog class inherits from the Animal class and overrides the makeSound method to provide a specific implementation.

Java Data Types and Variables

Java supports various data types, which determine the kind of data that can be stored in a variable.

Primitive Data Types

  • int: Represents whole numbers.
  • double: Represents floating-point numbers.
  • char: Represents a single character.
  • boolean: Represents true or false values.
int age = 25; double salary = 55000.50; char grade = 'A'; boolean isJavaFun = true;

Reference Data Types

Reference data types hold references (memory addresses) to objects. Common reference data types include arrays, strings, and user-defined classes.

String name = "John"; int[] numbers = {1, 2, 3, 4, 5};

Control Flow Statements

Control flow statements allow you to control the execution of your Java code.

Conditional Statements

Conditional statements, like if , else if , and else , help you make decisions in your code.

int score = 85; if (score >= 90) {    System.out.println("Excellent!"); } else if (score >= 70) {    System.out.println("Good job!"); } else {    System.out.println("Keep practicing."); }

Looping Statements

Looping statements, including for , while , and do-while , allow you to repeat tasks.

for (int i = 1; i <= 5; i++) {    System.out.println("Iteration " + i); } int count = 0; while (count < 3) {    System.out.println("Count: " + count);    count++; }

Exception Handling

Exception handling in Java is crucial for robust and error-free code.

Try-Catch Blocks

try {    // Code that may throw an exception    int result = 10 / 0; // This will throw an ArithmeticException } catch (ArithmeticException e) {    // Handle the exception    System.out.println("An error occurred: " + e.getMessage()); }

Custom Exceptions

You can create custom exceptions to handle specific error scenarios effectively.

class MyCustomException extends Exception {    public MyCustomException(String message) {        super(message);    } } public class Main {    public static void main(String[] args) {        try {            throw new MyCustomException("This is a custom exception.");        } catch (MyCustomException e) {            System.out.println("Caught custom exception: " + e.getMessage());        }    } }

Multithreading and Concurrency

Multithreading allows Java programs to execute multiple threads concurrently.

Input/Output (I/O) Operations

Input and output operations are essential for interacting with external data sources.

Java Fundamentals Interview Questions

1. what is the difference between == and .equals() in java for comparing objects.

How to Answer: Candidates should explain that == compares object references for equality, while .equals() is a method used to compare the content or value of objects. It's essential to mention that .equals() can be overridden by custom classes to provide a meaningful comparison based on object attributes.

Sample Answer: " == compares object references, checking if they point to the same memory location. In contrast, .equals() compares the actual content of objects. For instance, when comparing strings, .equals() checks if the character sequences are identical."

What to Look For: Look for candidates who understand the fundamental distinction between reference equality and content equality. They should also demonstrate knowledge of when and how to override the .equals() method in custom classes.

2. What are the differences between ArrayList and LinkedList in Java?

How to Answer: Candidates should highlight that ArrayList is backed by an array, provides fast random access, but has slower insertions and deletions. LinkedList uses a doubly linked list, excels in insertions/deletions, but is slower for random access. They should discuss use cases for each data structure.

Sample Answer: " ArrayList is based on an array, allowing fast random access. However, insertions and deletions are slower due to array resizing. LinkedList uses a doubly linked list, making insertions and deletions faster, but accessing elements sequentially is more efficient."

What to Look For: Look for candidates who can articulate the trade-offs between ArrayList and LinkedList and demonstrate when to use each data structure based on specific requirements.

3. Explain the significance of the static keyword in Java.

How to Answer: Candidates should describe that static denotes class-level members (variables or methods) that belong to the class, not instances. They should mention that static members can be accessed without creating an object of the class and are shared across all instances of the class.

Sample Answer: "The static keyword is used to define class-level members in Java. These members belong to the class itself, not to instances of the class. This means you can access static members without creating objects of the class, and changes to static variables are shared among all instances."

What to Look For: Look for candidates who can clearly explain the concept of static and provide examples of when and why it's useful, such as for constants or utility methods.

Object-Oriented Programming Interview Questions

4. what is the difference between an abstract class and an interface in java.

How to Answer: Candidates should explain that an abstract class can have both abstract (unimplemented) and concrete (implemented) methods, while an interface can only have abstract methods. They should also mention that a class can implement multiple interfaces but inherit from only one abstract class.

Sample Answer: "An abstract class can have both abstract and concrete methods, while an interface can only contain abstract methods. A class can implement multiple interfaces, but it can inherit from only one abstract class."

What to Look For: Look for candidates who can clearly articulate the distinctions between abstract classes and interfaces, understand their use cases, and explain when to prefer one over the other.

5. How does Java support multiple inheritance, and what is the "diamond problem"?

How to Answer: Candidates should discuss that Java supports multiple inheritance through interfaces, allowing a class to implement multiple interfaces. They should explain the "diamond problem" as a naming conflict when a class inherits methods with the same signature from multiple interfaces and how Java resolves it using interface method implementation.

Sample Answer: "Java supports multiple inheritance through interfaces, where a class can implement multiple interfaces. The 'diamond problem' occurs when a class inherits methods with the same signature from multiple interfaces. Java resolves this by requiring the implementing class to provide its implementation for the conflicting method."

What to Look For: Look for candidates who can explain how Java handles multiple inheritance and understand the challenges and solutions associated with the "diamond problem."

6. What are the access modifiers in Java, and how do they differ?

How to Answer: Candidates should list and describe the four main access modifiers in Java: public , private , protected , and default (no modifier). They should explain their visibility and accessibility rules within and outside the class hierarchy.

Sample Answer: "In Java, there are four access modifiers: public (accessible from anywhere), private (only within the same class), protected (within the same package and subclasses), and default (package-private, within the same package). They control the visibility and accessibility of class members."

What to Look For: Look for candidates who can clearly define access modifiers and provide examples of when and why each one is used.

Exception Handling Interview Questions

7. what is the difference between checked and unchecked exceptions in java.

How to Answer: Candidates should explain that checked exceptions are compile-time exceptions that must be handled using try-catch or declared with throws in the method signature. Unchecked exceptions, on the other hand, are runtime exceptions and do not require explicit handling.

Sample Answer: "Checked exceptions are exceptions that the compiler checks at compile-time, and you must either handle them using try-catch or declare them with throws in the method signature. Unchecked exceptions, also known as runtime exceptions, do not require explicit handling."

What to Look For: Look for candidates who can distinguish between checked and unchecked exceptions, understand their implications, and provide examples of each.

8. How does the finally block work in Java exception handling?

How to Answer: Candidates should explain that the finally block is used to ensure that a specific block of code is always executed, regardless of whether an exception is thrown or not. They should emphasize that it's commonly used for cleanup tasks like closing resources.

Sample Answer: "The finally block in Java ensures that a particular block of code is executed, whether an exception occurs or not. It's commonly used for tasks like closing files or releasing resources to guarantee proper cleanup."

What to Look For: Look for candidates who can articulate the purpose of the finally block and demonstrate an understanding of its role in exception handling and resource management.

Multithreading Interview Questions

9. what is synchronization in java, and why is it necessary.

How to Answer: Candidates should explain that synchronization in Java is used to control access to shared resources by multiple threads. They should mention that it prevents race conditions and ensures data consistency. Additionally, they should discuss synchronization mechanisms like synchronized methods and blocks.

Sample Answer: "Synchronization in Java is essential for controlling access to shared resources by multiple threads. It prevents race conditions and ensures data consistency. We achieve synchronization using synchronized methods or blocks to protect critical sections of code."

What to Look For: Look for candidates who can describe the importance of synchronization in multithreaded environments, provide examples of synchronization, and discuss potential issues like deadlock and how to avoid them.

10. Explain the difference between wait() , notify() , and notifyAll() methods in Java.

How to Answer: Candidates should describe that wait() is used by a thread to release the lock and enter a waiting state until another thread calls notify() or notifyAll() to wake it up. notify() wakes up one waiting thread, while notifyAll() wakes up all waiting threads.

Sample Answer: " wait() is used by a thread to release the lock and enter a waiting state until another thread calls notify() or notifyAll() . notify() wakes up one waiting thread, while notifyAll() wakes up all waiting threads, allowing them to compete for the lock."

What to Look For: Look for candidates who can explain the purpose and differences between wait() , notify() , and notifyAll() methods and demonstrate an understanding of their use in thread synchronization.

Advanced Java Concepts Interview Questions

11. what is the java memory model (jmm), and why is it important in multithreading.

How to Answer: Candidates should explain that the Java Memory Model (JMM) defines how threads interact with memory when reading and writing shared data. It's crucial for ensuring thread safety and preventing data inconsistencies in multithreaded programs.

Sample Answer: "The Java Memory Model (JMM) defines how threads interact with memory when reading and writing shared data. It's vital for ensuring thread safety and preventing data inconsistencies in multithreaded programs by specifying the order of memory operations."

What to Look For: Look for candidates who can articulate the significance of the Java Memory Model in multithreading and how it helps maintain data consistency.

12. How does Java support garbage collection, and what are the different types of garbage collectors?

How to Answer: Candidates should explain that Java supports automatic memory management through garbage collection. They should mention the types of garbage collectors in Java, such as the Serial, Parallel, and G1 collectors, and briefly describe their characteristics.

Sample Answer: "Java supports automatic memory management through garbage collection. There are various garbage collectors in Java, including the Serial, Parallel, and G1 collectors. Each has its own characteristics and is suitable for different scenarios."

What to Look For: Look for candidates who can discuss Java's garbage collection mechanisms, their advantages, and when to use specific types of garbage collectors.

13. What is the purpose of the Java Virtual Machine (JVM), and how does it execute Java programs?

How to Answer: Candidates should explain that the JVM is responsible for executing Java bytecode. They should describe the steps involved in the execution process, such as class loading, bytecode verification, and Just-In-Time (JIT) compilation.

Sample Answer: "The Java Virtual Machine (JVM) executes Java programs by loading classes, verifying bytecode, and then executing it. It uses Just-In-Time (JIT) compilation to convert bytecode into machine code for efficient execution."

What to Look For: Look for candidates who can provide a clear overview of the JVM's role in executing Java programs and explain key steps in the execution process.

14. What is Java's reflection API, and when is it used?

How to Answer: Candidates should describe that the reflection API in Java allows inspection and manipulation of classes, methods, fields, and objects at runtime. They should mention use cases, such as dynamic code generation, serialization, and frameworks like Spring.

Sample Answer: "Java's reflection API enables runtime inspection and manipulation of classes, methods, fields, and objects. It's used in scenarios like dynamic code generation, serialization, and in frameworks like Spring for dependency injection."

What to Look For: Look for candidates who can explain the purpose of the reflection API, provide examples of its use cases, and discuss its advantages and potential drawbacks.

15. Explain the concept of Java annotations and their practical applications.

How to Answer: Candidates should describe that Java annotations are metadata annotations that provide additional information about classes, methods, fields, or other program elements. They should discuss practical applications, such as code documentation, code generation, and framework configuration.

Sample Answer: "Java annotations are metadata annotations used to provide additional information about program elements. They have practical applications in code documentation, code generation, and configuring frameworks like Hibernate or Spring."

What to Look For: Look for candidates who can explain the concept of Java annotations, offer examples of their use in real-world scenarios, and discuss their benefits in code organization and automation.

Advanced Java Topics

Now, let's dive into some advanced Java topics that will set you apart in those challenging interviews.

Java Virtual Machine (JVM) Internals

Understanding the internal workings of the Java Virtual Machine (JVM) is crucial to write efficient and optimized Java code.

JVM Architecture

  • Class Loader: Loads class files into memory.
  • Execution Engine: Executes bytecode instructions.
  • Memory Areas: Includes methods, heap, stack, and more.
  • Native Interface: Allows interaction with native libraries.

Optimizing JVM performance involves configuring memory settings, garbage collection algorithms, and thread management. Profiling tools like VisualVM and JConsole can help identify bottlenecks.

Garbage Collection in Java

Java automatically manages memory through garbage collection (GC). Understanding GC mechanisms is vital for efficient memory usage.

GC Algorithms

  • Serial GC: Single-threaded, suitable for small applications.
  • Parallel GC: Multithreaded, for medium-sized applications.
  • Concurrent Mark-Sweep (CMS) GC: Low-latency collector.
  • Garbage-First (G1) GC: Balances throughput and latency.

By adjusting GC settings, you can optimize memory usage and reduce application pauses. Common parameters include heap size, GC algorithm selection, and thread counts.

Java Reflection

Java reflection allows you to inspect and manipulate classes, methods, fields, and constructors at runtime.

Reflection Basics

You can access class metadata, inspect annotations, and invoke methods dynamically. This is especially useful for frameworks like Spring.

Class<?> clazz = MyClass.class; Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) {    System.out.println("Method Name: " + method.getName()); }

Reflection is employed in frameworks, libraries, and testing frameworks like JUnit. It enables features like dependency injection and dynamic loading.

Java Stream API

The Stream API introduced in Java 8 simplifies data processing and manipulation.

Stream Basics

Streams provide a concise way to filter, transform, and aggregate data in collections.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); int sum = numbers.stream()                .filter(n -> n % 2 == 0)                .mapToInt(Integer::intValue)                .sum();

Stream Operations

Operations like filter , map , reduce , and collect make complex data operations more readable and efficient.

Java Lambda Expressions

Lambda expressions introduce functional programming concepts to Java, making code more concise and expressive.

Lambda Syntax

Lambda expressions are defined with a parameter list, an arrow -> , and a body.

// Traditional approach Runnable runnable = new Runnable() {    public void run() {        System.out.println("Hello, World!");    } }; // Lambda expression Runnable lambdaRunnable = () -> System.out.println("Hello, World!");

Functional Interfaces

Functional interfaces define a single abstract method and are crucial for using lambda expressions.

Java Functional Programming

Functional programming (FP) principles emphasize immutability, pure functions, and higher-order functions.

Functional Concepts

  • Immutability: Avoid changing data after creation.
  • Pure Functions: Functions with no side effects.
  • Higher-Order Functions: Functions that accept or return other functions.

Benefits and Use Cases

FP can lead to more concise, predictable, and maintainable code. It's particularly useful in parallel and asynchronous programming.

Tricky Java Coding Exercises

Now, it's time to put your Java skills to the test with tricky coding exercises. These exercises will help you develop problem-solving abilities and apply your knowledge effectively.

Problem-Solving Approach

Before jumping into coding challenges, let's establish a problem-solving approach that will serve as your foundation.

Algorithm Design

  • Understand the Problem: Carefully read and comprehend the problem statement.
  • Plan Your Approach: Devise a strategy or algorithm to solve the problem step by step.
  • Implement Your Solution: Write clear and concise code based on your plan.
  • Test and Debug: Test your code with various inputs and debug any issues.
  • Optimize: Analyze your code for efficiency and make improvements if needed.

Coding Challenges and Solutions

Now, let's explore some common Java coding challenges and their solutions. These examples will help you apply your problem-solving skills and Java knowledge effectively.

Example: Finding the Maximum Number in an Array

Problem: Write a Java program to find the maximum number in an array.

public class MaxInArray {    public static int findMax(int[] arr) {        if (arr == null || arr.length == 0) {            throw new IllegalArgumentException("Array is empty or null.");        }        int max = arr[0];        for (int num : arr) {            if (num > max) {                max = num;            }        }        return max;    }    public static void main(String[] args) {        int[] numbers = { 23, 45, 12, 67, 8, 56 };        int maxNumber = findMax(numbers);        System.out.println("The maximum number is: " + maxNumber);    } }

In this example, we define a findMax method that iterates through the array and keeps track of the maximum value. The main method demonstrates how to use this method.

Example: Reversing a String

Problem: Write a Java program to reverse a string.

public class ReverseString {    public static String reverse(String input) {        if (input == null) {            throw new IllegalArgumentException("Input string is null.");        }        StringBuilder reversed = new StringBuilder();        for (int i = input.length() - 1; i >= 0; i--) {            reversed.append(input.charAt(i));        }        return reversed.toString();    }    public static void main(String[] args) {        String original = "Hello, World!";        String reversedString = reverse(original);        System.out.println("Reversed string: " + reversedString);    } }

In this example, the reverse method takes an input string and builds a reversed version of it using a StringBuilder .

Time and Space Complexity Analysis

When solving coding exercises, it's essential to analyze the time and space complexity of your solutions.

  • Time Complexity: Assess how the runtime of your algorithm scales with input size (e.g., O(n), O(n^2), etc.).
  • Space Complexity: Evaluate the amount of memory your algorithm uses relative to the input size.

By understanding these complexities, you can optimize your code and choose the most efficient solutions for different scenarios.

As you tackle more coding exercises and analyze their complexities, you'll become better equipped to solve challenging Java interview questions.

How to Ace Tricky Java Interviews?

Congratulations on mastering the core Java concepts, exploring advanced topics, and honing your coding skills! Now, let's focus on essential tips and strategies to ensure you shine in those tricky Java interviews.

Interview Strategies

Interview success isn't just about what you know; it's also about how you present yourself and approach the interview.

Pre-Interview Preparation

  • Research the Company: Understand the company's products, culture, and values.
  • Review Your Resume: Be ready to discuss your past experiences and projects.
  • Know Your Strengths and Weaknesses: Prepare to highlight your strengths and show how you've worked on your weaknesses.

During the Interview

  • Active Listening: Pay close attention to the interviewer's questions and instructions.
  • Ask Clarifying Questions: If a question is unclear, don't hesitate to seek clarification.
  • Think Aloud: When solving problems, share your thought process with the interviewer.
  • Stay Calm: If you encounter a challenging question, stay composed and don't rush.
  • Time Management: Allocate your time wisely to ensure you address all parts of the interview.

Communication Skills

Effective communication is vital during interviews to convey your ideas clearly and confidently.

Clear Communication

  • Use Simple Language: Avoid jargon and use plain, understandable language.
  • Structure Your Answers: Organize your responses logically with clear introductions and conclusions.
  • Avoid Rambling: Be concise and to the point.

Asking Questions

  • Prepare Questions: Have insightful questions ready to ask the interviewer.
  • Show Interest: Ask questions that demonstrate your genuine interest in the role and company.

Handling Behavioral Questions

Behavioral questions assess your past experiences and how you've handled specific situations.

STAR Technique

  • Situation: Describe the context and situation you faced.
  • Task: Explain the task or challenge you had to address.
  • Action: Detail the actions you took to resolve the issue.
  • Result: Summarize the positive outcome and what you learned.

Answering Ethical Dilemmas

Prepare for ethical and moral questions by considering your values and ethical principles. Be honest and transparent about how you would handle such situations.

Handling Whiteboard Coding

Whiteboard coding can be daunting, but with practice and the right approach, you can excel.

  • Understand the Problem: Clarify the problem statement with the interviewer.
  • Pseudocode: Outline your solution before writing actual code.
  • Discuss Complexity: Mention the time and space complexity of your solution.
  • Practice: Practice whiteboard coding regularly to build confidence.

Post-Interview Follow-Up

Don't forget the importance of post-interview etiquette.

Thank-You Notes

  • Send a Thank-You Email: Express your gratitude for the interview opportunity.
  • Reiterate Your Interest: Reiterate your enthusiasm for the role and the company.

Feedback Request

  • Ask for Feedback: Politely request feedback on your interview performance.
  • Learn and Improve: Use feedback to enhance your skills for future interviews.

By following these tips and strategies, you'll not only demonstrate your technical prowess but also showcase your professionalism and interpersonal skills, setting you on the path to success in your tricky Java interviews.

Navigating tricky Java interview questions is a journey that demands preparation, practice, and a passion for learning. By mastering core Java concepts, embracing advanced topics, and honing your coding skills, you've equipped yourself with the tools needed to excel in challenging interviews.

Remember, interview success isn't just about what you know—it's about how you present yourself, communicate effectively, and handle pressure. With the right strategies and a commitment to continuous improvement, you're well-prepared to tackle any tricky Java interview that comes your way.

You may also like

Top 50 Paraprofessional Interview Questions and Answers

Top 50 Paraprofessional Interview Questions and Answers

Top 50 Bank Teller Interview Questions and Answers

Top 50 Bank Teller Interview Questions and Answers

Top 50 Docker Interview Questions and Answers

Top 50 Docker Interview Questions and Answers

Unlock the next level of your recruiting workflows, download "top 50 tricky java interview questions ".

Javatpoint Logo

All Interview

Company interview, technical interview, web interview, php interview, .net interview, java interview, database interview.



are those questions that require some extra efforts to solve the questions. If we try to answer a with common sense, we will fail because they require some specific knowledge. Most of the tricky Java questions come from confusing concepts like loop, multithreading, overloading, overriding, etc.

Sometimes we get puzzled in solving the questions while the question is not much difficult. Sometimes we write code in haphazard way while the solution to the question is very easy.

We can solve the question by using our analytical thinking even if we do not know the answer. In this section, we will cover some and .

1) Consider the following code and guess the output.

b

As we see the print statement it seems that the statement is commented but not so. // \u000d is a new line Unicode character.

a

In the program, the operators are just for puzzle someone. The operators are neither pre or post increment. The statement can be written and solved as follows:

int i=20+ (+9)- (-12)+ (+4)- (-13)+ (+19);

i=20+9+12+4+13+19

i=77

c

Because String literals are used from the string pool. It means that s1 and s2 refer to the same object and are equal. Therefore, the first two print statements print . The third print statement prints because the toString() method uses a method to compute the value and it is not from the string pool. The final print statement again prints because equals() looks at the values of String objects.

d

Because the code starts running and prints a and b on lines 13 and 15. Line 16 throws an exception, which is caught on line 17. After line 18 prints c, the finally block is run and d is printed. Then the try statement ends and e is printed on line 22.

e

The local variables require assignment before referencing them. Option E is incorrect because class and instance variables have default values and allow referencing. a_b defaults to a null value. Options A, B, C, and D are incorrect because identifiers may begin with a letter, underscore, or dollar sign. If a_b was an instance variable, the code would compile and output 0null.

b

The array is allowed to use an anonymous initializer because it is in the same line as the declaration. The ArrayList uses the diamond operator allowed since Java 7. It specifies the type matches the one on the left without having to re-type it. After adding the two elements, list contains [6, 8]. We replace the element at index 1 with 9, resulting in [6, 9]. Finally, we remove the element at index 0, leaving [9]. Option C is incorrect because arrays output something like that rather than an ArrayList.

e

The Unicode declaration must be enclosed in single quotes: '\u004e'.

c

Because Java does not allow us to compare values in the case statements. An error occurred due to invalid switch statement is called Orphaned case error.

e

Because the number defined is of type string, so they will not add together. Hence, the above code prints the same string as it is.

b

In the Integer class, the MIN_VALUE is negative (i.e. -2 ), both the MAX_VALUE and MIN_VALUE of the Double class are positive numbers. The Double.MIN_VALUE is 2 , a double constant whose magnitude is the least among all double values.

So, unlike the noticeable answer, this program will print 0.0 because of Double.MIN_VALUE is greater than 0.

a

The calculation is simple. First statement having L at last that denotes the exact explicitly long value i.e. 31536000000. On the other hand, the second statement does not have L at last, so it gives a different value as a result. Because it treated as integer and evaluates result in integer. But the result goes beyond the boundary of the integer range. Hence, it starts truncating the value i.e. 1726327040. Therefore, the purpose of L is that it explicitly denotes the long value.

b

We know that the static block executed first. Therefore, the post decrement value of x will be 1111 and the pre decrement value will be 1109 and the difference between the values is 2 and the same will print on the console. Note that the block after the static block will never get executed.

d

In the above program, the switch statement makes a random choice among three possible alternatives. Recall that the value of the expression is one of the integers 0, 1, or 2, selected at random with equal probability, so the switch statement below will assign one of the values "Rock", "Scissors", "Paper" to computerMove, with probability 1/3 for each case. Although the switch statement in this example is correct, this code segment as a whole illustrates a subtle .

We probably haven't spotted the error, since it's not an error from a human point of view. The computer reports the last line to be an error, because the variable computerMove might not have been assigned a value. In Java, it is only legal to use the value of a variable if a value has already been definitely assigned to that variable. It means that the computer must be able to prove, just from looking at the code when the program is compiled, that the variable must have been assigned a value. Unfortunately, the computer only has a few simple rules that it can apply to make the determination. In this case, it sees a switch statement in which the type of expression is int and in which the cases that are covered are 0, 1, and 2. For other values of the expression, computerMove is never assigned a value. So, the computer thinks computerMove might still be undefined after the switch statement. Now, in fact, this isn't true: 0, 1, and 2 are actually the only possible values of the expression (int)(3*Math.random()), but the computer is not smart enough to figure that out. The easiest way to fix the problem is to replace the case label case 2 with default.

The computer can see that a value is assigned to computerMove in all cases. More generally, we say that a value has been definitely assigned to a variable at a given point in a program if every execution path leading from the declaration of the variable to that point in the code includes an assignment to the variable. This rule takes into account loops and if statements as well as switch statements.

d

The program will compile and run successfully. Does not matter the Test class is empty.

a

brace creates a new Class. These inner classes are capable of accessing the behavior of their parent class. So, in our case, we are actually creating a subclass of HashSet class, so this inner class is capable of using put() method.

And set of braces are nothing but . Recall the concept of core Java where we can easily associate instance initializer blocks with static initializers due to similar brace like struct. Only difference is that static initializer is added with static keyword, and is run only once; no matter how many objects we create.

i. for( ; ; )
ii. for( ; true; )
iii. for( ; false; )
iv. for( ; 2==2; )
v. for(int i=1; i>=1; i++)

d

The loops and runs infinitely because the first for loop by default picks true value at condition place, the second for loop specifies that the condition is true, the fourth for loop compares the values and returns true, the fifth for loop also returns true at each iteration. Therefore, the for loop and runs infinitely.

a

If a Java program have both static blocks and main() method, in such a case all the static block will execute first then the main() method. Therefore, option A is correct.

d

The String.split() method splits the string with the specified delimiter (|). The following statement also does the same.

e

By Calling System.exit(0) in try or catch block, we can skip the finally block. System.exit(int) method can throw a SecurityException.

If System.exit(0) exits the JVM without throwing the exception then finally block will not execute. But, if System.exit(0) does throw SecurityException then finally block will be executed.

b

ArrayStoreException is a runtime exception. Array must contain the same data type elements. It exception is thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. In other words, if you want to store the integer Object in an Array of String you will get ArrayStoreException.

You may also like:

  • Java Interview Questions
  • SQL Interview Questions
  • Python Interview Questions
  • JavaScript Interview Questions
  • Angular Interview Questions
  • Selenium Interview Questions
  • Spring Boot Interview Questions
  • HR Interview Questions
  • C Programming Interview Questions
  • C++ Interview Questions
  • Data Structure Interview Questions
  • DBMS Interview Questions
  • HTML Interview Questions
  • IAS Interview Questions
  • Manual Testing Interview Questions
  • OOPs Interview Questions
  • .Net Interview Questions
  • C# Interview Questions
  • ReactJS Interview Questions
  • Networking Interview Questions
  • PHP Interview Questions
  • CSS Interview Questions
  • Node.js Interview Questions
  • Spring Interview Questions
  • Hibernate Interview Questions
  • AWS Interview Questions
  • Accounting Interview Questions

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence Tutorial

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking Tutorial

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering Tutorial

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

15 tricky Java interview questions and answers

tricky problem solving interview questions in java

Hiring the right Java developer is crucial for your business. A bad hire can lead to inefficient code, missed deadlines, and poor team dynamics. That’s why it’s essential to vet every candidate thoroughly before you bring them on board. Part of that process is asking the right questions when interviewing your Java developer candidates.

With our list of 15 tricky Java interview questions, you can assess your applicants’ theoretical knowledge, practical skills, and ability to think quickly and creatively. Coupling these questions with a Java skills test will ensure you select the best talent for your team.

Table of contents

What are tricky java interview questions, why include tricky java questions in your interviews, how to add tricky java interview questions to your hiring campaign, how testgorilla can help you find the best java developers.

Java is a widely used programming language known for its object-oriented programming (OOP) capabilities. It’s instrumental in creating web applications, mobile apps, and software tools. 

When we talk about “tricky” Java interview questions, we’re referring to queries that delve deeper into the Java language – questions designed to evaluate a candidate’s understanding of Java’s concepts and principles. 

Compared to regular Java interview questions, tricky questions go beyond basic syntax and principles. They aim to assess candidates’ ability to solve complex problems, implement intricate designs, and use Java’s advanced features. 

These questions are meant to be answered in an interview setting, as they require candidates to explain concepts or outline code structure rather than write lines of code. Detailed coding tasks are better suited for Java skill tests, such as TestGorilla’s Java Data Structures and Java Debugging skill tests.

Incorporating tricky Java questions in your interview process allows you to identify candidates who can handle complex Java-based tasks. 

The value of these questions isn’t just in assessing technical knowledge, though. They also help you understand the candidate’s problem-solving abilities, communication skills, and approach under pressure. 

Below, we cover the key reasons why including challenging Java questions is a win for your hiring process.

Why include tricky java questions in your interviews graphic

Identify in-depth understanding and application of Java

Complex Java questions explore deeper layers of a candidate’s knowledge. By these questions, you can determine how well your applicants grasp advanced Java concepts and how they apply them in real-world scenarios. 

Candidates’ responses can indicate their ability to solve problems, think critically, and make decisions – all vital aspects of a Java developer role.

Evaluate thought processes

By asking tricky Java questions in interviews, you give candidates a chance to showcase their unique perspectives and ability to think on their feet. Their answers shed light on their thought processes – including how they approach a problem, the logic they follow, and the solutions they propose. These responses offer deep insights into their cognitive abilities.

Assess communication skills

Most Java developers need to communicate technical topics effectively to do their job. And in an interview setting, candidates’ ability to articulate their thoughts is tested as much as their technical prowess. 

Tricky Java questions take this further by requiring candidates to express complex ideas clearly and succinctly. You get to observe how well they communicate intricate concepts, which is essential for team collaboration.

Create a more thorough evaluation process

Complex Java questions can bring an extra dimension to your interview process, complementing the information you get from resume screening and Java tests . While skill tests accurately assess a candidate’s coding capabilities, tricky interview questions enable candidates to demonstrate their knowledge verbally. This allows for a more well-rounded evaluation of each applicant.

Overall, including tricky Java questions in your interview process helps you identify top candidates who truly understand and can apply Java’s advanced principles. Along with skill tests, personality tests, and behavioral interview questions, these questions provide a robust and comprehensive evaluation system, helping you make the best hiring decisions for your business.

Listed below are 15 tricky Java questions you can use in your interviews. We’ve provided examples of solid, thoughtful replies to each question – but there’s often more than one “correct” answer. Candidates might offer equally valid yet different responses. 

1. What is the Java Memory Model, and how does it support multi-threaded applications?

The Java Memory Model (JMM) is an abstraction of the underlying hardware’s memory architecture. It provides a framework for understanding how threads interact through memory. In the context of multi-threaded applications, the JMM provides guarantees about when changes made by one thread are visible to others.

JMM offers a set of rules that programs must follow to ensure consistent behavior in multi-threaded environments. It addresses the “happens before” relationship, which is the foundation of visibility and ordering guarantees. If one action happens before another, the memory effects of the first will be visible to the second.

2. Explain the differences between the synchronized keyword, Lock , and Semaphore for managing thread synchronization.

Synchronized is a keyword in Java that controls access to an object to prevent data inconsistencies due to concurrent access. It provides an implicit lock and release mechanism but no explicit methods to lock or unlock, giving the programmer less control.

The Lock interface in the java.util.concurrent.locks package provides more extensive operations than the implicit locking mechanism. It allows more flexible structuring and can be non-blocking, making it more resilient to deadlock situations.

A Semaphore controls access to a shared resource using permits. It’s used when the number of resources to access is fixed. It allows multiple threads to access a fixed set of resources in parallel.

3. What are the benefits and drawbacks of using Java’s Executor Framework over directly creating threads?

The Executor Framework simplifies managing and controlling threads. It comes with several benefits. It provides thread pooling, which helps to reduce the overhead of thread creation and destruction. It also offers convenient scheduling capabilities and lets you more finely control how tasks are executed.

However, there are some drawbacks. The Executor Framework introduces an additional layer of abstraction, which can make it more complex. Also, a thread pool can cause resource exhaustion if not correctly configured.

4. Describe the concept of Java NIO (New I/O) and compare it with traditional I/O (java.io)

Java NIO (New I/O) is an alternative I/O API introduced in Java 1.4. It provides non-blocking I/O capabilities, allowing a thread to handle multiple input and output channels simultaneously. This leads to more efficient use of threads and can improve the performance of I/O-intensive applications.

In contrast, the traditional I/O API (java.io) is blocking. This means that when a thread invokes a read or write operation, it gets blocked until the operation is completed.

Furthermore, NIO provides additional features unavailable in java.io, such as file system notifications, scalable network sockets, and character set encoders and decoders. But NIO is generally more complex to use than java.io.

5. How do you handle concurrent modifications to a collection using the ConcurrentHashMap and CopyOnWriteArrayList ?

Both ConcurrentHashMap and CopyOnWriteArrayList are designed for multithreaded environments and are part of the java.util.concurrent package.

ConcurrentHashMap allows high concurrency for updates (via segment locking) and retrieval operations. Iterators of this class reflect the state of the map at the time they were created, so they don’t throw ConcurrentModificationException . It’s particularly useful when you need a thread-safe map where reads are more common than writes.

CopyOnWriteArrayList uses a different approach. Any modification operation (add, set, remove, etc.) on this list results in a new copy of the underlying array, while read operations work on the existing copy. This approach eliminates the need for locking for reads, making CopyOnWriteArrayList excellent when iteration is a more common operation than modification.

6. What are CompletableFutures in Java, and how do they enable asynchronous programming?

CompletableFuture is a Future that may be explicitly completed by setting its value and status. It’s part of the java.util.concurrent package and supports asynchronous programming in Java.

CompletableFuture offers a variety of methods to handle the results of asynchronous computations. You can chain together multiple asynchronous operations, handle exceptions, combine results, or run additional tasks when the computation completes.

By allowing you to write non-blocking code, CompletableFuture makes it possible to maximize the usage of computational resources. It makes it possible to perform other tasks instead of waiting for a long-running operation to complete.

7. Explain the different types of garbage collectors available in the JVM and their use cases (e.g., G1, CMS, Parallel).

The JVM comes with several garbage collectors, each designed for specific use cases:

Serial Garbage Collector. This collector is single-threaded and best suited for simple, single-processor machines. It’s designed for small applications with low memory footprints.

Parallel Garbage Collector (Throughput Collector). This collector uses multiple threads for garbage collection, making it suitable for medium to large-sized data sets in multiprocessor environments. It aims to maximize throughput by minimizing the time spent in garbage collection.

Concurrent Mark Sweep (CMS) Collector. The CMS collector aims to minimize application pauses by doing most of its work concurrently with the standard application threads. It’s best suited for responsive applications that can’t tolerate long garbage collection pauses.

Garbage-First (G1) Collector. The G1 collector is designed for applications running on multiprocessor machines with large memories. It aims to provide high throughput and predictable pause times by dividing the heap into regions and prioritizing garbage collection in the regions that contain the most garbage.

Each garbage collector has its trade-offs, and the best choice depends on the specific needs of your application.

8. How can you achieve high-performance serialization and deserialization in Java, considering various formats (JSON, XML, Protocol Buffers)?

To achieve high-performance serialization and deserialization in Java, you can use various libraries and techniques depending on the data format.

For JSON, popular libraries include Jackson and Gson. These provide comprehensive APIs to convert objects to JSON and vice versa. Jackson is generally faster and has a smaller memory footprint than Gson.

For XML, JAXB is a standard Java API for object/XML mapping and provides mechanisms for efficient serialization and deserialization.

Protocol Buffers (protobuf), a binary protocol developed by Google, allows faster serialization/deserialization than JSON and XML. It also results in smaller payloads. For Java, protobuf provides an API to generate Java classes from a .proto file, which you can use for serialization and deserialization.

In all cases, custom serializers and deserializers can improve performance, as you can optimize them according to the specific application’s needs.

9. What is the Java Flight Recorder (JFR), and how can it be used to monitor and diagnose Java applications?

Java Flight Recorder (JFR) is a tool integrated into the Java Virtual Machine (JVM) for collecting diagnostic and profiling data about a running Java application. It has a minimal performance overhead, making it safe to use in production environments.

JFR can capture many event types covering areas like CPU usage, memory management, network usage, I/O, garbage collection, Java exceptions, and more. It’s a valuable tool for understanding the behavior of your Java application and the underlying JVM.

The collected data can be analyzed with the Java Mission Control (JMC) tool, providing a graphical interface with detailed metrics and diagnostics. Therefore, JFR helps you identify performance bottlenecks and memory leaks.

10. Describe the principles of the Dependency Injection design pattern and how it can be implemented using frameworks like Spring.

Dependency Injection (DI) is a design pattern where an object’s dependencies are injected by an external entity instead of the object creating them itself. This promotes loose coupling, enhances testability, and enables better separation of concerns.

DI has three types: constructor injection, setter injection, and field injection.

In constructor injection , dependencies are provided through the class constructor. 

Setter injection involves providing the dependency using a setter method. 

Field injection injects dependencies directly into the fields.

The Spring framework provides comprehensive support for implementing DI. In Spring, the ApplicationContext is the container that provides DI features.

You define your beans and their dependencies in a configuration file (XML, Java Config, or Annotation-based). Spring’s container then creates these beans, resolves their dependencies, and provides the right beans when needed. The @Autowired annotation is often used to wire beans automatically.

Spring’s DI helps in building flexible, reusable, and testable Java applications.

Question 11

How does the Stream API in Java 8 handle parallelism, and what considerations should you consider when using it?

The Stream API in Java 8 can facilitate parallel execution of operations. By invoking the parallelStream() method instead of stream() on a collection, you can create a stream that processes elements in parallel.

Underneath, the Stream API uses the Fork/Join Framework to divide tasks into smaller subtasks and assign them to different threads. It uses the common ForkJoinPool , which by default has as many threads as you have processors, as defined by Runtime.getRuntime().availableProcessors() .

However, you must consider several factors when using it. Parallel streams work best when: 

Your data is large enough . Smaller data sets may not benefit much from parallelism and might even suffer due to overhead. 

Your tasks are CPU-intensive. If they’re I/O bound, parallelism might not improve performance.

Your operations are independent. Ensure your lambda functions don’t have a shared mutable state to avoid thread-safety issues.

12. Discuss the pros and cons of using the ThreadLocal class in Java for managing thread-local variables

ThreadLocal in Java provides a way to create variables that can only be read and written by the same thread. This encapsulation makes having per-thread singleton instances and per-thread context information easy.

Pros include:

Thread safety. Since each thread has its own instance, it doesn’t need synchronization.

Performance. It can lead to more efficient code by reducing the overhead of synchronization.

Cons include:

Memory leaks. If you don’t remove a ThreadLocal key from its ThreadLocalMap , it could potentially lead to memory leaks, especially in thread pool scenarios. 

Misuse. You should use ThreadLocal sparingly, as it can make the code harder to reason about and maintain.

It’s important to use ThreadLocal responsibly and clean up any set variables when they’re no longer needed.

13. How can you implement a custom ClassLoader in Java, and what are the potential use cases?

To implement a custom ClassLoader in Java, you typically extend the ClassLoader class and override the findClass() method. This method is called after the parent ClassLoader fails to find the class in its classpath.

The key steps typically include the following: 

Convert the binary name of the class to a file name. 

Read that file into a byte array. 

Call defineClass() to convert the byte array into a Class object.

Use cases for a custom ClassLoader could include:

Loading classes dynamically from sources other than the classpath, such as a network location or a database.

Implementing hot-swapping of classes in a running JVM.

Isolating or sandboxing specific parts of an application by controlling class loading behavior.

Creating a custom ClassLoader should be done with caution due to the complexity involved.

14. Describe the java.lang.instrument package and how it enables bytecode manipulation in Java.

The java.lang.instrument package provides services that enable Java programming language agents to instrument programs running on the JVM. It allows an agent (in the form of a JAR file) to transform the bytecode of classes loaded by the JVM at runtime.

The key class in the package is Instrumentation, which provides methods to retransform classes and query class status. An agent receives an instance of Instrumentation in its premain or agentmain methods.

The instrument package is primarily used for profiling, monitoring, and logging purposes. For instance, you can use it to measure the execution time of a method, monitor memory usage, or add additional logging for debugging purposes.

15. What is Double-Checked Locking, and why is it considered an anti-pattern for implementing Singleton in multi-threaded environments?

Double-Checked Locking is an idiom that reduces synchronization overhead when implementing Singleton classes in a multithreaded environment. In this pattern, the Singleton instance is checked twice before it’s initialized – once without synchronization (first check) and once with synchronization (second check).

The problem with Double-Checked Locking in Java arises due to the Java Memory Model. Without the proper use of the volatile keyword, there’s a risk that the Singleton instance will not be seen as fully initialized by all threads. 

This is because the Java compiler is allowed to reorder instructions, meaning that the Singleton instance could be set before it’s fully initialized. Consequently, another thread could see it as not null and use it before it’s fully initialized, leading to unpredictable results.

Complex Java interview questions can provide a better understanding of a candidate's technical competency. But they shouldn’t be the only tool you rely on when evaluating potential hires. 

It’s best to use them as part of a comprehensive screening process that also considers applicants’ problem-solving skills, critical thinking, teamwork, and cultural fit. 

This is where a pre-employment testing platform like TestGorilla can be highly beneficial.

With TestGorilla, you can access a range of scientifically validated tests tailored for assessing tech professionals, including Java coding tests . These tests allow you to objectively measure a candidate’s proficiency in Java and other related technical areas.

However, TestGorilla’s capabilities extend far beyond technical testing. Our platform also includes personality tests like the DISC Personality and Big 5 (OCEAN) Personality tests. These can help you assess if a candidate’s temperament and working style are compatible with your team’s culture and dynamics.

Additionally, you can add custom questions to your assessment to cover specific areas relevant to your business. For instance, you can include problem-solving questions to evaluate a candidate’s logical thinking and creativity and behavioral questions to uncover their teamwork and conflict resolution approach.

Another unique feature of TestGorilla is the one-way interview system . This allows candidates to respond to your preset interview prompts at their convenience, and you can review their responses whenever it suits you. This approach offers greater flexibility to both you and the candidate while also standardizing the interview process to ensure fairness.

Combining tech skill tests with behavioral and personality assessments gives you a complete picture of each candidate’s skills, personality, and potential fit within your team. You can make better hiring decisions and avoid bias along the way.

Tricky Java interview questions are vital in assessing your Java developer candidates’ technical competency. However, you should also use them as part of a holistic assessment approach covering soft skills, cognitive abilities, and cultural fit. Pairing these elements ensures you have a comprehensive view of each candidate’s strengths and areas for development.

TestGorilla provides an extensive library of tests, customizable assessments, and one-way interview tools to help you do just that. To get hands-on experience with our platform and its features, sign up for your free TestGorilla plan account today.

Related posts

tricky problem solving interview questions in java

TestGorilla vs. Equalture

tricky problem solving interview questions in java

TestGorilla vs. Glider AI

Why is the federal government prioritizing skills-based hiring featured image

Why is the federal government prioritizing skills-based hiring?

Hire the best candidates with TestGorilla

Create pre-employment assessments in minutes to screen candidates, save time, and hire the best talent.

tricky problem solving interview questions in java

Latest posts

tricky problem solving interview questions in java

The best advice in pre-employment testing, in your inbox.

No spam. Unsubscribe at any time.

Hire the best. No bias. No stress.

Our screening tests identify the best candidates and make your hiring decisions faster, easier, and bias-free.

Free resources

tricky problem solving interview questions in java

This checklist covers key features you should look for when choosing a skills testing platform

tricky problem solving interview questions in java

This resource will help you develop an onboarding checklist for new hires.

tricky problem solving interview questions in java

How to assess your candidates' attention to detail.

tricky problem solving interview questions in java

Learn how to get human resources certified through HRCI or SHRM.

tricky problem solving interview questions in java

Learn how you can improve the level of talent at your company.

tricky problem solving interview questions in java

Learn how CapitalT reduced hiring bias with online skills assessments.

tricky problem solving interview questions in java

Learn how to make the resume process more efficient and more effective.

Recruiting metrics

Improve your hiring strategy with these 7 critical recruitment metrics.

tricky problem solving interview questions in java

Learn how Sukhi decreased time spent reviewing resumes by 83%!

tricky problem solving interview questions in java

Hire more efficiently with these hacks that 99% of recruiters aren't using.

tricky problem solving interview questions in java

Make a business case for diversity and inclusion initiatives with this data.

The Talent500 Blog

16 Tricky Java Developer Interview Questions And How to Answer Them

Mahidhar S K

Java is one of the most famous programming languages owing to its platform independence. Its functions around a ‘write once, run anywhere’ philosophy and is useful for companies looking to write code for Windows, macOS, smartphones, and Linux alike. Skilled Java developers are much sought after and while entry-level Java developers earn about Rs.2.7 lakh per annum, those with 1-4 years’ experience earn about Rs.4.1 lakh annually and those with 5-9 years of experience earn an annual compensation of about Rs.8.3 lakh as per data by PayScale.

16 Tricky Java Developer Interview Questions And How to Answer Them 2

Analytical thinking is key to scaling the rungs and so, interviewers frequently ask tough and tricky questions to test your understanding of basic concepts. To help you prepare for your next Java interview , here is a list of 16 tricky Java questions and their answers that both entry level and experienced Java developers should master.

1. What is Liskov Substitution Principle?

Liskov’s Substitution Principle prescribes that you can replace an object with an instance of its subtype without corrupting the program. Practically, you can replace a class with its subclass and Java’s inheritance mechanism follows this principle.

2. Distinguish between JDK and JRE

Java Runtime Environment (JRE) provides the requirements for Java programs to be executed and contains the JVM, Java class libraries and Java class loader. Conversely, the Java Development Kit (JDK) is a Software Development Kit , allowing one to develop, compile and execute applications and applets with Java. It includes the JRE and tools like JavaDoc and Java Debugger.

3. In OOP, how does abstraction differ from encapsulation?

While abstraction focuses on an object’s behavior, encapsulation focuses on the implementation of an object’s behavior. Abstraction hides unwanted information whereas encapsulation hides the data into a single unit, protecting the information from outside influence.

4. Why does Java not support multiple inheritances?

With multiple inheritances, one can run into the ‘diamond of death problem’. Here ambiguity arises when classes B and C inherit from class A; and class D inherits from B and C. This can lead to compiler errors and since Java was designed to be simple , multiple inheritances are not supported.

5. Will finally block execute if you put System.exit () in catch or try block?

The finally block will not execute and after System.exit () the program will be terminated. In other words, the finally block will be bypassed if there is no catch on the way to exit. The exception here is when a block that catches exceptions prompts the finally block to get executed.

6. How can you ensure that N threads can access N resources without deadlock?

Firstly, impose an ordering on the locks. Then, force the threads to keep to that ordering. Zero deadlocks will arise if the threads lock and unlock the mutexes in the same order. In other words, one must acquire resources in one order and release them in the reverse order.

7. Is Java pass-by-reference or pass-by-value?

In Java one can pass a parameter by value only; pass-by-reference does not exit. So, Java follows pass-by-value, even though in passing an object’s value one passes the reference to it.

You may also like to read: 4 great tips to stand out in a coding interview

8. What’s the difference between fail-fast and fail-safe ?

Fail-fast iterators throw an exception when they detect that the collection is modified structurally since the start of the iteration. Fail-safe iterators do not throw an exception; here, the iterator works with a clone of the collection and is not affected by modifications to it. 

9. Can you store null keys/ values and duplicate keys/values in a Java HashMap?

One can store only 1 null key (bucket 0) and multiple null values in a Java HashMap. The HashMap, does not allow for duplicate keys but duplicate values are permitted.

10. What do System.gc() and Runtime.gc() methods do?

These suggest to JVM that garbage collection can be started; however, the JVM may finally run the garbage collector at a later time. System.gc() is a class method and Runtime.gc() is an instance method. 

11. Distinguish between throw and throws in Java

The throw keyword is used within a method to raise an exception explicitly. This keyword is followed by an instance. The throws keyword declares an exception, precedes a class name, and works in a way that the try-catch block does. This keyword is used with the method signature.

12. Describe the lifecycle of an Applet

An applet’s lifecycle can be said to follow these states:

  • init(): The applet is initialized
  • start(): Execution begins
  • paint(): Applet redraws its output
  • stop(): Execution is stopped
  • destroy(): Final clean up before unloading is performed 

You must read : How To Become A Better Java Developer in 2023?

13. Why to use PreparedStatement over Statement?

PreparedStatement provides better performance and security. Performance is higher because of pre-compilation of the SQL query and security is more because wrong use of Statement keeps one susceptible to SQL injection.

14. What’s the difference between CountDownLatch and CyclicBarrier ?

In case of a CountDownLatch, a main thread waits for other threads to execute, until the latch counts down to zero. In case of a CyclicBarrier, a group of threads wait for each other to complete execution; once this is done, the barrier is broken, and action can be taken.

15. Can you override a private method in Java?

It is not possible to override a private method in Java as it is not visible to other classes. The scope of the private method is limited to its own class and if you try to override it you will get a compile time error. 

16. How to notice a memory leak in Java?

An OutOfMemoryError (OOM) is a sign of a memory leak. Further, if the application’s memory utilization is on the rise the data processing remains the same, one may be dealing with a memory leak. Similarly, performance problems with large data sets is indicative of a memory leak. Tools like Java VisualVM help one analyze code and identify memory leaks.

These 16 questions cover topics ranging from OOP, Java threads, and garbage collectors to exception handling and JDBC. While this is sure to serve as a quick primer to tricky topics in Java, make sure to look up some other challenging Java questions and their solutions so that you ace your interview and land a great developer job!

Related Articles

Essential Skills to Become an Ace Java Developer

Tricky Java Interview questions and answers

Understanding Design Patterns in Java

Java developer toolkit: Important skills, learning resources, interview prep & more

Most Popular Articles

How to Bundle JavaScript With Rollup

Top 5 Java Microservices Frameworks Architecture

How To Advance In Blockchain As A Java Developer

Our Other Articles

Software Engineer Career Path [2023 Career Guide]

What is the future of manual testing?

Ace your next coding interview with these 5 books

Mahidhar S K

Mahidhar S K

Full-stack developer at Talent500. A thorough polyglot programmer, passionate about systems design & efficiency. Loves metal and plays the electric guitar.

Add comment

Cancel reply.

Save my name, email, and website in this browser for the next time I comment.

You may also like

unit testing

Unleashing the Power of Unit Testing: Reliable Code at Your Fingertips

In the world of software development, making sure of code quality and reliability is important. Keeping that in mind, one of the most effective ways to ensure your code is bug-free is through unit testing.  Unit testing...

Afreen Khalfe

Building Data Pipelines for Multi-Cloud Environments: Challenges and Solutions

In the contemporary digital era, the proliferation of data across various sectors has necessitated the development of sophisticated data management and processing strategies. Among these, the concept of multi-cloud data...

backend

Backend Optimization Strategies: Tips for Enhancing Performance and Efficiency

As programmers, we continuously seek to develop software programs that not only provide the desired functionality, but also run optimally. However, in the current landscape of web and application development, along with...

Sumit Malviya

  • Agile & Project Management
  • Automation Testing
  • cyber security
  • data science
  • data architecture
  • data engineering
  • Diversity & inclusion
  • Java + React
  • Node + React
  • general tech
  • Human Resources Management
  • Information Security
  • IT Infra and Networking
  • Job Interview Guides
  • Manual Testing
  • Workplace Communication
  • Remote Working
  • Software Engineering
  • Artificial Intelligence
  • Augmented Reality
  • Data Analytics
  • Developer Guides
  • Java Developer Guides
  • Virtual Reality

Recent Posts

  • API Gateway Vs Service Mesh: Practical Differences For DevOps Pros
  • Data Science Integration in Full-Stack Applications: Utilizing Machine Learning Models for Intelligent Decision-Making
  • What is Telemetry in DevOps?

tricky problem solving interview questions in java

Talent500 helps the world’s fastest growing businesses build their global workforce.

We help companies hire, build and manage global teams. We are trusted by industry leaders across the globe – from Fortune 500s and larger enterprises, to some of the world’s fastest-growing startups. We are backed by Accel Partners & ANSR, a global leader and enterprise transformation platform.

Discover jobs

Enterprise blog

Professionals blog

Terms of use

Privacy policy

All rights reserved by Talent500 © 2024.

  • Python + React
  • Angular + Node
  • Data Science

Better resumes & cover letters

AI Resume Builder

Resume Checker

AI Cover Letters

Resume Summary Generator

Resume Bullet Generator

Resume Skills Generator

Tailor your resume to jobs

Job Tailored Resumes

Resume Keyword Scanner

Job Keyword Finder

Organize your search

Job Tracker

Contact Tracker

Interview Tracker

Job Search Metrics

Speed up your search

Job Application Autofill

Chrome Extension

  • For Organizations
  • University Career Centers
  • Career Coaches
  • Workforce Development
  • Outplacement
  • Affiliate Program

huntr logo

Targeted Resume

Beautiful, perfectly job-tailored resumes designed to make you stand out, built 10x faster with the power of AI.

  • For Organizations University Career Centers Career Coaches Bootcamps Workforce Development Outplacement Affiliate Program
  • Sign up for free

Interview Questions

50 Interview Questions About Java (With Answers)

Java skills are highly sought after. Here are 50 interview questions about Java.

June 08, 2024

Java is a key programming language that allows developers to create amazing applications. This post will include 50 interview questions about java so that developers can take some time to practice these questions ahead of a job interview. It also highlights why java is important in the workplace.

Faster job search. More Offers. Use our AI Cover Letter Builder, Interview Prep and Job Search Tools to land your next job.

What is Java?

Java is a versatile and powerful programming language that enables developers to create robust, high-performance applications for a wide range of platforms. From mobile devices and desktop computers to large-scale enterprise systems and the Internet of Things (IoT), Java's portability, object-oriented structure, and security features make it an ideal choice for developers. Its syntax is designed to be easy to read and write, reducing the complexity of coding and making it accessible for beginners, yet sophisticated enough for seasoned professionals. As a foundational skill in the field of software development, understanding Java opens the door to a myriad of career opportunities and technological innovations.

java

Why is Java important in the workplace?

1. enhanced problem-solving abilities.

Java, as a programming language, is known for its complexity and versatility. Professionals skilled in Java possess enhanced problem-solving abilities, as they are trained to think logically and analytically. This skill is invaluable in the workplace, as it allows for the efficient tackling of complex tasks and challenges, leading to innovative solutions and improvements in processes and products.

2. Cross-Platform Development

One of Java's most significant advantages is its portability across different platforms without the need for special adaptations. This means that Java developers can create applications that run seamlessly on any operating system, increasing the utility and reach of business applications. In today's diverse technological landscape, the ability to develop cross-platform solutions is crucial for meeting varied customer needs and staying competitive.

3. Scalability and Performance

Java's robustness and efficiency make it an ideal choice for building large-scale, high-performance applications. Skills in Java enable professionals to create scalable solutions that can handle growing amounts of data and an increasing number of users without compromising on performance. This is particularly important in the workplace for businesses aiming to expand their operations and cater to a larger audience without facing technological limitations.

Tips for a Java-Based Interview

When preparing for a job interview that focuses on your Java skills, it's important to not only showcase your technical expertise but also to demonstrate how you've applied your knowledge in practical situations. Here are five tips to help you effectively answer skill-based interview questions on Java:

1. Understand Java Fundamentals Thoroughly

Before stepping into the interview room, ensure that your understanding of Java fundamentals is solid. Be prepared to discuss core concepts like object-oriented programming principles, exception handling, collections framework, multithreading, and concurrency. Interviewers often start with these basics to gauge your foundational knowledge.

2. Showcase Your Practical Experience

When answering questions, don't just focus on theoretical knowledge. Instead, highlight how you've applied Java in real-world projects. Discuss specific challenges you faced, how you addressed them using Java, and the outcomes of your efforts. This demonstrates your problem-solving skills and your ability to apply Java concepts effectively.

3. Stay Updated on Latest Java Features

Java is continuously evolving, with new versions bringing enhancements and new features. Familiarize yourself with the latest updates in Java, even if your practical experience is with an older version. This shows your commitment to staying current and your enthusiasm for the language.

4. Discuss Your Collaboration and Communication Skills

Technical skills are crucial, but so are soft skills. When discussing your Java projects, highlight how you collaborated with team members, communicated complex ideas effectively, and contributed to achieving team goals. This shows that you're not just a skilled developer but also a valuable team player.

5. Prepare for Coding Challenges

Be ready to write code during your interview. You might be asked to solve a problem on the spot to demonstrate your coding ability. Practice common Java coding problems beforehand and be familiar with using whiteboards or online coding platforms. Approach these challenges calmly, and explain your thought process as you code. This not only showcases your technical skills but also your problem-solving approach and ability to work under pressure.

java programming

1. Can you describe your experience with Java programming?

I have extensive experience in Java programming, having worked on various projects ranging from web applications to backend services. My experience includes developing, testing, and maintaining Java-based applications, leveraging frameworks such as Spring and Hibernate. I am proficient in writing clean, efficient code and utilizing Java’s object-oriented principles to create scalable and robust software solutions.

2. What is the difference between JDK, JRE, and JVM?

The JDK (Java Development Kit) is a software development kit used to develop Java applications. It includes the JRE (Java Runtime Environment) and development tools like the compiler (javac). The JRE is the runtime environment for executing Java applications and contains the JVM (Java Virtual Machine), which is responsible for converting Java bytecode into machine-specific code for execution.

3. Explain the concept of object-oriented programming in Java.

Object-oriented programming (OOP) in Java is a programming paradigm based on the concept of objects, which are instances of classes. OOP principles include encapsulation, inheritance, polymorphism, and abstraction. These principles help in organizing complex software systems by grouping related properties and behaviors into objects, promoting code reuse, and improving maintainability.

4. How does Java achieve platform independence?

Java achieves platform independence through the use of the JVM (Java Virtual Machine). Java source code is compiled into bytecode, which is platform-independent. The JVM interprets this bytecode and translates it into machine code specific to the operating system it is running on. This allows Java programs to run on any device with a compatible JVM.

5. Can you describe the difference between == and equals() in Java?

In Java, the == operator checks for reference equality, meaning it evaluates whether two references point to the same object in memory. The equals() method, on the other hand, is used to check for value equality, meaning it compares the actual data within the objects. The default implementation of equals() in the Object class is similar to ==, but it can be overridden to provide custom equality logic.

6. What is inheritance in Java? Can you give an example?

Inheritance in Java is a mechanism where one class (subclass) inherits the properties and behaviors (fields and methods) of another class (superclass). This promotes code reuse and establishes a natural hierarchy between classes. For instance, a class Dog can inherit from a class Animal, meaning Dog will have access to all the fields and methods defined in Animal, in addition to its own unique attributes.

7. Explain the use of the final keyword in Java.

The final keyword in Java can be used to define constants, prevent method overriding, and inheritance. When applied to a variable, it makes the variable’s value unchangeable. When used with methods, it prevents subclasses from overriding the method. When applied to a class, it prevents the class from being subclassed.

8. What is the difference between an abstract class and an interface?

An abstract class in Java can have both abstract methods (without implementation) and concrete methods (with implementation). It is used to represent an abstract concept and cannot be instantiated. An interface, however, can only have abstract methods (until Java 8, after which it can have default and static methods with implementation). Interfaces are used to define a contract that implementing classes must follow, promoting loose coupling.

9. Can you explain what a Java package is and its advantages?

A Java package is a namespace that organizes a set of related classes and interfaces. Packages help avoid name conflicts, provide access protection, and make it easier to locate and use classes. They also improve code maintainability by grouping logically related classes together.

10. Describe how exception handling works in Java.

Exception handling in Java is managed through the use of try, catch, and finally blocks. Code that might throw an exception is placed in a try block. Catch blocks are used to handle specific exceptions that occur within the try block. The finally block, if present, is executed regardless of whether an exception is thrown or not, allowing for cleanup actions.

11. What are the main differences between checked and unchecked exceptions?

Checked exceptions are exceptions that must be either caught or declared in the method signature using the throws keyword. They are checked at compile-time. Examples include IOException and SQLException. Unchecked exceptions, on the other hand, are not required to be declared or caught and are checked at runtime. Examples include NullPointerException and ArithmeticException.

12. Can you explain the concept of multithreading in Java?

Multithreading in Java is a process that allows multiple threads to run concurrently, enabling the execution of multiple tasks simultaneously. This improves the performance of applications, especially on multi-core systems. Java provides built-in support for multithreading through the java.lang.Thread class and the java.util.concurrent package.

13. How do you create a thread in Java?

In Java, you can create a thread by either extending the java.lang.Thread class and overriding its run() method or by implementing the java.lang.Runnable interface and passing an instance of it to a Thread object. The thread is then started using the start() method.

14. What is synchronization and why is it important in Java?

Synchronization in Java is a mechanism that ensures that multiple threads can access shared resources in a controlled manner to prevent data inconsistency and thread interference. It is achieved using the synchronized keyword, which can be applied to methods or blocks of code. This is crucial in concurrent programming to avoid race conditions and ensure thread safety.

15. Can you describe the Java memory model?

The Java memory model defines how threads interact through memory and what behaviors are allowed in concurrent execution. It specifies how variables are read and written, ensuring visibility and atomicity properties. The model includes the heap, where objects are stored, and stack memory, where method calls and local variables are stored. It also defines rules for synchronization and memory barriers to manage visibility and ordering of operations.

16. What is garbage collection in Java?

Garbage collection in Java is the process by which the JVM automatically identifies and frees memory occupied by objects that are no longer referenced by the application. This helps in managing memory efficiently and preventing memory leaks. The garbage collector runs in the background and reclaims memory, making it available for new object creation.

17. Explain the use of the static keyword in Java.

The static keyword in Java is used to denote that a member variable or method belongs to the class itself rather than to instances of the class. Static members can be accessed without creating an instance of the class. Static methods can only access other static members and cannot access instance variables or methods directly.

18. How does Java handle memory management?

Java handles memory management through a combination of stack and heap memory allocation and garbage collection. The JVM automatically manages the allocation and deallocation of memory, with stack memory used for method calls and local variables, and heap memory used for dynamically allocated objects. Garbage collection ensures that memory used by objects no longer in use is reclaimed.

19. Can you describe the Singleton design pattern and how to implement it in Java?

The Singleton design pattern ensures that a class has only one instance and provides a global point of access to that instance. This is useful for managing shared resources or configurations. It is implemented by creating a private constructor, a private static instance variable, and a public static method that returns the single instance, initializing it if it hasn't been already.

20. What is the Java Collections Framework?

The Java Collections Framework is a set of classes and interfaces that provide commonly used data structures and algorithms for manipulating collections of objects. It includes interfaces like List, Set, and Map, and classes like ArrayList, HashSet, and HashMap. The framework provides methods for inserting, deleting, and accessing elements, making it easier to manage groups of objects.

21. Explain the difference between ArrayList and LinkedList.

ArrayList and LinkedList are both implementations of the List interface in Java, but they have different underlying data structures and performance characteristics. ArrayList is backed by a dynamic array, which allows fast random access but slow insertions and deletions due to shifting elements. LinkedList, on the other hand, is a doubly-linked list, which allows fast insertions and deletions but slower random access due to traversal through nodes.

22. How do you sort an array in Java?

In Java, you can sort an array using the Arrays.sort() method, which is part of the java.util package. This method sorts the array in ascending order using a dual-pivot quicksort algorithm for primitives and a modified mergesort for objects, ensuring stability and performance.

23. What is a HashMap and how does it work?

A HashMap in Java is a part of the Collections Framework that implements the Map interface. It stores key-value pairs and allows for fast retrieval based on the key's hash code. HashMap uses a hash table to store the pairs and provides constant-time performance for basic operations like get and put, assuming a good hash function that distributes keys uniformly across the buckets.

24. Can you describe the differences between HashMap and Hashtable?

HashMap and Hashtable are both implementations of the Map interface, but they have key differences. HashMap is unsynchronized and allows null keys and values, making it faster and more flexible for non-thread-safe environments. Hashtable, on the other hand, is synchronized and does not allow null keys or values, making it thread-safe but slower compared to HashMap.

25. What are Java annotations and how are they used?

Java annotations are metadata that provide data about a program but are not part of the program itself. They can be applied to classes, methods, fields, and other elements. Annotations are used for various purposes such as marking deprecated methods, overriding methods, and providing instructions to the compiler or runtime. Custom annotations can also be created for specific use cases.

26. Can you explain the concept of Java generics?

Java generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. This allows for type-safe code, where the compiler can enforce type checks at compile-time, reducing runtime errors. Generics provide stronger type checks, eliminate casting, and enable code reuse for different data types while maintaining type safety.

27. What is the difference between List and Set in Java?

List and Set are both interfaces in the Java Collections Framework but serve different purposes. A List is an ordered collection that allows duplicate elements and provides positional access to elements. A Set is an unordered collection that does not allow duplicate elements and is typically used when the uniqueness of elements is a priority.

28. How do you handle file I/O operations in Java?

File I/O operations in Java are handled using classes from the java.io and java.nio packages. The java.io package includes classes like FileInputStream, FileOutputStream, FileReader, and FileWriter for basic file operations. The java.nio package provides more advanced and efficient I/O operations using channels, buffers, and file systems.

29. What is the purpose of the transient keyword in Java?

The transient keyword in Java is used to indicate that a field should not be serialized when an object is converted to a byte stream. This is useful for fields that are not part of the object's persistent state or that are derived from other fields and do not need to be stored.

30. Explain the concept of polymorphism in Java.

Polymorphism in Java is the ability of a single interface or method to represent different underlying forms (data types). It allows one interface to be used for a general class of actions. The specific action is determined by the exact nature of the situation. Polymorphism is achieved through method overriding (runtime polymorphism) and method overloading (compile-time polymorphism).

31. What is the difference between method overloading and method overriding?

Method overloading in Java occurs when two or more methods in the same class have the same name but different parameters. It is a compile-time polymorphism. Method overriding, on the other hand, occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. It is a runtime polymorphism.

32. How do you implement serialization in Java?

Serialization in Java is implemented by making a class implement the java.io.Serializable interface. This interface is a marker interface with no methods. To serialize an object, you use ObjectOutputStream to write the object's state to a byte stream. To deserialize, you use ObjectInputStream to read the byte stream and reconstruct the object.

33. Can you describe the difference between String, StringBuilder, and StringBuffer?

In Java, String is an immutable sequence of characters, meaning once created, it cannot be changed. StringBuilder and StringBuffer are mutable sequences of characters. StringBuilder is not synchronized and is faster, making it suitable for single-threaded environments. StringBuffer is synchronized and thread-safe, making it suitable for multi-threaded environments.

34. What is a lambda expression in Java?

A lambda expression in Java is a concise way to represent an anonymous function (a block of code with parameters). Introduced in Java 8, lambda expressions enable functional programming by allowing you to pass behavior as an argument to methods, making the code more readable and succinct. They are commonly used with functional interfaces and stream operations.

35. How do you create a custom exception in Java?

To create a custom exception in Java, you extend the Exception class (for checked exceptions) or the RuntimeException class (for unchecked exceptions). This involves defining a constructor that calls the superclass constructor and optionally adding custom methods and fields for additional functionality.

36. Can you explain the difference between public, protected, private, and default access modifiers?

In Java, access modifiers control the visibility of classes, methods, and fields. Public means accessible from any other class. Protected means accessible within the same package and by subclasses. Private means accessible only within the same class. Default (no modifier) means accessible within the same package.

37. What is a Java Stream and how is it used?

A Java Stream is a sequence of elements that supports various operations to process data, introduced in Java 8. Streams can be used to perform declarative operations on collections, such as filtering, mapping, and reducing. They allow for efficient and concise data processing and support both sequential and parallel execution.

38. Explain the concept of functional interfaces in Java.

A functional interface in Java is an interface with a single abstract method, used as the type for lambda expressions and method references. Functional interfaces enable functional programming by allowing you to pass behavior as a parameter. Java provides several built-in functional interfaces in the java.util.function package.

39. How do you use the Optional class in Java?

The Optional class in Java is a container object used to represent the presence or absence of a value, introduced in Java 8. It provides methods to check for a value, retrieve the value if present, and provide a default value if not. Optional helps in avoiding null checks and null pointer exceptions, promoting more readable and safer code.

40. Can you describe the Comparator and Comparable interfaces?

The Comparable interface in Java is used to define the natural ordering of objects by implementing the compareTo() method. The Comparator interface is used to define custom ordering by implementing the compare() method. Comparable is used when objects have a single natural order, while Comparator is used for multiple or custom orderings.

41. What is the purpose of the volatile keyword in Java?

The volatile keyword in Java is used to indicate that a variable's value will be modified by different threads. It ensures that the value of the volatile variable is always read from the main memory and not from the thread's local cache. This guarantees visibility of changes to the variable across threads, preventing issues related to memory consistency.

42. How do you manage transactions in Java?

Transactions in Java are managed using the Java Transaction API (JTA) or frameworks like Spring. JTA provides a standard interface for demarcating transactions, while Spring's @Transactional annotation simplifies transaction management by handling transaction boundaries declaratively. Proper transaction management ensures data integrity and consistency in applications.

43. Can you explain the role of the Java Virtual Machine (JVM)?

The Java Virtual Machine (JVM) is the runtime environment that executes Java bytecode. It provides platform independence by abstracting the underlying hardware and operating system. The JVM performs tasks such as memory management, garbage collection, and optimization, ensuring efficient execution of Java applications.

44. What is the main method in Java and why is it important?

The main method in Java is the entry point for any standalone application. It has the signature public static void main(String[] args) and is called by the JVM to start the application. The main method allows the program to be executed and provides an entry point for the application logic.

45. How do you use enums in Java?

Enums in Java are a special type of class used to define a collection of constants. Enums provide type safety and can have fields, methods, and constructors. They are defined using the enum keyword and are used to represent fixed sets of related constants, such as days of the week or states of a process.

46. What are the best practices for writing Java code?

Best practices for writing Java code include following naming conventions, writing clean and readable code, using meaningful variable and method names, and adhering to the principles of object-oriented programming. It is important to handle exceptions properly, write unit tests, document code with comments, and use version control systems for collaboration.

47. Can you describe the Model-View-Controller (MVC) architecture in Java?

The Model-View-Controller (MVC) architecture is a design pattern used to separate concerns in an application. The Model represents the data and business logic, the View represents the user interface, and the Controller handles user input and interacts with the Model. MVC promotes modularity and maintainability by decoupling the components of an application.

48. How do you connect to a database using JDBC in Java?

To connect to a database using JDBC in Java, you load the database driver, establish a connection using the DriverManager.getConnection() method, create a Statement or PreparedStatement object to execute SQL queries, process the ResultSet obtained from the query, and finally close the connection and other resources to free up resources.

49. What are some common performance issues in Java and how do you address them?

Common performance issues in Java include memory leaks, excessive garbage collection, inefficient algorithms, and poor database access patterns. To address these issues, you can use profiling tools to identify bottlenecks, optimize code and algorithms, use efficient data structures, minimize object creation, and optimize database queries and indexing.

50. Can you explain the use of design patterns in Java and provide examples?

Design patterns in Java are proven solutions to common software design problems. They provide a template for writing code that is reusable, maintainable, and scalable. Examples include the Singleton pattern for ensuring a class has only one instance, the Factory pattern for creating objects, and the Observer pattern for implementing event-driven systems. Design patterns promote best practices and improve code quality.

Get More Interviews, Faster

Huntr streamlines your job search. Instantly craft tailored resumes and cover letters, fill out application forms with a single click, effortlessly keep your job hunt organized, and much more...

or learn more

Next-Generation Job Tailored Resumes

Huntr provides the most advanced job <> resume matching system in the world. Helping you match not only keywords, but responsibilities and qualifications from a job, into your resume.

Job Keyword Extractor + Resume AI Integration

Huntr extracts keywords from job descriptions and helps you integrate them into your resume using the power of AI.

Application Autofill

Save hours of mindless form filling. Use our chrome extension to fill application forms with a single click.

Move beyond basic, bare-bones job trackers. Elevate your search with Huntr's all-in-one, feature-rich management platform.

Perfectly tailored cover letters, in seconds! Our cover letter generator blends your unique background with the job's specific requirements, resulting in unique, standout cover letters.

Huntr checks your resume for spelling, length, impactful use of metrics, repetition and more, ensuring your resume gets noticed by employers.

Gorgeous Resume Templates

Stand out with one of 7 designer-grade templates. Whether you're a creative spirit or a corporate professional, our range of templates caters to every career aspiration.

Personal Job Search CRM

The ultimate companion for managing your professional job-search contacts and organizing your job search outreach.

tricky problem solving interview questions in java

Java Guides

Java Guides

Search this blog, top 10 java tricky coding interview questions, youtube video.

Q1 - Consider the following program and predict the output:

Q2 - what is the output of the following program, q3 - what will be the output of the following program, q4 - consider the following program:, q5 - look at the following code and choose the right option for the word :, q6 - consider the following program:, q7 - consider the following program and predict the output:, q8 - consider the following program and choose the correct option from the list of options:, q9 - consider the following program:, q10 - consider the following program and predict the output:, related posts.

Java Multithreading Quiz - Multiple Choice Questions
  Java OOPS Quiz - Java Interview OOPS Programs - Part 1 .  
  Java OOPS Quiz - Java Interview OOPS Programs - Part 2 .  

Post a Comment

Leave Comment

My Top and Bestseller Udemy Courses

  • Spring 6 and Spring Boot 3 for Beginners (Includes Projects)
  • Building Real-Time REST APIs with Spring Boot
  • Building Microservices with Spring Boot and Spring Cloud
  • Full-Stack Java Development with Spring Boot 3 & React
  • Testing Spring Boot Application with JUnit and Mockito
  • Master Spring Data JPA with Hibernate
  • Spring Boot Thymeleaf Real-Time Web Application - Blog App

Check out all my Udemy courses and updates: Udemy Courses - Ramesh Fadatare

Copyright © 2018 - 2025 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub

tricky problem solving interview questions in java

Download Interview guide PDF

  • Java Interview Questions

Download PDF

Do you have what it takes to ace a Java Interview? We are here to help you in consolidating your knowledge and concepts in Java . Before we begin, let's understand what Java is all about.

What is Java? 

Java is a high-level programming language that was developed by James Gosling in the year 1982. It is based on the principles of object-oriented programming and can be used to develop large-scale applications. 

The following article will cover all the popular Core Java interview questions, String Handling interview questions, Java 8 interview questions, Java multithreading interview questions, Java OOPs interview questions, Java exception handling interview questions, collections interview questions, and some frequently asked Java coding interview questions.

Go through all the important questions to enhance your chances of performing well in the Java Interviews. The questions will revolve around the basic, core & advanced fundamentals of Java.

So, let’s dive deep into the plethora of useful Java Technical Interview Questions and Answers categorised into the following sections:

  • Java interview questions for Freshers

Java Intermediate Interview Questions

Java interview questions for experienced, java programming interview questions.

Join our community and share your recent Java interview experiences.

Java Interview Questions for Freshers

1. why is java a platform independent language.

Java language was developed so that it does not depend on any hardware or software because the compiler compiles the code and then converts it to platform-independent byte code which can be run on multiple systems.

  • The only condition to run that byte code is for the machine to have a runtime environment (JRE) installed in it.

2. Why is Java not a pure object oriented language?

Java supports primitive data types - byte, boolean, char, short, int, float, long, and double and hence it is not a pure object oriented language .

3. Difference between Heap and Stack Memory in java. And how java utilizes this.

Stack memory is the portion of memory that was assigned to every individual program. And it was fixed. On the other hand, Heap memory is the portion that was not allocated to the java program but it will be available for use by the java program when it is required, mostly during the runtime of the program.

Java Utilizes this memory as - 

  • When we write a java program then all the variables, methods, etc are stored in the stack memory.
  • And when we create any object in the java program then that object was created in the heap memory. And it was referenced from the stack memory.

Example- Consider the below java program :

For this java program. The stack and heap memory occupied by java is -

tricky problem solving interview questions in java

Main and PrintArray is the method that will be available in the stack area and as well as the variables declared that will also be in the stack area. 

And the Object (Integer Array of size 10) we have created, will be available in the Heap area because that space will be allocated to the program during runtime. 

4. Can java be said to be the complete object-oriented programming language?

It is not wrong if we claim that Java is the complete object-oriented programming language because everything in Java is under the classes and we can access them by creating the objects.

But we can even say that Java is not a completely object-oriented programming language because it has the support of primitive data types like int, float, char, boolean, double, etc.

Now for the question: Is Java a completely object-oriented programming language? We can say that - Java is not a pure object-oriented programming language, because it has direct access to primitive data types. And these primitive data types don't directly belong to the Integer classes.

5. How is Java different from C++?

  • C++ is only a  compiled language, whereas Java is compiled as well as an interpreted language.
  • Java programs are machine-independent whereas a c++ program can run only in the machine in which it is compiled. 
  • C++ allows users to use pointers in the program. Whereas java doesn’t allow it. Java internally uses pointers. 
  • C++ supports the concept of Multiple inheritances whereas Java doesn't support this. And it is due to avoiding the complexity of name ambiguity that causes the diamond problem.

Learn via our Video Courses

6. pointers are used in c/ c++. why does java not make use of pointers.

Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on code simplicity, and the usage of pointers can make it challenging. Pointer utilization can also cause potential errors. Moreover, security is also compromised if pointers are used because the users can directly access memory with the help of pointers.

Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover, the usage of pointers can make the procedure of garbage collection quite slow and erroneous. Java makes use of references as these cannot be manipulated, unlike pointers.

7. What do you understand by an instance variable and a local variable?

Instance variables are those variables that are accessible by all the methods in the class. They are declared outside the methods and inside the class. These variables describe the properties of an object and remain bound to it at any cost.

All the objects of the class will have their copy of the variables for utilization. If any modification is done on these variables, then only that instance will be impacted by it, and all other class instances continue to remain unaffected.

Local variables are those variables present within a block, function, or constructor and can be accessed only inside them. The utilization of the variable is restricted to the block scope. Whenever a local variable is declared inside a method, the other class methods don’t have any knowledge about the local variable.

tricky problem solving interview questions in java

8. What are the default values assigned to variables and instances in java?

  • There are no default values assigned to the variables in java. We need to initialize the value before using it. Otherwise, it will throw a compilation error of ( Variable might not be initialized ). 
  • But for instance, if we create the object, then the default value will be initialized by the default constructor depending on the data type. 
  • If it is a reference, then it will be assigned to null. 
  • If it is numeric, then it will assign to 0.
  • If it is a boolean, then it will be assigned to false. Etc.

9. What do you mean by data encapsulation?

  • Data Encapsulation is an Object-Oriented Programming concept of hiding the data attributes and their behaviours in a single unit.
  • It helps developers to follow modularity while developing software by ensuring that each object is independent of other objects by having its own methods, attributes, and functionalities.
  • It is used for the security of the private properties of an object and hence serves the purpose of data hiding.

tricky problem solving interview questions in java

10. Tell us something about JIT compiler.

  • JIT stands for Just-In-Time and it is used for improving the performance during run time. It does the task of compiling parts of byte code having similar functionality at the same time thereby reducing the amount of compilation time for the code to run.
  • First, the Java source code (.java) conversion to byte code (.class) occurs with the help of the javac compiler.
  • Then, the .class files are loaded at run time by JVM and with the help of an interpreter, these are converted to machine understandable code.
  • JIT compiler is a part of JVM. When the JIT compiler is enabled, the JVM analyzes the method calls in the .class files and compiles them to get more efficient and native code. It also ensures that the prioritized method calls are optimized.
  • Once the above step is done, the JVM executes the optimized code directly instead of interpreting the code again. This increases the performance and speed of the execution.

tricky problem solving interview questions in java

11. Can you tell the difference between equals() method and equality operator (==) in Java?

We are already aware of the (==) equals operator. That we have used this to compare the equality of the values. But when we talk about the terms of object-oriented programming, we deal with the values in the form of objects. And this object may contain multiple types of data. So using the (==) operator does not work in this case. So we need to go with the . equals() method.

Both [(==) and .equals()] primary functionalities are to compare the values, but the secondary functionality is different. 

So in order to understand this better, let’s consider this with the example -

This code will print true. We know that both strings are equals so it will print true. But here (==) Operators don’t compare each character in this case. It compares the memory location. And because the string uses the constant pool for storing the values in the memory, both str1 and str2 are stored at the same memory location. See the detailed Explanation in Question no 73: Link .

tricky problem solving interview questions in java

Now, if we modify the program a little bit with -

tricky problem solving interview questions in java

Then in this case, it will print false. Because here no longer the constant pool concepts are used. Here, new memory is allocated. So here the memory address is different, therefore ( == ) Operator returns false. But the twist is that the values are the same in both strings. So how to compare the values? Here the .equals() method is used.

.equals() method compares the values and returns the result accordingly.  If we modify the above code with - 

Then it returns true.

equals()  ==
This is a method defined in the Object class.  It is a binary operator in Java.
The .equals() Method is present in the Object class, so we can override our custom .equals() method in the custom class, for objects comparison. It cannot be modified. They always compare the HashCode.
This method is used for checking the equality of contents between two objects as per the specified business logic. This operator is used for comparing addresses (or references), i.e checks if both the objects are pointing to the same memory location.
  • In the cases where the equals method is not overridden in a class, then the class uses the default implementation of the equals method that is closest to the parent class.
  • Object class is considered as the parent class of all the java classes. The implementation of the equals method in the Object class uses the == operator to compare two objects. This default implementation can be overridden as per the business logic.

12. How is an infinite loop declared in Java?

Infinite loops are those loops that run infinitely without any breaking conditions. Some examples of consciously declaring infinite loop is:

  • Using For Loop:
  • Using while loop:
  • Using do-while loop:

13. Briefly explain the concept of constructor overloading

Constructor overloading is the process of creating multiple constructors in the class consisting of the same name with a difference in the constructor parameters. Depending upon the number of parameters and their corresponding types, distinguishing of the different types of constructors is done by the compiler.

tricky problem solving interview questions in java

Three constructors are defined here but they differ on the basis of parameter type and their numbers.

14. Define Copy constructor in java.

Copy Constructor is the constructor used when we want to initialize the value to the new object from the old object of the same class. 

Here we are initializing the new object value from the old object value in the constructor. Although, this can also be achieved with the help of object cloning.

15. Can the main method be Overloaded?

Yes, It is possible to overload the main method. We can create as many overloaded main methods we want. However, JVM has a predefined calling method that JVM will only call the main method with the definition of - 

Consider the below code snippets: 

16. Comment on method overloading and overriding by citing relevant examples.

In Java, method overloading is made possible by introducing different methods in the same class consisting of the same name. Still, all the functions differ in the number or type of parameters. It takes place inside a class and enhances program readability.

The only difference in the return type of the method does not promote method overloading. The following example will furnish you with a clear picture of it.

tricky problem solving interview questions in java

Both the functions have the same name but differ in the number of arguments. The first method calculates the area of the rectangle, whereas the second method calculates the area of a cuboid.

Method overriding is the concept in which two methods having the same method signature are present in two different classes in which an inheritance relationship is present. A particular method implementation (already present in the base class) is possible for the derived class by using method overriding. Let’s give a look at this example:

tricky problem solving interview questions in java

Both class methods have the name walk and the same parameters, distance, and time. If the derived class method is called, then the base class method walk gets overridden by that of the derived class.

17. A single try block and multiple catch blocks can co-exist in a Java Program. Explain.

Yes, multiple catch blocks can exist but specific approaches should come prior to the general approach because only the first catch block satisfying the catch condition is executed. The given code illustrates the same:

Here, the second catch block will be executed because of division by 0 (i / x). In case x was greater than 0 then the first catch block will execute because for loop runs till i = n and array index are till n-1.

18. Explain the use of final keyword in variable, method and class.

In Java, the final keyword is used as defining something as constant /final and represents the non-access modifier.

  • When a variable is declared as final in Java, the value can’t be modified once it has been assigned.
  • If any value has not been assigned to that variable, then it can be assigned only by the constructor of the class.
  • A method declared as final cannot be overridden by its children's classes.
  • A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn't make sense. Java throws compilation error saying - modifier final not allowed here
  • No classes can be inherited from the class declared as final. But that final class can extend other classes for its usage.

19. Do final, finally and finalize keywords have the same function?

All three keywords have their own utility while programming.

Final: If any restriction is required for classes, variables, or methods, the final keyword comes in handy. Inheritance of a final class and overriding of a final method is restricted by the use of the final keyword. The variable value becomes fixed after incorporating the final keyword. Example:

The second statement will throw an error.

Finally: It is the block present in a program where all the codes written inside it get executed irrespective of handling of exceptions. Example:

Finalize: Prior to the garbage collection of an object, the finalize method is called so that the clean-up activity is implemented. Example:

20. Is it possible that the ‘finally’ block will not be executed? If yes then list the case.

 Yes. It is possible that the ‘finally’ block will not be executed. The cases are-

  • Suppose we use System.exit() in the above statement.
  • If there are fatal errors like Stack overflow, Memory access error, etc.

21. Identify the output of the java program and state the reason.

The above code will generate a compile-time error at Line 7 saying - [error: variable i might already have been initialized] . It is because variable ‘i’ is the final variable. And final variables are allowed to be initialized only once, and that was already done on line no 5.

22. When can you use super keyword?

  • The super keyword is used to access hidden fields and overridden methods or attributes of the parent class.
  • Accessing data members of parent class when the member names of the class and its child subclasses are same.
  • To call the default and parameterized constructor of the parent class inside the child class.
  • Accessing the parent class methods when the child classes have overridden them.
  • The following example demonstrates all 3 cases when a super keyword is used.

23. Can the static methods be overloaded?

Yes! There can be two or more static methods in a class with the same name but differing input parameters.

24. Why is the main method static in Java?

The main method is always static because static members are those methods that belong to the classes, not to an individual object. So if the main method will not be static then for every object, It is available. And that is not acceptable by JVM. JVM calls the main method based on the class name itself. Not by creating the object.

Because there must be only 1 main method in the java program as the execution starts from the main method. So for this reason the main method is static. 

25. Can the static methods be overridden?

  • No! Declaration of static methods having the same signature can be done in the subclass but run time polymorphism can not take place in such cases.
  • Overriding or dynamic polymorphism occurs during the runtime, but the static methods are loaded and looked up at the compile time statically. Hence, these methods cant be overridden.

26. Difference between static methods, static variables, and static classes in java.

  • For example - We have used mathematical functions in the java program like - max(), min(), sqrt(), pow(), etc. And if we notice that, then we will find that we call it directly with the class name. Like - Math.max(), Math.min(), etc. So that is a static method.  And Similarly static variables we have used like (length) for the array to get the length. So that is the static method.
  • Static classes - A class in the java program cannot be static except if it is the inner class. If it is an inner static class, then it exactly works like other static members of the class.

27. What is the main objective of garbage collection?

The main objective of this process is to free up the memory space occupied by the unnecessary and unreachable objects during the Java program execution by deleting those unreachable objects.

  • This ensures that the memory resource is used efficiently, but it provides no guarantee that there would be sufficient memory for the program execution.

28. What is a ClassLoader?

  • Java Classloader is the program that belongs to JRE (Java Runtime Environment). The task of ClassLoader is to load the required classes and interfaces to the JVM when required. 
  • Example- To get input from the console, we require the scanner class. And the Scanner class is loaded by the ClassLoader.

29. What part of memory - Stack or Heap - is cleaned in garbage collection process?

30. what are shallow copy and deep copy in java.

To copy the object's data, we have several methods like deep copy and shallow copy. 

Object for this Rectangle class - Rectangle obj1 = new Rectangle();

  • Shallow copy - The shallow copy only creates a new reference and points to the same object. Example - For Shallow copy, we can do this by -

Now by doing this what will happen is the new reference is created with the name obj2 and that will point to the same memory location.

  • Deep Copy - In a deep copy, we create a new object and copy the old object value to the new object. Example -

Both these objects will point to the memory location as stated below -

tricky problem solving interview questions in java

Now, if we change the values in shallow copy then they affect the other reference as well. Let's see with the help of an example - 

We can see that in the above code, if we change the values of object1, then the object2 values also get changed. It is because of the reference.

Now, if we change the code to deep copy, then there will be no effect on object2 if it is of type deep copy. Consider some snippets to be added in the above code.

The above snippet will not affect the object2 values. It has its separate values. The output will be

Now we see that we need to write the number of codes for this deep copy. So to reduce this, In java, there is a method called clone().  

The clone() will do this deep copy internally and return a new object. And to do this we need to write only 1 line of code. That is - Rectangle obj2 = obj1.clone();

1. Apart from the security aspect, what are the reasons behind making strings immutable in Java?

A String is made immutable due to the following reasons:

  • String Pool: Designers of Java were aware of the fact that String data type is going to be majorly used by the programmers and developers. Thus, they wanted optimization from the beginning. They came up with the notion of using the String pool (a storage area in Java heap) to store the String literals. They intended to decrease the temporary String object with the help of sharing. An immutable class is needed to facilitate sharing. The sharing of the mutable structures between two unknown parties is not possible. Thus, immutable Java String helps in executing the concept of String Pool.

tricky problem solving interview questions in java

  • Multithreading : The safety of threads regarding the String objects is an important aspect in Java. No external synchronization is required if the String objects are immutable. Thus, a cleaner code can be written for sharing the String objects across different threads. The complex process of concurrency is facilitated by this method.
  • Collections : In the case of Hashtables and HashMaps, keys are String objects. If the String objects are not immutable, then it can get modified during the period when it resides in the HashMaps. Consequently, the retrieval of the desired data is not possible. Such changing states pose a lot of risks. Therefore, it is quite safe to make the string immutable.

2. What is a singleton class in Java? And How to implement a singleton class?

Singleton classes are those classes, whose objects are created only once. And with only that object the class members can be accessed. 

Understand this with the help of an example-:

Consider the water jug in the office and if every employee wants that water then they will not create a new water jug for drinking water. They will use the existing one with their own reference as a glass. So programmatically it should be implemented as -

In the above class, the Constructor is private so we cannot create the object of the class. But we can get the object by calling the method getInstance() . And the getInstance is static so it can be called without creating the object. And it returns the object. Now with that object, we can call getWater() to get the water.

We can get the single object using this getInstance(). And it is static, so it is a thread-safe singleton class. Although there are many ways to create a thread-safe singleton class. So thread-safe classes can also be:

  • When singletons are written with double-checked locking, they can be thread-safe.
  • We can use static singletons that are initialized during class loading. Like we did in the above example.
  • But the most straightforward way to create a thread-safe singleton is to use Java enums.

3. Which of the below generates a compile-time error? State the reason.

  • int[] n1 = new int[0];
  • boolean[] n2 = new boolean[-200];
  • double[] n3 = new double[2241423798];
  • char[] ch = new char[20];

We get a compile-time error in line 3. The error we will get in Line 3 is - integer number too large . It is because the array requires size as an integer. And Integer takes 4 Bytes in the memory. And the number ( 2241423798 ) is beyond the capacity of the integer. The maximum array size we can declare is - ( 2147483647 ).

Because the array requires the size in integer, none of the lines (1, 2, and 4) will give a compile-time error. The program will compile fine. But we get the runtime exception in line 2. The exception is - NegativeArraySizeException . 

Here what will happen is - At the time when JVM will allocate the required memory during runtime then it will find that the size is negative. And the array size can’t be negative. So the JVM will throw the exception.

4. How would you differentiate between a String, StringBuffer, and a StringBuilder?

  • Storage area: In string, the String pool serves as the storage area. For StringBuilder and StringBuffer, heap memory is the storage area.
  • Mutability: A String is immutable, whereas both the StringBuilder and StringBuffer are mutable.
  • Efficiency: It is quite slow to work with a String. However, StringBuilder is the fastest in performing operations. The speed of a StringBuffer is more than a String and less than a StringBuilder. (For example appending a character is fastest in StringBuilder and very slow in String because a new memory is required for the new String with appended character.)
  • Thread-safe: In the case of a threaded environment, StringBuilder and StringBuffer are used whereas a String is not used. However, StringBuilder is suitable for an environment with a single thread, and a StringBuffer is suitable for multiple threads. Syntax:

5. Using relevant properties highlight the differences between interfaces and abstract classes.

  • Availability of methods: Only abstract methods are available in interfaces, whereas non-abstract methods can be present along with abstract methods in abstract classes.
  • Variable types : Static and final variables can only be declared in the case of interfaces, whereas abstract classes can also have non-static and non-final variables.
  • Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract classes do not promote multiple inheritances.
  • Data member accessibility: By default, the class data members of interfaces are of the public- type. Conversely, the class members for an abstract class can be protected or private also.
  • Implementation: With the help of an abstract class, the implementation of an interface is easily possible. However, the converse is not true;

Abstract class example:

Interface example:

6. Is this program giving a compile-time error? If Yes then state the reason and number of errors it will give. If not then state the reason.

The above program will give a compile-time error. The compiler will throw 2 errors in this.

  • [Illegal Combination of modifiers: abstract and final] at line 1.
  • [Cannot inherit from final ‘InterviewBit’] at line 4.

It is because abstract classes are incomplete classes that need to be inherited for making their concrete classes. And on the other hand, the final keywords in class are used for avoiding inheritance. So these combinations are not allowed in java.

7. What is a Comparator in java?

Consider the example where we have an ArrayList of employees like( EId, Ename, Salary), etc. Now if we want to sort this list of employees based on the names of employees. Then that is not possible to sort using the Collections.sort() method. We need to provide something to the sort() function depending on what values we have to perform sorting. Then in that case a comparator is used.

Comparator is the interface in java that contains the compare method. And by overloading the compare method, we can define that on what basis we need to compare the values. 

8. In Java, static as well as private method overriding is possible. Comment on the statement.

The statement in the context is completely False. The static methods have no relevance with the objects, and these methods are of the class level. In the case of a child class, a static method with a method signature exactly like that of the parent class can exist without even throwing any compilation error.

The phenomenon mentioned here is popularly known as method hiding, and overriding is certainly not possible. Private method overriding is unimaginable because the visibility of the private method is restricted to the parent class only. As a result, only hiding can be facilitated and not overriding.

9. What makes a HashSet different from a TreeSet?

Although both HashSet and TreeSet are not synchronized and ensure that duplicates are not present, there are certain properties that distinguish a HashSet from a TreeSet.

  • Implementation: For a HashSet, the hash table is utilized for storing the elements in an unordered manner. However, TreeSet makes use of the red-black tree to store the elements in a sorted manner.
  • Complexity/ Performance: For adding, retrieving, and deleting elements, the time amortized complexity is O(1) for a HashSet. The time complexity for performing the same operations is a bit higher for TreeSet and is equal to O(log n). Overall, the performance of HashSet is faster in comparison to TreeSet.
  • Methods: hashCode() and equals() are the methods utilized by HashSet for making comparisons between the objects. Conversely, compareTo() and compare() methods are utilized by TreeSet to facilitate object comparisons.
  • Objects type: Heterogeneous and null objects can be stored with the help of HashSet. In the case of a TreeSet, runtime exception occurs while inserting heterogeneous objects or null objects.

10. Why is the character array preferred over string for storing confidential information?

In Java, a string is basically immutable i.e. it cannot be modified. After its declaration, it continues to stay in the string pool as long as it is not removed in the form of garbage. In other words, a string resides in the heap section of the memory for an unregulated and unspecified time interval after string value processing is executed.

As a result, vital information can be stolen for pursuing harmful activities by hackers if a memory dump is illegally accessed by them. Such risks can be eliminated by using mutable objects or structures like character arrays for storing any variable. After the work of the character array variable is done, the variable can be configured to blank at the same instant. Consequently, it helps in saving heap memory and also gives no chance to the hackers to extract vital data.

11. What do we get in the JDK file?

  • JDK - For making java programs, we need some tools that are provided by JDK (Java Development Kit). JDK is the package that contains various tools, Compiler, Java Runtime Environment, etc.
  • JRE -  To execute the java program we need an environment. (Java Runtime Environment) JRE contains a library of Java classes +  JVM. What are JAVA Classes?  It contains some predefined methods that help Java programs to use that feature, build and execute. For example - there is a system class in java that contains the print-stream method, and with the help of this, we can print something on the console.
  • JVM - (Java Virtual Machine) JVM  is a part of JRE that executes the Java program at the end.  Actually, it is part of JRE, but it is software that converts bytecode into machine-executable code to execute on hardware.

tricky problem solving interview questions in java

12. What are the differences between JVM, JRE and JDK in Java?

Criteria JDK  JRE JVM
Abbreviation Java Development Kit Java Runtime Environment Java Virtual Machine
Definition JDK is a complete software development kit for developing Java applications. It comprises JRE, JavaDoc, compiler, debuggers, etc. JRE is a software package providing Java class libraries, JVM and all the required components to run the Java applications. JVM is a platform-dependent, abstract machine comprising of 3 specifications - document describing the JVM implementation requirements, computer program meeting the JVM requirements and instance object for executing the Java byte code and provide the runtime environment for execution.
Main Purpose JDK is mainly used for code development and execution. JRE is mainly used for environment creation to execute the code. JVM provides specifications for all the implementations to JRE.
Tools provided JDK provides tools like compiler, debuggers, etc for code development JRE provides libraries and classes required by JVM to run the program. JVM does not include any tools, but instead, it provides the specification for implementation.
Summary JDK = (JRE) + Development tools JRE = (JVM) + Libraries to execute the application JVM = Runtime environment to execute Java byte code.

13. What are the differences between HashMap and HashTable in Java?

HashMap HashTable
HashMap is not synchronized thereby making it better for non-threaded applications. HashTable is synchronized and hence it is suitable for threaded applications.
Allows only one null key but any number of null in the values. This does not allow null in both keys or values.
Supports order of insertion by making use of its subclass LinkedHashMap. Order of insertion is not guaranteed in HashTable.

14. What is the importance of reflection in Java?

  • The term reflection is used for describing the inspection capability of a code on other code either of itself or of its system and modify it during runtime.
  • Consider an example where we have an object of unknown type and we have a method ‘fooBar()’ which we need to call on the object. The static typing system of Java doesn't allow this method invocation unless the type of the object is known beforehand. This can be achieved using reflection which allows the code to scan the object and identify if it has any method called “fooBar()” and only then call the method if needed.
  • Speed — Method invocations due to reflection are about three times slower than the direct method calls.
  • Type safety — When a method is invoked via its reference wrongly using reflection, invocation fails at runtime as it is not detected at compile/load time.
  • Traceability — Whenever a reflective method fails, it is very difficult to find the root cause of this failure due to a huge stack trace. One has to deep dive into the invoke() and proxy() method logs to identify the root cause.
  • Hence, it is advisable to follow solutions that don't involve reflection and use this method as a last resort.

15. What are the different ways of threads usage?

  • Extending the Thread class
  • Implementing the Runnable interface
  • Implementing a thread using the method of Runnable interface is more preferred and advantageous as Java does not have support for multiple inheritances of classes.
  • start() method is used for creating a separate call stack for the thread execution. Once the call stack is created, JVM calls the run() method for executing the thread in that call stack.

16. What are the different types of Thread Priorities in Java? And what is the default priority of a thread assigned by JVM?

There are a total of 3 different types of priority available in Java. 

MIN_PRIORITY: It has an integer value assigned with 1. MAX_PRIORITY: It has an integer value assigned with 10. NORM_PRIORITY: It has an integer value assigned with 5.

In Java, Thread with MAX_PRIORITY gets the first chance to execute. But the default priority for any thread is NORM_PRIORITY assigned by JVM. 

17. What is the difference between the program and the process?

  • A program can be defined as a line of code written in order to accomplish a particular task. Whereas the process can be defined as the programs which are under execution. 
  • A program doesn't execute directly by the CPU. First, the resources are allocated to the program and when it is ready for execution then it is a process.

18. What is the difference between the ‘throw’ and ‘throws’ keyword in java?

  • The ‘ throw ’ keyword is used to manually throw the exception to the calling method.
  • And the ‘ throws ’ keyword is used in the function definition to inform the calling method that this method throws the exception. So if you are calling, then you have to handle the exception.

Here in the above snippet, the method testExceptionDivide throws an exception. So if the main method is calling it then it must have handled the exception. Otherwise, the main method can also throw the exception to JVM.

And the method testExceptionDivide 'throws’ the exception based on the condition.

19. What are the differences between constructor and method of a class in Java?

Constructor Method
Constructor is used for initializing the object state. Method is used for exposing the object's behavior.
Constructor has no return type. Method should have a return type. Even if it does not return anything, return type is void.
Constructor gets invoked implicitly. Method has to be invoked on the object explicitly.
If the constructor is not defined, then a default constructor is provided by the java compiler. If a method is not defined, then the compiler does not provide it.
The constructor name should be equal to the class name. The name of the method can have any name or have a class name too.
A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn't make sense. Java throws compilation error saying - A method can be defined as final but it cannot be overridden in its subclasses.
Final variable instantiations are possible inside a constructor and the scope of this applies to the whole class and its objects. A final variable if initialised inside a method ensures that the variable cant be changed only within the scope of that method.

20. Identify the output of the below java program and Justify your answer.

The above code will throw the compilation error. It is because the super() is used to call the parent class constructor. But there is the condition that super() must be the first statement in the block. Now in this case, if we replace this() with super() then also it will throw the compilation error. Because this() also has to be the first statement in the block. So in conclusion, we can say that we cannot use this() and super() keywords in the same block.

21. Java works as “pass by value” or “pass by reference” phenomenon?

Java always works as a “pass by value”. There is nothing called a “pass by reference” in Java. However, when the object is passed in any method, the address of the value is passed due to the nature of object handling in Java. When an object is passed, a copy of the reference is created by Java and that is passed to the method. The objects point to the same memory location. 2 cases might happen inside the method:

  • Case 1: When the object is pointed to another location: In this case, the changes made to that object do not get reflected the original object before it was passed to the method as the reference points to another location.

For example:

  • Case 2: When object references are not modified: In this case, since we have the copy of reference the main object pointing to the same memory location, any changes in the content of the object get reflected in the original object.

22. What is the ‘IS-A ‘ relationship in OOPs java?

‘IS-A’ relationship is another name for inheritance. When we inherit the base class from the derived class, then it forms a relationship between the classes. So that relationship is termed an ‘IS-A’ Relationship.

Example - Consider a Television (Typical CRT TV). Now another Smart TV  that is inherited from television class. So we can say that the Smart iv is also a TV. Because CRT TV things can also be done in the Smart TV.

tricky problem solving interview questions in java

So here ‘IS-A’ Relationship formed. [ SmartTV ‘IS-A’ TV ] .

23. Which among String or String Buffer should be preferred when there are lot of updates required to be done in the data?

StringBuffer is mutable and dynamic in nature whereas String is immutable. Every updation / modification of String creates a new String thereby overloading the string pool with unnecessary objects. Hence, in the cases of a lot of updates, it is always preferred to use StringBuffer as it will reduce the overhead of the creation of multiple String objects in the string pool.

24. How to not allow serialization of attributes of a class in Java?

  • In order to achieve this, the attribute can be declared along with the usage of transient keyword as shown below:
  • In the above example, all the fields except someInfo can be serialized.

25. What happens if the static modifier is not included in the main method signature in Java?

There wouldn't be any compilation error. But then the program is run, since the JVM cant map the main method signature, the code throws “NoSuchMethodError” error at the runtime.

26. Consider the below program, identify the output, and also state the reason for that.

The output of the above program will be Hello. Main Method . This is because JVM will always call the main method based on the definition it already has. Doesn't matter how many main methods we overload it will only execute one main method based on its declaration in JVM.

27. Can we make the main() thread a daemon thread?

In java multithreading, the main() threads are always non-daemon threads. And there is no way we can change the nature of the non-daemon thread to the daemon thread.

28. What happens if there are multiple main methods inside one class in Java?

The program can't compile as the compiler says that the method has been already defined inside the class.

29. What do you understand by Object Cloning and how do you achieve it in Java?

  • It is the process of creating an exact copy of any object. In order to support this, a java class has to implement the Cloneable interface of java.lang package and override the clone() method provided by the Object class the syntax of which is:
  • In case the Cloneable interface is not implemented and just the method is overridden, it results in CloneNotSupportedException in Java.

30. How does an exception propagate in the code?

When an exception occurs, first it searches to locate the matching catch block. In case, the matching catch block is located, then that block would be executed. Else, the exception propagates through the method call stack and goes into the caller method where the process of matching the catch block is performed. This propagation happens until the matching catch block is found. If the match is not found, then the program gets terminated in the main method.

tricky problem solving interview questions in java

31. How do exceptions affect the program if it doesn't handle them?

Exceptions are runtime errors. Suppose we are making an android application with java. And it all works fine but there is an exceptional case when the application tries to get the file from storage and the file doesn’t exist (This is the case of exception in java). And if this case is not handled properly then the application will crash. This will be a bad experience for users.  This is the type of error that cannot be controlled by the programmer. But programmers can take some steps to avoid this so that the application won’t crash. The proper action can be taken at this step.

32. Is it mandatory for a catch block to be followed after a try block?

No, it is not necessary for a catch block to be present after a try block. - A try block should be followed either by a catch block or by a finally block. If the exceptions likelihood is more, then they should be declared using the throws clause of the method.

33. Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below?

finally block will be executed irrespective of the exception or not. The only case where finally block is not executed is when it encounters ‘System.exit()’ method anywhere in try/catch block.

34. Can you call a constructor of a class inside the another constructor?

Yes, the concept can be termed as constructor chaining and can be achieved using this() .

tricky problem solving interview questions in java

35. Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList. Explain.

In the case of ArrayList, data storing in the form of primitive data types (like int, float, etc.) is not possible. The data members/objects present in the ArrayList have references to the objects which are located at various sites in the memory. Thus, storing of actual objects or non-primitive data types (like Integer, Double, etc.) takes place in various memory locations.

tricky problem solving interview questions in java

However, the same does not apply to the arrays. Object or primitive type values can be stored in arrays in contiguous memory locations, hence every element does not require any reference to the next element.

tricky problem solving interview questions in java

36. Why does the java array index start with 0?

It is because the 0 index array avoids the extra arithmetic operation to calculate the memory address.

Example - Consider the array and assume each element takes 4-byte memory space. Then the address will be like this -

tricky problem solving interview questions in java

Now if we want to access index 4. Then internally java calculates the address using the formula-

[Base Address + (index * no_of_bytes)] . So according to this. The starting address of the index 4 will be - [100 + (4*4)] = 116 . And exactly that's what the address is calculated.  Now consider the same with 1 index Array -

tricky problem solving interview questions in java

Now if we apply the same formula here. Then we get - 116 as the starting address of the 4th index. Which is wrong. Then we need to apply formula - [ Base Address + ((index-1) * no_of_bytes)] .

And for calculating this, an extra arithmetic operation has to be performed. And consider the case where millions of addresses need to be calculated, this causes complexity. So to avoid this, ) the index array is supported by java.

37. Why is the remove method faster in the linked list than in an array?

In the linked list, we only need to adjust the references when we want to delete the element from either end or the front of the linked list. But in the array, indexes are used. So to manage proper indexing, we need to adjust the values from the array So this adjustment of value is costlier than the adjustment of references.

Example - To Delete from the front of the linked list, internally the references adjustments happened like this.

tricky problem solving interview questions in java

The only thing that will change is that the head pointer will point to the head’s next node. And delete the previous node. That is the constant time operation.

Whereas in the ArrayList, internally it should work like this-

tricky problem solving interview questions in java

For deletion of the first element, all the next element has to move to one place ahead. So this copying value takes time. So that is the reason why removing in ArrayList is slower than LinkedList.

38. How many overloaded add() and addAll() methods are available in the List interface? Describe the need and uses.

There are a total of 4 overloaded methods for add() and addAll() methods available in List Interface. The below table states the description of all.

Return Type Method Description
boolean : This method is used for adding the element at the end of the List. The Datatype of the element is of any type it has been initially assigned with. It returns the boolean indicating successfully inserted or not.
void : This method is the overloaded version of add() method. In this, along with the element, the index is also passed to the method for the specific index the value needs to be inserted. 
boolean : This method helps to add all elements at the end of collections from the list received in the parameter. It contains an iterator that helps to iterate the list and add the elements to the collection.
boolean : This is the overloaded method for addAll() method. In this along with the list, we can pass the specified index from which the list elements need to be added.

39. How does the size of ArrayList grow dynamically? And also state how it is implemented internally.

ArrayList is implemented in such a way that it can grow dynamically. We don't need to specify the size of ArrayList. For adding the values in it, the methodology it uses is -

1. Consider initially that there are 2 elements in the ArrayList. [2, 3] .

tricky problem solving interview questions in java

2. If we need to add the element into this. Then internally what will happen is-

  • ArrayList will allocate the new ArrayList of Size (current size + half of the current size). And add the old elements into the new. Old - [2, 3],    New - [2, 3, null].

tricky problem solving interview questions in java

  • Then the new value will be inserted into it. [2, 3, 4, null]. And for the next time, the extra space will be available for the value to be inserted.

tricky problem solving interview questions in java

3. This process continues and the time taken to perform all of these is considered as the amortized constant time. 

This is how the ArrayList grows dynamically. And when we delete any entry from the ArrayList then the following steps are performed -

1. It searches for the element index in the array. Searching takes some time. Typically it’s O(n) because it needs to search for the element in the entire array.

tricky problem solving interview questions in java

2. After searching the element, it needs to shift the element from the right side to fill the index.

tricky problem solving interview questions in java

So this is how the elements are deleted from the ArrayList internally. Similarly, the search operations are also implemented internally as defined in removing elements from the list (searching for elements to delete).

1. Although inheritance is a popular OOPs concept, it is less advantageous than composition. Explain.

Inheritance lags behind composition in the following scenarios:

  • Multiple-inheritance is not possible in Java. Classes can only extend from one superclass. In cases where multiple functionalities are required, for example - to read and write information into the file, the pattern of composition is preferred. The writer, as well as reader functionalities, can be made use of by considering them as the private members.
  • Composition assists in attaining high flexibility and prevents breaking of encapsulation.
  • Unit testing is possible with composition and not inheritance. When a developer wants to test a class composing a different class, then Mock Object can be created for signifying the composed class to facilitate testing. This technique is not possible with the help of inheritance as the derived class cannot be tested without the help of the superclass in inheritance.
  • The loosely coupled nature of composition is preferable over the tightly coupled nature of inheritance.

Let’s take an example:

In the above example, inheritance is followed. Now, some modifications are done to the Top class like this:

If the new implementation of the Top class is followed, a compile-time error is bound to occur in the Bottom class. Incompatible return type is there for the Top.stop() function. Changes have to be made to either the Top or the Bottom class to ensure compatibility. However, the composition technique can be utilized to solve the given problem:

2. What is the difference between ‘>>’ and ‘>>>’ operators in java?

These 2 are the bitwise right shift operators. Although both operators look similar. But there is a minimal difference between these two right shift operators.

  • ‘>>’ Bitwise Right Shift Operator - This operator shifts each bit to its right position. And this maintains the signed bit.
  • ‘>>>’ Bitwise Right Shift Operator with trailing zero - This operator also shifts each bit to its right. But this doesn’t maintain the signed bit. This operator makes the Most significant bit to 0.

Example- Num1 = 8, Num2 = -8.

So the binary form of these numbers are - 

Num1 = 00000000 00000000 00000000 00001000  Num2 = 11111111 11111111 11111111  11111000

‘>>’ Operator : 8 >> 1 (Shift by one bit) : 

Num1 = 00000000 00000000 00000000 00000100 Num2 = 11111111 11111111 11111111  11111100

‘>>>’ Operator : 8 >>> 1 (Shift by one bit) = 

Num1 = 00000000 00000000 00000000 00000100 Num2 = 01111111 11111111 11111111 11111100

3. What are Composition and Aggregation? State the difference.

Composition, and Aggregation help to build (Has - A - Relationship) between classes and objects. But both are not the same in the end. Let’s understand with the help of an example. 

  • Consider the University as a class that has some departments in it. So the university will be the container object. And departments in it will contain objects. Now in this case, if the container object destroys then the contained objects will also get destroyed automatically.  So here we can say that there is a strong association between the objects. So this Strong Association is called Composition .
  • Now consider one more example. Suppose we have a class department and there are several professors' objects there in the department. Now if the department class is destroyed then the professor's object will become free to bind with other objects. Because container objects (Department) only hold the references of contained objects (Professor’s). So here is the weak association between the objects. And this weak association is called Aggregation .

4. How is the creation of a String using new() different from that of a literal?

When a String is formed as a literal with the assistance of an assignment operator, it makes its way into the String constant pool so that String Interning can take place. This same object in the heap will be referenced by a different String if the content is the same for both of them.

The checking() function will return true as the same content is referenced by both the variables.

tricky problem solving interview questions in java

Conversely, when a String formation takes place with the help of a new() operator, interning does not take place. The object gets created in the heap memory even if the same content object is present.

The checking() function will return false as the same content is not referenced by both the variables.

tricky problem solving interview questions in java

5. How is the ‘new’ operator different from the ‘newInstance()’ operator in java?

Both ‘ new ’ and ‘ newInstance() ’ operators are used to creating objects. The difference is- that when we already know the class name for which we have to create the object then we use a new operator. But suppose we don’t know the class name for which we need to create the object, Or we get the class name from the command line argument, or the database, or the file. Then in that case we use the ‘ newInstance() ’ operator.

The ‘ newInstance() ’ keyword throws an exception that we need to handle. It is because there are chances that the class definition doesn’t exist, and we get the class name from runtime. So it will throw an exception.

6. Is exceeding the memory limit possible in a program despite having a garbage collector?

Yes, it is possible for the program to go out of memory in spite of the presence of a garbage collector. Garbage collection assists in recognizing and eliminating those objects which are not required in the program anymore, in order to free up the resources used by them.

In a program, if an object is unreachable, then the execution of garbage collection takes place with respect to that object. If the amount of memory required for creating a new object is not sufficient, then memory is released for those objects which are no longer in the scope with the help of a garbage collector. The memory limit is exceeded for the program when the memory released is not enough for creating new objects.

Moreover, exhaustion of the heap memory takes place if objects are created in such a manner that they remain in the scope and consume memory. The developer should make sure to dereference the object after its work is accomplished. Although the garbage collector endeavors its level best to reclaim memory as much as possible, memory limits can still be exceeded.

Let’s take a look at the following example:

7. Why is synchronization necessary? Explain with the help of a relevant example.

Concurrent execution of different processes is made possible by synchronization. When a particular resource is shared between many threads, situations may arise in which multiple threads require the same shared resource.

Synchronization assists in resolving the issue and the resource is shared by a single thread at a time. Let’s take an example to understand it more clearly. For example, you have a URL and you have to find out the number of requests made to it. Two simultaneous requests can make the count erratic.

No synchronization:

tricky problem solving interview questions in java

If a thread Thread1 views the count as 10, it will be increased by 1 to 11. Simultaneously, if another thread Thread2 views the count as 10, it will be increased by 1 to 11. Thus, inconsistency in count values takes place because the expected final value is 12 but the actual final value we get will be 11.

Now, the function increase() is made synchronized so that simultaneous accessing cannot take place.

With synchronization:

tricky problem solving interview questions in java

If a thread Thread1 views the count as 10, it will be increased by 1 to 11, then the thread Thread2 will view the count as 11, it will be increased by 1 to 12. Thus, consistency in count values takes place.

8. In the given code below, what is the significance of ... ?

  • Ability to provide ... is a feature called varargs (variable arguments) which was introduced as part of Java 5.
  • The function having ... in the above example indicates that it can receive multiple arguments of the datatype String.
  • For example, the fooBarMethod can be called in multiple ways and we can still have one method to process the data as shown below:

9. What will be the output of the below java program and define the steps of Execution of the java program with the help of the below code?

The Output we get by executing this program will be

Static Block 1. Value of j = 0 Static method.  Static Block 2. Value of j = 10 Instance Block 1. Value of i = 0 Instance Block 2. Value of i = 5 Instance method.  Welcome to InterviewBit

This is a java tricky interview question frequently asked in java interviews for the experienced. The output will be like this because, when the java program is compiled and gets executed, then there are various steps followed for execution. And the steps are - 

  • Identification of Static Members from top to bottom.
  • Execution of Static variable assignment and a Static block from top to bottom.
  • Execution of the main method.
  • Identification of Instance Members from top to bottom.
  • Execution of Instance variable assignment and Instance block from top to bottom.
  • Execution of Constructor.

In above steps from 4 to 6, will be executed for every object creation. If we create multiple objects then for every object these steps will be performed.

Now from the above code, the execution will happen like this - 

1. In the step of identification of static members. It is found that -

  • static int j.
  • static block.
  • main method.
  • static method_2.

During identification, the JVM will assign the default value in the static int j variable. Then it is currently in the state of reading and indirectly writing. Because the original value is not assigned.

2. In the next step, it will execute the static block and assign the value in static variables.

  • First static block it will print and because execution from top to bottom and original value in j is not assigned. So it will print the default value of 0.
  • After executing static block 1. It will execute the static method_1 because it is called from the static block 1.
  • Then it will assign the original value of 5 in the j variable. And executes the remaining static block.

3. Now it will execute the main method. In which it will create an object for the class InterviewBit. And then the execution of instances will happen.

4. Identify the instance variables and blocks from top to bottom. 

  • Instance block 1.
  • Instance method_1.

Like a static variable, the instance variable also has been initialized with the default value 0 and will be in the state of reading and writing indirectly.

5. It will execute the instance methods and assign the original value to the instance variable.

  • Prints the Instance block 1. And the current value of i is not assigned till now, so it will print 0.
  • Assign the original value to i. Then print instance block 2. And after that instance method will be called and printed because it is being called in the instance block.

6. And at the last step, the constructor will be invoked and the lines will be executed in the constructor.

This is how the java program gets executed.

10. Define System.out.println().

System.out.println() is used to print the message on the console. System - It is a class present in java.lang package . Out is the static variable of type PrintStream class present in the System class. println() is the method present in the PrintStream class.

So if we justify the statement, then we can say that if we want to print anything on the console then we need to call the println() method that was present in PrintStream class. And we can call this using the output object that is present in the System class.

11. Can you explain the Java thread lifecycle?

Java thread life cycle is as follows:

  • New – When the instance of the thread is created and the start() method has not been invoked, the thread is considered to be alive and hence in the NEW state.
  • Runnable – Once the start() method is invoked, before the run() method is called by JVM, the thread is said to be in RUNNABLE (ready to run) state. This state can also be entered from the Waiting or Sleeping state of the thread.
  • Running – When the run() method has been invoked and the thread starts its execution, the thread is said to be in a RUNNING state.
  • A thread is said to be in a Blocked state if it wants to enter synchronized code but it is unable to as another thread is operating in that synchronized block on the same object. The first thread has to wait until the other thread exits the synchronized block.
  • A thread is said to be in a Waiting state if it is waiting for the signal to execute from another thread, i.e it waits for work until the signal is received.
  • Terminated – Once the run() method execution is completed, the thread is said to enter the TERMINATED step and is considered to not be alive.

The following flowchart clearly explains the lifecycle of the thread in Java.

tricky problem solving interview questions in java

12. What could be the tradeoff between the usage of an unordered array versus the usage of an ordered array?

  • The main advantage of having an ordered array is the reduced search time complexity of O(log n) whereas the time complexity in an unordered array is O(n) .
  • The main drawback of the ordered array is its increased insertion time which is O(n) due to the fact that its element has to reordered to maintain the order of array during every insertion whereas the time complexity in the unordered array is only O(1).
  • Considering the above 2 key points and depending on what kind of scenario a developer requires, the appropriate data structure can be used for implementation.

13. Is it possible to import the same class or package twice in Java and what happens to it during runtime?

It is possible to import a class or package more than once, however, it is redundant because the JVM internally loads the package or class only once.

14. In case a package has sub packages, will it suffice to import only the main package? e.g. Does importing of com.myMainPackage.* also import com.myMainPackage.mySubPackage.*?

This is a big NO. We need to understand that the importing of the sub-packages of a package needs to be done explicitly. Importing the parent package only results in the import of the classes within it and not the contents of its child/sub-packages.

15. Will the finally block be executed if the code System.exit(0) is written at the end of try block?

NO. The control of the program post System.exit(0) is immediately gone and the program gets terminated which is why the finally block never gets executed.

16. What do you understand by marker interfaces in Java?

Marker interfaces, also known as tagging interfaces are those interfaces that have no methods and constants defined in them. They are there for helping the compiler and JVM to get run time-related information regarding the objects.

17. Explain the term “Double Brace Initialisation” in Java?

This is a convenient means of initializing any collections in Java. Consider the below example.

In the above example, we see that the stringSets were initialized by using double braces.

  • The first brace does the task of creating an anonymous inner class that has the capability of accessing the parent class’s behavior. In our example, we are creating the subclass of HashSet so that it can use the add() method of HashSet.
  • The second braces do the task of initializing the instances.

Care should be taken while initializing through this method as the method involves the creation of anonymous inner classes which can cause problems during the garbage collection or serialization processes and may also result in memory leaks.

18. Why is it said that the length() method of String class doesn't return accurate results?

  • The length method returns the number of Unicode units of the String. Let's understand what Unicode units are and what is the confusion below.
  • Code Point: This represents an integer denoting a character in the code space.
  • Code Unit: This is a bit sequence used for encoding the code points. In order to do this, one or more units might be required for representing a code point.
  • The code points from the first plane are encoded using one 16-bit code unit
  • The code points from the remaining planes are encoded using two code units.

Now if a string contained supplementary characters, the length function would count that as 2 units and the result of the length() function would not be as per what is expected.

In other words, if there is 1 supplementary character of 2 units, the length of that SINGLE character is considered to be TWO - Notice the inaccuracy here? As per the java documentation, it is expected, but as per the real logic, it is inaccurate.

19. What is the output of the below code and why?

“bit” would have been the result printed if the letters were used in double-quotes (or the string literals). But the question has the character literals (single quotes) being used which is why concatenation wouldn't occur. The corresponding ASCII values of each character would be added and the result of that sum would be printed. The ASCII values of ‘b’, ‘i’, ‘t’ are:

98 + 105 + 116 = 319

Hence 319 would be printed.

20. What are the possible ways of making object eligible for garbage collection (GC) in Java?

First Approach: Set the object references to null once the object creation purpose is served.

Second Approach: Point the reference variable to another object. Doing this, the object which the reference variable was referencing before becomes eligible for GC.

Third Approach: Island of Isolation Approach: When 2 reference variables pointing to instances of the same class, and these variables refer to only each other and the objects pointed by these 2 variables don't have any other references, then it is said to have formed an “Island of Isolation” and these 2 objects are eligible for GC.

21. In the below Java Program, how many objects are eligible for garbage collection?

In the above program, a total of 7 objects will be eligible for garbage collection. Let’s visually understand what's happening in the code.

tricky problem solving interview questions in java

In the above figure on line 3, we can see that on each array index we are declaring a new array so the reference will be of that new array on all the 3 indexes. So the old array will be pointed to by none. So these three are eligible for garbage collection. And on line 4, we are creating a new array object on the older reference. So that will point to a new array and older multidimensional objects will become eligible for garbage collection.

22. What is the best way to inject dependency? Also, state the reason.

There is no boundation for using a particular dependency injection. But the recommended approach is - 

Setters are mostly recommended for optional dependencies injection, and constructor arguments are recommended for mandatory ones. This is because constructor injection enables the injection of values into immutable fields and enables reading them more easily.

23. How we can set the spring bean scope. And what supported scopes does it have?

A scope can be set by an annotation such as the @Scope annotation or the "scope" attribute in an XML configuration file. Spring Bean supports the following five scopes:

  • Global-session

24. What are the different categories of Java Design patterns?

Java Design patterns are categorized into the following different types. And those are also further categorized as 

Structural patterns:

Behavioral patterns:

  • Interpreter
  • Template method/ pattern
  • Chain of responsibility
  • Command pattern
  • Iterator pattern
  • Strategy pattern
  • Visitor pattern

J2EE patterns:

  • MVC Pattern
  • Data Access Object pattern
  • Front controller pattern
  • Intercepting filter pattern
  • Transfer object pattern

Creational patterns:

  • Factory method/Template
  • Abstract Factory

25. What is a Memory Leak? Discuss some common causes of it.

The Java Garbage Collector (GC) typically removes unused objects when they are no longer required, but when they are still referenced, the unused objects cannot be removed. So this causes the memory leak problem. Example - Consider a linked list like the structure below -

tricky problem solving interview questions in java

In the above image, there are unused objects that are not referenced. But then also Garbage collection will not free it. Because it is referencing some existing referenced object. So this can be the situation of memory leak.

Some common causes of Memory leaks are - 

  • When there are Unbounded caches.
  • Excessive page swapping is done by the operating system.
  • Improper written custom data structures.
  • Inserting into a collection object without first deleting it. etc.

26. Assume a thread has a lock on it, calling the sleep() method on that thread will release the lock?

A thread that has a lock won't be released even after it calls sleep(). Despite the thread sleeping for a specified period of time, the lock will not be released.

1. Check if a given string is palindrome using recursion.

/* * Java program to check if a given inputted string is palindrome or not using recursion. */ import java.util.*; public class InterviewBit { public static void main (String args[]) { Scanner s = new Scanner(System.in); String word = s.nextLine(); System.out.println( "Is " +word+ " palindrome? - " +isWordPalindrome(word)); } public static boolean isWordPalindrome (String word) { String reverseWord = getReverseWord(word); //if word equals its reverse, then it is a palindrome if (word.equals(reverseWord)){ return true ; } return false ; } public static String getReverseWord (String word) { if (word == null || word.isEmpty()){ return word; } return word.charAt(word.length()- 1 ) + getReverseWord(word.substring( 0 , word.length() - 1 )); } }

2. Write a Java Program to print Fibonacci Series using Recursion.

In the above code, we are printing the base 2 Fibonacci values 0 and 1. And then based on the length of Fibonacci to be printed, we are using the helper function to print that.

3. Write a Java program to check if the two strings are anagrams.

The main idea is to validate the length of strings and then if found equal, convert the string to char array and then sort the arrays and check if both are equal.

4. Write a Java Program to find the factorial of a given number.

public class FindFactorial { public static void main (String[] args) { int num = 10 ; long factorialResult = 1l ; for ( int i = 1 ; i <= num; ++i) { factorialResult *= i; } System.out.println( "Factorial: " +factorialResult); } }

5. Given an array of non-duplicating numbers from 1 to n where one number is missing, write an efficient java program to find that missing number.

Idea is to find the sum of n natural numbers using the formula and then finding the sum of numbers in the given array. Subtracting these two sums results in the number that is the actual missing number. This results in O(n) time complexity and O(1) space complexity.

6. Write a Java Program to check if any number is a magic number or not. A number is said to be a magic number if after doing sum of digits in each step and inturn doing sum of digits of that sum, the ultimate result (when there is only one digit left) is 1.

Example, consider the number:

  • Step 1: 163 => 1+6+3 = 10
  • Step 2: 10 => 1+0 = 1 => Hence 163 is a magic number

7. Write a Java program to create and throw custom exceptions.

We have created the exception class named with CustomException and called the base exception constructor with the error message that we want to print. And to avoid handling exceptions in the main method, we have used the throws keyword in the method declaration.

8. Write a Java program to reverse a string.

In the above code, we are storing the last character from the string to the first and the first value to the last in the output character array. And doing the same thing in the loop for the remaining 2nd to n-1 characters. This is how the string will be reversed.

9. Write a Java program to rotate arrays 90 degree clockwise by taking matrices from user input.

In the above code, for rotating the matrix to  90 degrees we are first transposing the matrix so the row becomes the column. And after that, we are reversing each row in the matrix. So this is how the matrix got rotated.

10. Write a java program to check if any number given as input is the sum of 2 prime numbers.

18 = 13 + 5 18 = 11 + 7

In the above code, for any number n , we find all the 2 pairs of numbers that are added together resulting in n . And each checking number if it is prime. If it is prime then we are printing that.

11. Write a Java program for solving the Tower of Hanoi Problem.

In the above code we are first moving the n-1 disk from Tower A to Tower B , then moving that nth disk from Tower A to Tower C , and finally, the remaining n-1 disk from Tower B to Tower C . And we are doing this recursively for the n-1 disk.

12. Implement Binary Search in Java using recursion.

In the above code, we are finding the middle element each time and checking if the element is in the middle or not. If it is not, then we check on which side from the middle it exists. And Recursively searching on the particular subarray. So this way we are reducing the search space by 2 every time. So the search time is very low.

1. Conclusion

Java is one of the simple high-level languages that provides powerful tools and impressive standards required for application development. It was also one of the first languages to provide amazing threading support for tackling concurrency-based problems. The easy-to-use syntax and the built-in features of Java combined with the stability it provides to applications are the main reasons for this language has ever-growing usage in the software community.

Interview Preparation Resources

  • How to Become a Java Developer?
  • How much does a Java Developer earn in India?
  • Java Projects
  • Java Programming Questions for Interview
  • Java 8 Interview Questions
  • Java String Interview Questions
  • Spring Interview Questions
  • Hibernate Interview Questions
  • Java Collections Interview Questions
  • Array Interview Questions
  • Design Patterns Interview Questions
  • Multithreading Interview Questions
  • Java Tutorial
  • Advance Java MCQ
  • Difference Between C++ and Java
  • Difference Between C and Java
  • Difference Between Java and Javascript
  • Hashmap vs Hashtable in Java
  • Kotlin Vs Java
  • Java Vs Python
  • Features of Java 9
  • Java 8 Features
  • Java Frameworks
  • Java Developer Skills
  • Java 11 Features
  • Additional Technical Interview Questions
  • JAVA SE Download

Coding Problems

What is the output of the below code?

What component does the task of bytecode to machine code conversion?

Which of the following happens when the garbage collection process kicks off during the execution of the thread?

What is the functionality of Class.getInstance() ?

What is the output of the below piece of code?

What is the output of the following code?

Which of the following is the functionality of the java interpreter?

What is the component used for compiling, debugging, and executing java programs?

When an object has its own lifecycle and its child object cant belong to another parent object, what is it called?

  • Privacy Policy

instagram-icon

  • Practice Questions
  • Programming
  • System Design
  • Fast Track Courses
  • Online Interviewbit Compilers
  • Online C Compiler
  • Online C++ Compiler
  • Online Java Compiler
  • Online Javascript Compiler
  • Online Python Compiler
  • Interview Preparation
  • Sql Interview Questions
  • Python Interview Questions
  • Javascript Interview Questions
  • Angular Interview Questions
  • Networking Interview Questions
  • Selenium Interview Questions
  • Data Structure Interview Questions
  • Data Science Interview Questions
  • System Design Interview Questions
  • Hr Interview Questions
  • Html Interview Questions
  • C Interview Questions
  • Amazon Interview Questions
  • Facebook Interview Questions
  • Google Interview Questions
  • Tcs Interview Questions
  • Accenture Interview Questions
  • Infosys Interview Questions
  • Capgemini Interview Questions
  • Wipro Interview Questions
  • Cognizant Interview Questions
  • Deloitte Interview Questions
  • Zoho Interview Questions
  • Hcl Interview Questions
  • Highest Paying Jobs In India
  • Exciting C Projects Ideas With Source Code
  • Top Java 8 Features
  • Angular Vs React
  • 10 Best Data Structures And Algorithms Books
  • Best Full Stack Developer Courses
  • Best Data Science Courses
  • Python Commands List
  • Data Scientist Salary
  • Maximum Subarray Sum Kadane’s Algorithm
  • Python Cheat Sheet
  • C++ Cheat Sheet
  • Javascript Cheat Sheet
  • Git Cheat Sheet
  • Java Cheat Sheet
  • Data Structure Mcq
  • C Programming Mcq
  • Javascript Mcq

1 Million +

10 Tricky Programming Questions to Ace Your Java Interview

Team CodeQuotient / June 9, 2022 / Software Engineering Bootcamp

Top-10-Tricky-Java-Programming-Interview-Questions-You-Must-Know

If you are preparing for a Java job interview, you must be familiar with these tricky programming questions. Every interview usually comes with tricky questions that trick candidates into thinking either too much or not at all.

With over 45 billion active virtual machines globally , Java is one of the most popular programming languages in the world. It is the number one development language for microservices and is the most-used language for DevOps, AI, VR, Big Data, Continuous Integration, Analytics, Mobile, Chatbots, and much more.

With over 9 million active Java developers globally , the demand for talent in this domain is at an all-time high. As per Mercer, one of the global leaders in talent assessment, the role of a Java developer is one of the most in-demand roles in 2022, thanks to the ever-increasing adoption of Java in multiple domains, devices, and organisations.

However, clearing an interview for this job role isn’t all that easy, given that most interview panellists tend to throw tricky questions at the candidates to find the best talent for the job. Let’s see some of those.

Java Programming – Tricky Interview Questions

Java-Programming-Tricky-Interview-Questions

Let us show you the ten most tricky Java programming questions you can expect in an interview, with solutions.

1. What will the following Java program print?

public class Test { public static void main(String[] args) {

System.out.println(Math.min(Double.MIN_VALUE, 0.0d)); } }

This question is tricky because, unlike the Integer class, where the MIN VALUE is negative, the Double class’s MAX VALUE and MIN VALUE are both positive integers. Double.MIN VALUE is 2^(-1074), a double constant with the least magnitude of all double values.

Because of Double, this program will print 0.0 instead of the obvious answer. The value of MIN VALUE is greater than zero.

If you’d like to understand the difference between a compiler and an interpreter in Java, Click here .

2. What will happen if you put the return statement or System.exit () on the ‘try‘ or ‘catch‘ block? Will the ‘finally’ block execute?

Many experienced Java programmers think the ‘finally’ block will always execute. However, that reasoning is challenged here by putting a return statement in the ‘try’ or ‘catch’ block or calling System.exit() from the ‘try’ or ‘catch’ block.

The solution for this mind-bender is that the ‘finally’ block will execute successfully, even if you put a return statement in the ‘try’ or ‘catch’ block. However, the ‘finally’ block will fail to execute if you call System.exit() from the ‘try’ or ‘catch’ block.

3. Can you override a private or static method in Java?

Method overriding is always an excellent topic to confuse developers. You cannot override a static method in Java. It will hide the superclass method if you create an identical method with the same return type and method arguments as the ones in the child class. This is also known as method hiding.

Likewise, overriding a private method in the subclass is impossible as it is not accessible there. As a workaround, you can create a new private method with the same name in the child class.

If you’re new to software development and overwhelmed with new terms, here are the 19 most important terms you should know!

4. What will the expression 1.0 / 0.0 return? Will it throw an exception or any compile-time errors?

It will compile successfully and not throw ArithmeticException. It will instead return Double.Infinity.

5. Does Java support multiple inheritances?

This is the most challenging problem in Java. Interviewers frequently argue that since C++ can allow multiple direct inheritances, why can’t Java? 

Because Java supports multiple inheritances of Type by enabling one interface to extend other interfaces, the answer is considerably more complicated than it appears. Java does not allow multiple inheritances of implementation.

6. What will happen if we put a key object in a HashMap already there?

HashMap does not allow duplicate keys, so putting the same key again will overwrite the original mapping. The same key will generate the same hashcode and end up at the same bucket position. Each bucket contains a linked list of maps.

This is an entry object that has both a Key and a Value. Java will compare each entry’s Key object to this new key using the equals() method, and if the comparison returns true, the value object in that entry will be replaced by the new value.

7. What does the following Java program print?

public class Test { public static void main(String[] args) throws Exception { char[] chars = new char[] {‘\u0097’}; String str = new String(chars); byte[] bytes = str.getBytes(); System.out.println(Arrays.toString(bytes)); } }

This question is particularly tricky because this program’s output depends on the operating system and locale. On a Windows XP with the US locale, the above program prints 63, but if you run this program on Linux or Solaris, you will get different values.

8. If a method throws NullPointerException in the superclass, can we override it with a method that throws RuntimeException?

Yes, you can throw a superclass of RuntimeException in overridden method, but you can not do that if it’s a checked Exception.

9. What is the difference between CyclicBarrier and CountDownLatch in Java?

You can reuse CyclicBarrier even if the Barrier is broken, but you can not reuse CountDownLatch in Java.

10. Can you access a non-static variable in the static context?

No, you cannot access a non-static variable from the static context in Java, as it will give a compile-time error.

With these answers in your arsenal, you are well-equipped to handle some of the trickiest questions any Java interviewer can throw at you. If you are a new learner in the field of programming or want to upskill and take your career to the next level, CodeQuotient offers their flagship SuperCoders Program – a full-stack development internship. It focuses on in-depth, project-based practical learning to unlock the supreme programmer inside you!

Get UGC Approved, BCA Degree And Earn While You Do That

Join CodeQuotient's Under-Graduate Program In Software Engineering

Get Paid Internship with Our Hiring Partners to Sponsor Your Fees

100% Placement Assistance

You will also like:

  • Common C++ Questions to Know for Tech Interviews
  • 10+ Coding Interview Questions Every Programmer Must Know
  • Critical Tips To Ace Cognizant Coding Questions
  • 6 Steps to Cracking ANY Coding Interview That No One Told You
  • The 10 Most Common Accenture Coding Questions

Your email address will not be published. Required fields are marked *

Recent Posts

The reality of us student visas: what you need to know, what is the difference between bcs and bca course, bca for pcb students: why should you consider this degree.

  • Distance BCA Degree Course vs Traditional On-Campus BCA
  • Programming Languages That a Software Engineering Graduate Must Know
  • How to Ace the Infosys Off-Campus Recruitment Drive
  • Exploring the Best Software Engineer Graduate Programs
  • CEO's Corner
  • CodeQuotient School of Technology
  • Engineering High-Performing Teams
  • Software Engineering Bootcamp
  • Uncategorized

You May Also Like .

Reality of US student visas

©️ 2024. All Rights Reserved.

About   |   Blog   |  Contact   |  Privacy Policy   |  Terms and Conditions

tricky problem solving interview questions in java

Recent Posts

Why are Certifications important for Professionals?

Why are Certifications important for Professionals?

by Abdul Wasay

In today's competitive tech landscape, constantly upgrading your skillset is crucial for career advancement. While experience reigns supreme, certifications can be that extra edge that sets you apart from the crowd. Whether you're a seasoned developer in the USA or a...

5 Reasons Why Anyone Can Learn to Code

5 Reasons Why Anyone Can Learn to Code

by Editorial Team

Coding has become an essential skill in today’s digital age, opening doors to countless opportunities across various industries. Many people, however, still hold the belief that coding is a complex skill reserved for tech geniuses. This couldn’t be further from the...

Land Your Dream Developer Job in Months with SkillReactor

Land Your Dream Developer Job in Months with SkillReactor

Are you a coder looking to break into the tech industry or upskill to land your dream developer job? Then look no further than SkillReactor! This article will explore how our unique EdTech platform can empower you to achieve your coding goals faster than traditional...

Thinking of moving to a new job? Here’s how to resign appropriately

Thinking of moving to a new job? Here’s how to resign appropriately

by Amanda Kavanagh

By Amanda Kavanagh While many of us may harbour fantasies about quitting a job with panache — the 1998 film Half Baked comes to mind — our long-term career view usually prevents drastic action.  No matter how long you’ve worked somewhere, chances are you want to...

Java Coding Interview Questions

by Abdul Wasay | Mar 25, 2024

Java Coding Interview Questions You Need to Know

Did you know that Java is one of the world’s most widely used programming languages? It powers countless applications and systems, from enterprise software to Android apps. As a result, Java coding interview questions have become a crucial part of the hiring process for Java developers . If you’re aspiring to land a job as a Java developer, you must have a strong grasp of these questions.

tricky problem solving interview questions in java

Key Takeaways:

  • Mastering Java coding interview questions is crucial for Java developers aiming to excel in interviews.
  • A strong understanding of Java coding interview questions increases your chances of success.
  • Java is widely used in various industries, making it a valuable skill for developers.
  • Preparing for common Java coding interview questions helps build your technical skills.
  • Stay updated with the latest Java features and practices to stand out in interviews.

Common Java Coding Interview Questions

Java Coding Interview

This section will explore some of the most commonly asked Java coding interview questions. These questions cover fundamental concepts that every Java developer should be familiar with. Understanding and preparing for these questions can greatly increase your chances of success in your Java coding interviews.

Write a program that prints the numbers from 1 to 100. But for multiples of three, print “Fizz” instead of the number, and for the multiples of five, print “Buzz”. For numbers that are multiples of both three and five, print “FizzBuzz”.

Palindrome Check

Write a function to determine if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward.

Fibonacci Series

Create a program that generates the Fibonacci series up to a given number of terms. The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones.

Reverse a String

Write a function that reverses a given string. For example, if the input is “Hello”, the output should be “olleH”.

Find the Missing Number

Given an array of integers from 1 to n, one number is missing. Write a function to find the missing number in the array.

These are just a few examples of common Java coding interview questions. Practicing and familiarizing yourself with various questions to build your confidence and problem-solving skills is important.

tricky problem solving interview questions in java

QuestionDescriptionSample InputSample Output
FizzBuzzPrint numbers from 1 to 100, replacing multiples of three with “Fizz”, multiples of five with “Buzz”, and multiples of both three and five with “FizzBuzz”.N/A1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, …
Palindrome CheckDetermine if a given string is a palindrome.“racecar”true
Fibonacci SeriesGenerate the Fibonacci series up to a given number of terms.50, 1, 1, 2, 3
Reverse a StringReverse a given string.“world”“dlrow”
Find the Missing NumberFind the missing number in an array of integers from 1 to n.[1, 2, 4, 5]3

Core Java Interview Questions

When interviewing candidates for Java developer positions, assessing their understanding of core Java principles is crucial. Core Java interview questions focus on the foundational concepts of the Java programming language, ensuring that candidates possess a strong grasp of the fundamentals. This section explores essential core Java interview questions that evaluate a candidate’s knowledge and expertise in key areas.

1. What is the difference between JDK, JRE, and JVM?

The Java Development Kit (JDK) is a software development environment that provides tools, libraries, and documentation for developing Java applications. The Java Runtime Environment (JRE) is an implementation of the Java Virtual Machine (JVM) that allows you to run Java applications. The Java Virtual Machine (JVM) is an abstract machine that interprets Java bytecode, enabling platform independence by translating the bytecode into machine-specific instructions.

2. Explain the key features of object-oriented programming in Java.

Encapsulation: Bundling data and methods within a class to hide implementation details. Inheritance: Allowing classes to inherit attributes and behaviors from other classes. Polymorphism: Using a single interface to represent multiple forms. Abstraction: Providing a simplified view of complex systems by defining classes based on common characteristics.

It is essential to assess a candidate’s understanding of these core Java concepts and ability to apply them in real-world scenarios. By evaluating their responses to these interview questions, you can gauge the depth of their knowledge and experience with Java programming.

tricky problem solving interview questions in java

The next section will explore advanced Java coding interview questions that challenge candidates with complex programming problems and advanced Java concepts.

tricky problem solving interview questions in java

Advanced Java Coding Interview Questions

Aspiring Java developers who wish to stand out in interviews must be familiar with the common Java coding interview questions and prepared for more advanced ones. This section presents a collection of challenging Java coding questions that require a deep understanding of advanced Java concepts and principles.

1. Explain the concept of multithreading in Java.

Multithreading is the ability of a Java program to execute multiple threads concurrently, allowing for parallel task execution. It enables efficient utilization of system resources and improves overall program performance. However, managing multiple threads requires synchronization and coordination to avoid issues such as race conditions and deadlocks.

2. What are the differences between method overriding and method overloading?

Method overriding occurs when a subclass defines a method with the same name and signature as an inherited method from its superclass. The overriding method provides a different implementation, replacing the behavior of the superclass method for objects of the subclass. Method overloading, on the other hand, involves defining multiple methods with the same name but different parameters within a class. Overloaded methods enable flexibility by allowing different ways to invoke the same method based on the number and types of arguments passed.

3. Explain the concept of generics in Java.

Generics in Java allow classes and methods to be parameterized by type, providing compile-time type safety. Using generics enables the creation of reusable code independent of specific types, enhancing code readability and maintainability. Generics, such as ArrayList and HashMap, are commonly used with collections to enforce type constraints and enable the compiler to detect type mismatches at compile time.

Tip: When dealing with generics, it is important to specify the appropriate type parameters to ensure type safety and prevent runtime errors.

4. Describe the concept of exception handling in Java.

Exception handling in Java allows programmers to handle and recover from exceptional conditions or errors that may occur during program execution. It involves the use of try-catch blocks to catch and handle exceptions. The catch block contains code to handle specific types of exceptions, providing an alternative course of action when an exception occurs. Additionally, the final block ensures that certain code is executed regardless of whether an exception is thrown.

5. What are the advantages and disadvantages of using an abstract class in Java?

An abstract class in Java serves as a blueprint from which other classes can inherit. It provides a common interface and defines methods and variables that subclasses can implement or override. The advantages of using an abstract class include promoting code reusability, enforcing a consistent structure across related classes, and allowing for future extension through subclassing. However, one disadvantage is that Java does not allow multiple inheritance, so a class can only inherit from one abstract class.

AdvantagesDisadvantages
Enables code reusabilityJava does not allow multiple inheritance
Defines common methods and variables for subclasses
Provides a consistent structure across related classes
Allows for future extension through subclassing

By familiarizing themselves with these advanced Java coding interview questions and understanding the underlying concepts, aspiring Java developers can enhance their problem-solving skills and demonstrate their proficiency in advanced Java programming.

Java Programming Interview Questions

When preparing for a Java programming interview, it’s important to have a solid understanding of the key concepts and techniques that are commonly tested. This section focuses on specific areas of Java programming that you should be prepared to discuss and provides examples of interview questions related to these topics.

Object-Oriented Programming

Object-oriented programming (OOP) is a fundamental aspect of Java programming. Interviewers often ask questions to assess your understanding of OOP principles and how they are implemented in Java. Here are some common interview questions related to OOP:

  • Explain the concept of inheritance and how it is used in Java.
  • What are abstract classes and interfaces, and what is their difference?
  • How does polymorphism work in Java? Provide an example.

Exception Handling

Exception handling is an essential part of Java programming. During an interview, you may be asked how to handle exceptions effectively. Here are a few examples of interview questions related to exception handling:

  • Explain the difference between checked and unchecked exceptions in Java.
  • What is the purpose of the try-catch-finally block? Provide an example.
  • How can you create your custom exceptions in Java?

Multithreading

Understanding multithreading is crucial for developing efficient and responsive Java applications. Interviewers may ask questions about multithreading to assess your knowledge in this area. Here are some common interview questions about multithreading:

  • Explain the difference between a thread and a process.
  • How can you create a new thread in Java? Provide an example.
  • What are the advantages and disadvantages of using multithreading in Java?

By familiarizing yourself with these Java programming interview questions, you can feel more confident and prepared for your next interview. Remember to practice answering these questions and be ready to explain your thought process and demonstrate your problem-solving skills.

tricky problem solving interview questions in java

“Having a strong understanding of object-oriented programming, exception handling, and multithreading in Java is crucial for success in coding interviews.”

Tricky Java Coding Interview Questions

In a Java coding interview, candidates often encounter tricky questions that test their problem-solving skills and critical thinking ability. These questions go beyond the basics and require a deep understanding of Java concepts. To help you prepare for these challenging questions, we have highlighted some examples below and insights on how to approach them.

Question 1: Palindrome Check

Determine whether a given string is a palindrome or not. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward.

Example: Input: “racecar” Output: true Input: “hello” Output: false

To solve this question, you can use two pointers, one starting from the beginning of the string and the other from the end. Compare the characters at each position until the pointers meet. If all the characters match, the string is a palindrome.

Question 2: Find the Missing Number

Given an array of integers from 1 to n with one missing number, find the missing number.

Example: Input: [1, 2, 4, 5, 6] Output: 3

To solve this question, you can calculate the expected sum of all the numbers from 1 to n using the formula (n * (n + 1)) / 2. Then, subtract the sum of the given array from the expected sum to find the missing number.

Question 3: Reverse Linked List

Reverse a singly linked list.

Example: Input: 1 -> 2 -> 3 -> 4 -> 5 Output: 5 -> 4 -> 3 -> 2 -> 1

You can use three-pointers to reverse the links between the nodes to solve this question. Traverse through the linked list and update the next pointers accordingly until you reach the end of the list.

These are just a few examples of tricky Java coding interview questions. By practicing and understanding the underlying concepts, you can improve your problem-solving skills and approach these questions with confidence.

Best Java Coding Interview Questions

Are you preparing for a Java coding interview? This section has curated a list of the best questions for you. These questions cover a wide range of concepts and difficulty levels, ensuring you comprehensively understand Java coding requirements.

Check out the following questions to improve your interview preparation:

  • Question 1: Explain the difference between StringBuffer and StringBuilder. Answer: StringBuffer and StringBuilder are both used to manipulate strings in Java. However, there is a significant difference between them. StringBuffer is synchronized and thread-safe, while StringBuilder is not synchronized but faster. It is important to understand when to use each one based on your requirements.
  • Question 2: What is the difference between a deep and shallow copy? Answer: In Java, a deep copy creates a completely independent copy of an object, including all its nested objects. On the other hand, a shallow copy creates a new object that references the same nested objects as the original object. Understanding the differences between these two copy types is crucial for avoiding unexpected behavior in your code.
  • Question 3: How does Java handle memory management? Explain the concept of garbage collection. Answer: Java uses automatic memory management through a process called garbage collection. Garbage collection identifies and frees up memory that the program no longer uses. This automated memory management relieves developers from manual memory allocation and deallocation, making Java a memory-friendly language.

Mastering these Java coding interview questions will enhance your technical skills and boost your confidence during interviews. In the next section, we will examine some more intriguing questions.

Java Interview Questions for Experienced Developers

Experienced Java developers stand out from the crowd with their depth of knowledge and practical experience. When it comes to interviews, these professionals often face different questions that delve deeper into their expertise. This section is designed to address those specific questions and provide valuable insights for experienced developers.

Here, we will explore advanced concepts and scenarios experienced Java developers will likely encounter during interviews. By understanding and preparing for these questions, you can showcase your proficiency in design patterns, performance optimization, architectural principles, and more.

Sample Questions for Experienced Java Developers

  • How would you optimize the performance of a Java application?
  • Can you explain the differences between checked and unchecked exceptions?
  • Discuss the advantages and disadvantages of using multiple inheritance in Java.
  • Explain the purpose and usage of the Java Volatile keyword.
  • Describe the principles of the Model-View-Controller (MVC) architectural pattern and its implementation in Java.
Experienced Java developers are expected to have a deep understanding of the programming language and its intricacies. Interviewers may ask questions that require practical knowledge, problem-solving skills, and the ability to make architectural decisions.

To further assist you in your preparations, here is a sample table comparing the skills and knowledge required for entry-level Java interviews versus experienced Java interviews:

Skills/KnowledgeEntry-Level Java InterviewsExperienced Java Interviews
Core Java✔️✔️
Object-Oriented Programming✔️✔️
Design Patterns✔️
Concurrency✔️
Performance Optimization✔️
Architectural Principles✔️

Remember, the depth of your answers and practical examples of projects you’ve worked on will be crucial in impressing interviewers. Showcase your experience, problem-solving abilities, and the value you can bring as an experienced Java developer.

Top Java Coding Interview Questions

Java coding interview questions are an essential part of the interview process for aspiring Java developers. In this section, we will discuss the top Java coding interview questions that hiring managers frequently ask. By understanding and preparing for these questions, candidates can increase their chances of success in Java coding interviews.

1. What is the difference between ArrayList and LinkedList in Java?

2. Explain the concept of object-oriented programming (OOP) and its main principles.

3. What is the difference between equals() and == in Java?

4. Explain the concept of multithreading in Java and how it works.

5. What is the purpose of the “final” keyword in Java?

6. What are checked and unchecked exceptions in Java?

7. Explain the concept of inheritance in Java and how it is implemented.

8. What is the role of the “static” keyword in Java?

“In Java, static keyword is used to create variables and methods that belong to the class, rather than instances of the class. Static members can be accessed directly using the class name, without creating an object. This can be useful for utility methods or variables that need to be shared across all instances of a class.”

9. What is method overloading in Java?

10. Explain the concept of exception handling in Java and how it helps write robust code.

To summarize, being well-prepared for Java coding interviews can significantly improve your chances of landing a job as a Java developer. By familiarizing yourself with these top Java coding interview questions and practicing your problem-solving skills, you can confidently tackle any coding challenge that comes your way.

Comparison between ArrayList and LinkedList in Java

ArrayListLinkedList
Implements the List interface.Implements the List and Deque interfaces.
Uses a dynamic array to store elements.Uses a linked list to store elements.
Provides efficient random access and modification of elements.Provides efficient insertion and deletion of elements.
Slower performance for insertion and deletion of elements.Fast performance for insertion and deletion of elements.
Requires more memory when compared to LinkedList.Requires less memory when compared to ArrayList.

Mastering Java coding interview questions is essential for Java developers looking to excel in their interviews. These questions not only assess a candidate’s technical knowledge but also their problem-solving and critical-thinking skills. By thoroughly studying and practicing these questions, candidates can enhance their understanding of fundamental Java concepts and confidently tackle interview challenges.

Preparing for Java coding interviews involves a combination of theoretical knowledge and practical application. It is important to have a strong understanding of core Java principles and advanced Java concepts. By familiarizing themselves with various Java programming topics, candidates can demonstrate their versatility and ability to adapt to different coding scenarios.

Furthermore, becoming well-versed in Java coding interview questions can significantly boost a candidate’s confidence during the interview process. By knowing how to approach and solve different coding problems, candidates can effectively showcase their technical skills and demonstrate their value to potential employers.

What are Java coding interview questions?

Java coding interview questions assess a candidate’s knowledge and proficiency in Java programming. They cover various aspects of Java, including core concepts, object-oriented programming, data structures, algorithms, and more.

Why are Java coding interview questions important?

Java coding interview questions are important because they help hiring managers evaluate a candidate’s technical skills and problem-solving abilities. Interviewers can assess a candidate’s understanding of Java fundamentals, coding practices, and ability to apply Java concepts to real-world scenarios by asking specific Java coding questions.

What are some common Java coding interview questions?

Common Java coding interview questions include topics such as Java basics (data types, loops, conditionals), object-oriented programming (inheritance, polymorphism), Java collections (ArrayList, HashMap), exception handling, multithreading, and more.

What are core Java interview questions?

Core Java interview questions focus on the fundamental concepts of the Java programming language. They assess a candidate’s knowledge of Java syntax, data types, operators, control flow, classes and objects, inheritance, interfaces, and basic Java libraries.

What are advanced Java coding interview questions?

Advanced Java coding interview questions are designed to evaluate a candidate’s in-depth understanding of complex Java concepts and advanced programming techniques. These questions often cover advanced topics such as multithreading, Java Generics, Java streams, concurrency, design patterns, and performance optimization.

What are Java programming interview questions?

Java programming interview questions focus on assessing a candidate’s ability to apply Java programming concepts to solve specific problems. These questions cover object-oriented programming, exception handling, data structures, algorithms, database connectivity, and Java frameworks.

What are some tricky Java coding interview questions?

Tricky Java coding interview questions are designed to challenge a candidate’s problem-solving abilities and critical thinking skills. They often involve complex scenarios, edge cases, or unexpected behavior of Java language features. Candidates must analyze the problem, consider different approaches, and provide the most appropriate solution.

What are the best Java coding interview questions?

The best Java coding interview questions cover a wide range of Java concepts and difficulty levels. These questions effectively evaluate a candidate’s understanding of core Java principles, ability to write clean and efficient code, and problem-solving skills. They provide a comprehensive assessment of a candidate’s Java programming proficiency.

What are Java interview questions for experienced developers?

Java interview questions for experienced developers are specifically tailored to evaluate their advanced knowledge and practical experience with Java programming. These questions may delve into advanced Java topics, design patterns, database integration, performance tuning, debugging techniques, and frameworks commonly used in enterprise-level applications.

What are the top Java coding interview questions?

The top Java coding interview questions are hiring managers’ most frequently asked questions. These questions cover a variety of Java concepts and are specifically designed to assess a candidate’s problem-solving skills, coding techniques, familiarity with Java libraries/frameworks, and ability to write efficient and maintainable code.

AI Proof Your Career

Logo 1

Secure Your Lifetime 40% Discount for Code Learning. Use code OFF40

Review these 50 questions to crack your Java programming interview

Review these 50 questions to crack your Java programming interview

by javinpaul

A list of frequently asked Java questions from programming job interviews.

cA9-wkkWif9KjVOo09g1D5s5OiE8KskLLfa-

Hello, everybody! Over the past few years, I have been sharing a lot of Java Interview questions and discussion individually. Many of my readers have requested that I bring them together so that they can have them in the same spot. This post is the result of that.

This article contains more than 50 Java Interview questions covering all important topics like Core Java fundamentals, Java Collection Framework , Java Multithreading and Concurrency , Java IO , JDBC , JVM Internals , Coding Problems , Object-Oriented programming , etc.

The questions are also picked up from various interviews and they are, by no means, very difficult. You might have seen them already in your phone or face-to-face round of interviews.

The questions are also very useful to review important topics like multithreading and collections. I have also shared some useful resources for further learning and improvement like The Complete Java MasterClass to brush up and fill gaps in your Java skills.

So what are we waiting for? Here is the list of some of the most frequently asked Java questions in interviews for both beginner and experienced Java developers.

50+ Java Interview Questions for 2 to 3 years Experienced Programmers

So, without wasting any more of your time, here is my list of some of the frequently asked Core Java Interview Question s for beginner programmers. This list focuses on beginners and less experienced devs, like someone with 2 to 3 years of experience in Java.

1) How does Java achieve platform independence? ( answer ) hint: bytecode and Java Virtual Machine

2) What is ClassLoader in Java? ( answer ) hint: part of JVM that loads bytecodes for classes. You can write your own.

3) Write a Java program to check if a number is Even or Odd? ( answer ) hint: you can use bitwise operator, like bitwise AND, remember, even the number has zero at the end in binary format and an odd number has 1 in the end.

4) Difference between ArrayList and HashSet in Java? ( answer ) hint: all differences between List and Set are applicable here, e.g. ordering, duplicates, random search, etc. See Java Fundamentals: Collections by Richard Warburton to learn more about ArrayList, HashSet and other important Collections in Java.

ueOwMAd5GBdw4blCOpEBpOdMOtcs-et6nPYA

5) What is double checked locking in Singleton? ( answer ) hint: two-time check whether instances is initialized or not, first without locking and second with locking.

6) How do you create thread-safe Singleton in Java? ( answer ) hint: many ways, like using Enum or by using double-checked locking pattern or using a nested static class.

7) When to use the volatile variable in Java? ( answer ) hint: when you need to instruct the JVM that a variable can be modified by multiple threads and give hint to JVM that does not cache its value.

8) When to use a transient variable in Java? ( answer ) hint: when you want to make a variable non-serializable in a class, which implements the Serializable interface. In other words, you can use it for a variable whose value you don’t want to save. See The Complete Java MasterClass to learn about transient variables in Java.

9) Difference between the transient and volatile variable in Java? ( answer ) hint: totally different, one used in the context of serialization while the other is used in concurrency.

10) Difference between Serializable and Externalizable in Java? ( answer ) hint: Externalizable gives you more control over the Serialization process.

11) Can we override the private method in Java? ( answer ) hint: No, because it’s not visible in the subclass, a primary requirement for overriding a method in Java.

12) Difference between Hashtable and HashMap in Java? ( answer ) hint: several but most important is Hashtable , which is synchronized, while HashMap is not. It's also legacy and slow as compared to HashMap .

13) Difference between List and Set in Java? ( answer ) hint: List is ordered and allows duplicate. Set is unordered and doesn't allow duplicate elements.

14) Difference between ArrayList and Vector in Java ( answer ) hint: Many, but most important is that ArrayList is non-synchronized and fast while Vector is synchronized and slow. It's also legacy class like Hashtable .

15) Difference between Hashtable and ConcurrentHashMap in Java? ( answer ) hint: more scalable. See Java Fundamentals: Collections by Richard Warburton to learn more.

16) How does ConcurrentHashMap achieve scalability? ( answer ) hint: by dividing the map into segments and only locking during the write operation.

17) Which two methods you will override for an Object to be used as Key in HashMap ? ( answer ) hint: equals and hashcode

18) Difference between wait and sleep in Java? ( answer ) hint: The wait() method releases the lock or monitor, while sleep doesn't.

19) Difference between notify and notifyAll in Java? ( answer ) hint: notify notifies one random thread is waiting for that lock while notifyAll inform to all threads waiting for a monitor. If you are certain that only one thread is waiting then use notify , or else notifyAll is better. See Threading Essentials Mini-Course by Java Champion Heinz Kabutz to learn more about threading basics.

20) Why you override hashcode, along with equals() in Java? ( answer ) hint: to be compliant with equals and hashcode contract, which is required if you are planning to store your object into collection classes, e.g. HashMap or ArrayList .

21) What is the load factor of HashMap means? ( answer ) hint: The threshold that triggers the re-sizing of HashMap is generally 0.75, which means HashMap resize itself if it's 75 percent full.

22) Difference between ArrayList and LinkedList in Java? ( answer ) hint: same as an array and linked list, one allows random search while other doesn't. Insertion and deletion easy on the linked list but a search is easy on an array. See Java Fundamentals: Collections , Richard Warburton’s course on Pluralsight, to learn more about essential Collection data structure in Java.

23) Difference between CountDownLatch and CyclicBarrier in Java? ( answer ) hint: You can reuse CyclicBarrier after the barrier is broken but you cannot reuse CountDownLatch after the count reaches to zero.

24) When do you use Runnable vs Thread in Java? ( answer ) hint: always

25) What is the meaning of Enum being type-safe in Java? ( answer ) hint: It means you cannot assign an instance of different Enum type to an Enum variable. e.g. if you have a variable like DayOfWeek day then you cannot assign it value from DayOfMonth enum.

26) How does Autoboxing of Integer work in Java? ( answer ) hint: By using the valueOf() method in Java.

27) Difference between PATH and Classpath in Java? ( answer ) hint: PATH is used by the operating system while Classpath is used by JVM to locate Java binary, e.g. JAR files or Class files. See Java Fundamentals: The Core Platform to learn more about PATH , Classpath , and other Java environment variable.

io-lPE67oMG1oBh204LvPm61t7kAcLFvp-B6

28) Difference between method overloading and overriding in Java? ( answer ) hint: Overriding happens at subclass while overloading happens in the same class. Also, overriding is a runtime activity while overloading is resolved at compile time.

29) How do you prevent a class from being sub-classed in Java? ( answer ) hint: just make its constructor private

30) How do you restrict your class from being used by your client? ( answer ) hint: make the constructor private or throw an exception from the constructor

31) Difference between StringBuilder and StringBuffer in Java? ( answer ) hint: StringBuilder is not synchronized while StringBuffer is synchronized.

32) Difference between Polymorphism and Inheritance in Java? ( answer ) hint: Inheritance allows code reuse and builds the relationship between class, which is required by Polymorphism, which provides dynamic behavior. See Java Fundamentals: Object-Oriented Design to learn more about OOP features.

33) Can we override static method in Java? ( answer ) hint: No, because overriding resolves at runtime while static method call is resolved at compile time.

34) Can we access the private method in Java? ( answer ) hint: yes, in the same class but not outside the class

35) Difference between interface and abstract class in Java? ( answer ) hint: from Java 8 , the difference is blurred. However, a Java class can still implement multiple interfaces but can only extend one class.

36) Difference between DOM and SAX parser in Java? ( answer ) hint: DOM loads whole XML File in memory while SAX doesn’t. It is an event-based parser and can be used to parse a large file, but DOM is fast and should be preferred for small files.

37) Difference between throw and throws keyword in Java? ( answer ) hint: throws declare what exception a method can throw in case of error but throw keyword actually throws an exception. See Java Fundamentals: Exception Handling to learn more about Exception handling in Java.

QSqKD-b97Dr36kViV1eTdvqNVNgdZRp52D7n

38) Difference between fail-safe and fail-fast iterators in Java? ( answer ) hint: fail-safe doesn’t throw ConcurrentModificationException while fail-fast does whenever they detect an outside change on the underlying collection while iterating over it.

39) Difference between Iterator and Enumeration in Java? ( answer ) hint: Iterator also gives you the ability to remove an element while iterating while Enumeration doesn’t allow that.

40) What is IdentityHashMap in Java? ( answer ) hint: A Map , which uses the == equality operator to check equality instead of the equals() method.

41) What is the String pool in Java? ( answer ) hint: A pool of String literals. Remember it's moved to heap from perm gen space in JDK 7.

42) Can a Serializable class contains a non-serializable field in Java? ( answer ) hint: Yes, but you need to make it either static or transient.

43) Difference between this and super in Java? ( answer ) hint: this refers to the current instance while super refers to an instance of the superclass.

44) Difference between Comparator and Comparable in Java? ( answer ) hint: Comparator defines custom ordering while Comparable defines the natural order of objects, e.g. the alphabetic order for String . See The Complete Java MasterClass to learn more about sorting in Java.

DOCGFtdTMhjj3faRAiQ69ZSTxf2pffyroFfv

45) Difference between java.util.Date and java.sql.Date in Java? ( answer ) hint: former contains both date and time while later contains only date part.

46) Why wait and notify method are declared in Object class in Java? ( answer ) hint: because they require lock which is only available to an object.

47) Why Java doesn’t support multiple inheritances? ( answer ) hint: It doesn’t support because of a bad experience with C++, but with Java 8, it does in some sense — only multiple inheritances of Type are not supported in Java now.

48) Difference between checked and unchecked Exception in Java? ( answer ) hint: In case of checked, you must handle exception using catch block, while in case of unchecked, it’s up to you; compile will not bother you.

49) Difference between Error and Exception in Java? ( answer ) hint: I am tired of typing please check the answer

50) Difference between Race condition and Deadlock in Java? ( answer ) hint: both are errors that occur in a concurrent application, one occurs because of thread scheduling while others occur because of poor coding. See Multithreading and Parallel Computing in Java to learn more about deadlock, Race Conditions, and other multithreading issues.

Closing Notes

Thanks, You made it to the end of the article … Good luck with your programming interview! It’s certainly not going to be easy, but by following this roadmap and guide, you are one step closer to becoming a DevOps engineer .

If you like this article, then please share with your friends and colleagues, and don’t forget to follow javinpaul on Twitter!

Additional Resources

  • Java Interview Guide: 200+ Interview Questions and Answers
  • Spring Framework Interview Guide — 200+ Questions & Answers
  • Preparing For a Job Interview By John Sonmez
  • Java Programming Interview Exposed by Markham
  • Cracking the Coding Interview — 189 Questions and Answers
  • Data Structure and Algorithms Analysis for Job Interviews
  • 130+ Java Interview Questions of Last 5 Years
P.S. — If you need some FREE resources to learn Java, you can check out this list of free Java courses to start your preparation. P. S. S. — I have not provided the answer to the interview questions shared in the image “ How many String objects are created in the code?” can you guess and explain?

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Java 8 Interview Questions(+ Answers)

Last updated: January 11, 2024

tricky problem solving interview questions in java

  • >= Java 8

announcement - icon

Now that the new version of REST With Spring - “REST With Spring Boot” is finally out, the current price will be available until the 22nd of June , after which it will permanently increase by 50$

>> GET ACCESS NOW

Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.

The Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.

>> Learn more and deploy your first Spring Boot app to Azure.

And, you can participate in a very quick (1 minute) paid user research from the Java on Azure product team.

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:

>> Try out the Profiler

A quick guide to materially improve your tests with Junit 5:

Do JSON right with Jackson

Download the E-book

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> LEARN SPRING

Building a REST API with Spring?

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

>> Try Alpaquita Containers now.

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Creating PDFs is actually surprisingly hard. When we first tried, none of the existing PDF libraries met our needs. So we made DocRaptor for ourselves and later launched it as one of the first HTML-to-PDF APIs.

We think DocRaptor is the fastest and most scalable way to make PDFs , especially high-quality or complex PDFs. And as developers ourselves, we love good documentation, no-account trial keys, and an easy setup process.

>> Try DocRaptor's HTML-to-PDF Java Client (No Signup Required)

1. Introduction

In this tutorial, we’re going to explore some of the JDK8-related questions that might pop up during an interview.

Java 8 is a platform release packed with new language features and library classes. Most of these new features are geared towards achieving cleaner and more compact code, while some add new functionality that has never before been supported in Java.

Further reading:

Memory management in java interview questions (+answers), java collections interview questions, 2. java 8 general knowledge, q1. what new features were added in java 8.

Java 8 ships with several new features, but the most significant are the following:

  • Lambda Expressions − a new language feature allowing us to treat actions as objects
  • Method References − enable us to define Lambda Expressions by referring to methods directly using their names
  • Optional − special wrapper class used for expressing optionality
  • Functional Interface – an interface with maximum one abstract method; implementation can be provided using a Lambda Expression
  • Default methods − give us the ability to add full implementations in interfaces besides abstract methods
  • Nashorn, JavaScript Engine − Java-based engine for executing and evaluating JavaScript code
  • Stream API − a special iterator class that allows us to process collections of objects in a functional manner
  • Date API − an improved, immutable JodaTime-inspired Date API

Along with these new features, lots of feature enhancements are done under the hood at both the compiler and JVM level.

3. Method References

Q1. what is a method reference.

A method reference is a Java 8 construct that can be used for referencing a method without invoking it. It’s used for treating methods as Lambda Expressions. They only work as syntactic sugar to reduce the verbosity of some lambdas. This way the following code:

Can become:

A method reference can be identified by a double colon separating a class or object name, and the name of the method. It has different variations, such as constructor reference:

Static method reference:

Bound instance method reference:

Unbound instance method reference:

We can read a detailed description of method references with full examples by following this link and this one .

Q2. What Is the Meaning of String::Valueof Expression?

It’s a static method reference to the valueOf method of the String class.

4. Optional

Q1. what is optional how can it be used.

Optional is a new class in Java 8 that encapsulates an optional value, i.e. a value that is either there or not. It’s a wrapper around an object, and we can think of it as a container of zero or one element.

Optional has a special Optional.empty() value instead of wrapped null . Thus it can be used instead of a nullable value to get rid of NullPointerException in many cases.

We can read a dedicated article about Optional here .

The main purpose of Optional , as designed by its creators, is to be a return type of methods that previously would return null . Such methods would require us to write boilerplate code to check the return value, and we could sometimes forget to do a defensive check. In Java 8, an Optional return type explicitly requires us to handle null or non-null wrapped values differently.

For instance, the Stream.min() method calculates the minimum value in a stream of values. But what if the stream is empty? If it wasn’t for Optional , the method would return null or throw an exception.

However, it returns an Optional value, which may be Optional.empty() (the second case). This allows us to easily handle such cases:

It’s worth noting that Optional is not a general purpose class like Option in Scala. It’s not recommended that we use it as a field value in entity classes, which is clearly indicated by it not implementing the Serializable interface.

5. Functional Interfaces

Q1. describe some of the functional interfaces in the standard library.

There are a lot of functional interfaces in the java.util.function package. The more common ones include, but are not limited to:

  • Function – it takes one argument and returns a result
  • Consumer – it takes one argument and returns no result (represents a side effect)
  • Supplier – it takes no arguments and returns a result
  • Predicate – it takes one argument and returns a boolean
  • BiFunction – it takes two arguments and returns a result
  • BinaryOperator – it is similar to a BiFunction , taking two arguments and returning a result. The two arguments and the result are all of the same types.
  • UnaryOperator – it is similar to a Function , taking a single argument and returning a result of the same type

For more on functional interfaces, see the article “Functional Interfaces in Java 8.”

Q2. What Is a Functional Interface? What Are the Rules of Defining a Functional Interface?

A functional interface is an interface with one single abstract method ( default methods do not count), no more, no less.

Where an instance of such an interface is required, a Lambda Expression can be used instead. More formally put: Functional interfaces provide target types for lambda expressions and method references.

The arguments and return type of such an expression directly match those of the single abstract method.

For instance, the Runnable interface is a functional interface, so instead of:

We could simply do:

Functional interfaces are usually annotated with the @FunctionalInterface annotation, which is informative and doesn’t affect the semantics.

6. Default Method

Q1. what is a default method and when do we use it.

A default method is a method with an implementation, which can be found in an interface.

We can use a default method to add a new functionality to an interface, while maintaining backward compatibility with classes that are already implementing the interface:

Usually when we add a new abstract method to an interface, all implementing classes will break until they implement the new abstract method. In Java 8, this problem was solved by using the default method.

For example, the Collection interface does not have a forEach method declaration. Thus adding such a method would simply break the whole collections API.

Java 8 introduced the default method so that the Collection interface can have a default implementation of the forEach method without requiring the classes implementing this interface to implement the same.

Q2. Will the Following Code Compile?

Yes, the code will compile because it follows the functional interface specification of defining only a single abstract method. The second method, count , is a default method that does not increase the abstract method count.

7. Lambda Expressions

Q1. what is a lambda expression and what is it used for.

In very simple terms, a lambda expression is a function that we can reference and pass around as an object.

Moreover, lambda expressions introduce functional style processing in Java, and facilitate the writing of compact and easy-to-read code.

As a result, lambda expressions are a natural replacement for anonymous classes such as method arguments. One of their main uses is to define inline implementations of functional interfaces.

Q2. Explain the Syntax and Characteristics of a Lambda Expression

A lambda expression consists of two parts, the parameter part and the expressions part separated by a forward arrow:

Any lambda expression has the following characteristics:

  • Optional type declaration – when declaring the parameters on the left-hand side of the lambda, we don’t need to declare their types as the compiler can infer them from their values. So int param -> … and param ->… are all valid
  • Optional parentheses – when only a single parameter is declared, we don’t need to place it in parentheses. This means param -> … and (param) -> … are all valid, but when more than one parameter is declared, parentheses are required
  • Optional curly braces – when the expressions part only has a single statement, there is no need for curly braces. This means that param – > statement and param – > {statement;} are all valid, but curly braces are required when there is more than one statement
  • Optional return statement – when the expression returns a value and it is wrapped inside curly braces, then we don’t need a return statement. That means (a, b) – > {return a+b;} and (a, b) – > {a+b;} are both valid

To read more about Lambda expressions, follow this link and this one .

8. Nashorn Javascript

Q1. what is nashorn in java8.

Nashorn is the new Javascript processing engine for the Java platform that shipped with Java 8. Until JDK 7, the Java platform used Mozilla Rhino for the same purpose, as a Javascript processing engine.

Nashorn provides better compliance with the ECMA normalized JavaScript specification and better runtime performance than its predecessor.

Q2. What Is JJS?

In Java 8, jjs is the new executable or command line tool we use to execute Javascript code at the console.

Q1. What Is a Stream? How Does It Differ From a Collection?

In simple terms, a stream is an iterator whose role is to accept a set of actions to apply on each of the elements it contains.

The stream represents a sequence of objects from a source such as a collection, which supports aggregate operations. They were designed to make collection processing simple and concise. Contrary to the collections, the logic of iteration is implemented inside the stream, so we can use methods like map and flatMap for performing a declarative processing.

Additionally, the Stream API is fluent and allows pipelining:

Another important distinction from collections is that streams are inherently lazily loaded and processed.

Q2. What Is the Difference Between Intermediate and Terminal Operations?

We combine stream operations into pipelines to process streams. All operations are either intermediate or terminal.

Intermediate operations are those operations that return Stream itself, allowing for further operations on a stream.

These operations are always lazy, i.e. they do not process the stream at the call site. An intermediate operation can only process data when there is a terminal operation. Some of the intermediate operations are filter , map and flatMap .

In contrast, terminal operations terminate the pipeline and initiate stream processing. The stream is passed through all intermediate operations during terminal operation call. Terminal operations include forEach , reduce, Collect and sum .

To drive this point home, let’s look at an example with side effects:

The output will be as follows:

As we can see, the intermediate operations are only triggered when a terminal operation exists.

Q3. What Is the Difference Between Map and flatMap Stream Operation?

There is a difference in signature between map and flatMap . Generally speaking, a map operation wraps its return value inside its ordinal type, while flatMap does not.

For example, in Optional , a map operation would return Optional<String> type, while flatMap would return String type.

So after mapping, we need to unwrap (read “flatten”) the object to retrieve the value, whereas after flat mapping, there is no such need as the object is already flattened. We apply the same concept to mapping and flat mapping in Stream .

Both map and flatMap are intermediate stream operations that receive a function and apply this function to all the elements of a stream.

The difference is that for the map , this function returns a value, but for flatMap , this function returns a stream. The flatMap operation “flattens” the streams into one.

Here’s an example where we take a map of users’ names and lists of phones and “flatten” it down to a list of phones of all the users using flatMap :

Q4. What Is Stream Pipelining in Java 8?

Stream pipelining is the concept of chaining operations together. We do this by splitting the operations that can happen on a stream into two categories: intermediate operations and terminal operations.

Each intermediate operation returns an instance of Stream itself when it runs. Therefore, we can set up an arbitrary number of intermediate operations to process data, forming a processing pipeline.

There must then be a terminal operation which returns a final value and terminates the pipeline.

10. Java 8 Date and Time API

Q1. tell us about the new date and time api in java 8.

A long-standing problem for Java developers has been the inadequate support for the date and time manipulations required by ordinary developers.

The existing classes such as java.util.Date and SimpleDateFormatter aren’t thread-safe, leading to potential concurrency issues for users.

Poor API design is also a reality in the old Java Data API. Here’s just a quick example: years in java.util.Date start at 1900, months start at 1, and days start at 0, which is not very intuitive.

These issues and several others have led to the popularity of third-party date and time libraries, such as Joda-Time.

In order to address these problems and provide better support in JDK, a new date and time API, which is free of these problems, has been designed for Java SE 8 under the package java.time .

11. Conclusion

In this article, we explored several important technical interview questions with a bias on Java 8. This is by no means an exhaustive list, but it contains questions that we think are most likely to appear in each new feature of Java 8.

Even if we’re just starting out, ignorance of Java 8 isn’t a good way to go into an interview, especially when Java appears strongly on a resume. It is therefore important that we take some time to understand the answers to these questions and possibly do more research.

Good luck in the interview.

Slow MySQL query performance is all too common. Of course it is.

The Jet Profiler was built entirely for MySQL , so it's fine-tuned for it and does advanced everything with relaly minimal impact and no server changes.

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Build your API with SPRING - book cover

Follow the Java Category

tricky problem solving interview questions in java

Ace the top 15 Java algorithm questions for coding interviews

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Algorithm-based questions are a staple of any modern coding interview, as they demonstrate your problem-solving and critical thinking skills. To make sure you don’t get caught off guard in your next Java interview, we’ve put together 15 of the most common algorithm coding questions used by most tech companies and recruiters across the industry.

These algorithm coding questions vary in difficulty, so if you can’t figure out one don’t be ashamed to move on to the next and return later. With enough practice, you’ll shortly be able to crack any interview question thrown at you. Each question is followed by a detailed explanation to help you get prepped for the big interviews ahead.

Today we’ll be covering questions on:

Measuring Complexity: Big O Notation

Sorting and searching: quicksort, binary search and more.

Dynamic Programing: Memoization and Tabulation

Greedy Algorithms: Maximization

Divide and Conquer

Graph Algorithms

Master Java coding interview patterns with our hands-on course today.

Cover

Finally, we add all lines’ time complexity, drop the leading constants and lower order terms, and find our Big O Complexity.

Almost ever interviewer will ask a question which calls for at least one type of searching or sorting, if not more. To help you prepare for these questions, we’ve included the following overview section to build foundational search/sort algorithm proficiency.

Note: It’s unlikely you’ll be prompted to use a certain algorithm in an interview. Instead, you must learn to recognize which algorithm to use based on keywords in the problem statement. As you practice, try to pinpoint which part of the problem statement would lead you to use the indicated algorithm.

2: Quicksort

Given an unsorted array of numbers, find K th smallest number in it.

Please note that it is the K th smallest number in the sorted order, not the K th distinct element.

Time Complexity: average O ( N ) O(N) O ( N ) or worst case O ( N 2 ) O(N^2) O ( N 2 )

We use Quicksort’s partitioning scheme to find the Kth smallest number. We recursively partition the input array and if, after partitioning, our pivot is at the K-1 index we have found our required number. If not, we choose one the following options:

  • If pivot’s position is larger than K-1, we recursively partition the array on numbers lower than the pivot.
  • If pivot’s position is smaller than K-1, we recursively partition the array on numbers greater than the pivot.

3: Binary Search

We are given a 2D array where all elements in any individual row or column are sorted. In such a matrix, we have to search or find the position of, a given key.

Time Complexity: O ( m + n ) O(m + n) O ( m + n )

We start from the upper right corner of the matrix and compare its value with the key. If they are equal, we have found the position of the key.

If the key is smaller than the current element, we move to the left one position. If the key is larger than the current element, we move right one position.

As the matrix is sorted, moving left always results in lower values than the current while moving down always results higher values. We continue this process until either we find the element or go out of the boundary of the matrix (which indicates that the key does not exist).

4. Merge Sort

Given the head pointer of a linked sort, sort the linked list in ascending order using merge sort, and return the new head pointer of the sorted linked list.

Time Complexity: O ( n l o g n ) O(nlogn) O ( n l o g n )

In the dividing step, we split our input linked list into two halves and keep doing so until there is a linked list of size 1 or 0. Linked lists of size 1 and 0 are always sorted. In the combining step, we merge sorted lists and keep doing so until we have a completely sorted list.

At each step, we divide our problem into two sub-problems. The size of each sub-problem is n 2 \frac n2 2 n ​ and the total cost of combining steps (merging sorted lists) is n n n .

5. Insertion Sort

Given the head pointer of a linked list, sort the linked list in ascending order using insertion sort. Return the new head pointer of the sorted linked list.

Time Complexity: O ( n 2 ) O(n^2) O ( n 2 )

While the original list is not empty:

Remove an element (say ‘X’) from the original list.

Insert ‘X’ at the correct sorted position in the sorted list.

To insert a node into the sorted linked list, we may need to scan the entire sorted list depending upon the node being inserted.

Using a HashMap, implement a function that takes an array arr , a number value , and the size of the array as an input and returns two numbers that add up to value .

Time Complexity: O ( n ) O(n) O ( n )

For all the elements in the arr array, we store the difference n - arr[i] in hmap .

Then with another iteration over arr , we check if any element of arr exists in the hmap , which means the difference of n and the number found ( n - arr[i] ) are also present.

Therefore, an array of size 2 called result is created to store the pair that sums up to n . If hmap contains an array element, result[] is updated, or else it is returned containing the default value.

Implement an isSubset() function to take two arrays as input and check whether an array is a subset of another given array.

Time Complexity: O ( m + n ) O(m+n) O ( m + n )

First, we iterate over arr2 and arr3 to see whether their elements can be found in arr1 .

At the back end, the values are checked against their hashed indices in arr1 .

Dynamic Programming: Memoization and Tabulation

Dynamic Programming is a central algorithm technique for the modern developer, as it focuses on breaking a problem into simpler sub-problems to achieve optimization. The more optimal the solution to sub-problems, the more optimal the overall solution is.

This is the foundation of recursive problem-solving and therefore will be asked by any good interviewer.

Dynamic Programming questions can either be solved from a Top-Down approach or a Bottom-Up approach, using either Memoization or Tabulation , respectively. Interviewers may ask for one or may leave it to your decision.

Below we’ll see an example of each so you’re prepared for any alternative.

8. The Knapsack Problem:

Imagine that you’re an adventurer with a knapsack looking over a dragon’s hoard.

Given two integer arrays that represent the weights and profits of N items, implement a function knapSack() that finds a subset of these items that will give us the maximum profit without their cumulative weight exceeding a given number capacity . Each item may only be selected once, which means when we get to it we can either skip it or put it in the knapsack.

Use the top-down approach with memoization.

Time Complexity: O ( N ∗ C ) O(N*C) O ( N ∗ C )

The function knapSack makes a lookupTable within the function that stores the maximum value that can be attained with maximum capacity (lines 29-35). This function calls the helper function knapsackRecursive (line 36). It returns the maximum value that can be attained using only the first i items, i.e., items at the currentIndex while keeping their total weight no more than weights.

We have two varying values ( capacity and currentIndex ), so we can use a two-dimensional array to store the results of all the solved subproblems in our recursive function knapsackRecursive .

We need to store results for every subarray, i.e., for every possible index and for every possible capacity. If the lookupTable[currentIndex][capacity] is already computed before (line 10), this value is immediately returned (line 11).

Otherwise, we call the function recursively:

With the item, saving the result in profit1 (line 17).

Without the item, saving the result in the variable, profit2 (line 21).

Out of the two, we return the result that is greater (as done on lines 23-24).

9. Staircase Problem

A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a function to count the number of possible ways that the child can run up the stairs.

Try to solve this one using a Bottom-Up approach with Tabulation.

We know that:

The total number of ways to reach the zero-step is 1 (line 6).

The total number of ways to reach the first step is 1 (line 7).

The total number of ways to reach the second step is 2 (line 8).

Hence, we fill up the lookupTable with these three values (lines 6-8).

We know that the total number of ways to reach any n th stair is by taking 1, 2, or 3 steps. Hence, the total number of ways to reach an n th stair would be equal to the sum of the total number of ways to reach [n-1] th step, number of ways to reach [n-2] th step, and the number of ways to reach the [n-3] th step.

So, the rest of the values of the lookupTable are filled by calculating the total number of ways to reach an nth step by summing the ways to reach the previous three steps (line 11).

The required value is then returned from the lookupTable (line 13).

Greedy Algorithms: Local Maximization

Greedy is an algorithmic technique where the solution is built one piece at a time, prioritizing immediate, obvious benefits at each choice. In other words, it seeks to maximize profit (the positive) and minimizes the cost (the negative).

This technique works on the idea that the locally optimal choice will contribute to the globally optimal solution. Below we’ll see a few interview questions to help you use this technique when required.

10: Change Machine Problem

You have to make such a change machine that only returns the change in the form of coins.

You are supplied with an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents), and pennies (1 cent). The user will enter any amount. For each amount, you have to return the minimum number of coins possible!

Line 3: A public array is given containing the set of coins available.

Line 6: The function getMinCoins() is defined; it has ArrayList as its return type and int amount as its parameter.

Line 9: The ArrayList of type Integer is allocated to store the change.

Lines 10-17: A for loop traverses the int[]coins array from beginning to end (given in descending order).

Line 12: Since the first index of coins has the maximum element, compare in the while condition whether this amount is greater than the max coin.

Line 14: If yes, subtract the max value coin from the amount given.

Line 15: Add this coin to the change list.

Line 17: When the largest coin becomes greater than the remaining amount, the while loop breaks and the value of i is incremented to move to the next (lesser value) coin.

Keep iterating this for loop, until the remaining amount can no longer be subdivided by the available coins.

11: Find the Egyptian Fraction

Every positive fraction can be represented as the sum of its unique unit fractions. A fraction is a unit fraction if the numerator is 1 and the denominator is a positive integer. For example, 1 3 \frac 13 3 1 ​ is a unit fraction. Such a representation is called Egyptian fraction.

Time Complexity: O ( l o g 3 ) O(log_3) O ( l o g 3 ​ )

For a given number of the form n d \frac nd d n ​ , where d > n, first find the greatest possible unit fraction, and then perform recursion for the remaining part.

For example, consider 6 14 \frac 6{14} 14 6 ​ . We first find the ceiling of 14 6 \frac {14}6 6 14 ​ , i.e., 3, so the first unit fraction becomes 1 3 \frac 13 3 1 ​ . Now subtract 1 3 \frac 13 3 1 ​ out of 6 14 \frac 6{14} 14 6 ​ and recur for 6 14 \frac 6{14} 14 6 ​ – 1 3 \frac 13 3 1 ​ .

We use the greedy algorithm because we want to reduce the fraction to a form where the denominator is greater than the numerator and the numerator doesn’t divide the denominator.

The method is to find the biggest unit fraction we can and subtract it from the remaining fraction. Doing subtractions always decreases this group of unit fractions, but it never repeats a fraction and eventually will stop, which is why we call this approach greedy.

Divide and Conquer:

Similar to Dynamic Programming, Divide and Conquer algorithms work by breaking down a problem into sub-problems. Where they differ is that Divide and Conquer algorithms solve each sub-problem then combine the results to form the ultimate solution whereas the sub-problems in Dynamic Programming are fully separate.

This is another staple type of algorithm that will be tested in your coding interview.

12: Euclidean Algorithm Problem

Given two integers a and b , calculate the largest number (GCD) that divides both of them without leaving a remainder.

Time Complexity: O ( l o g m i n ( a , b ) ) O(log min(a,b)) O ( l o g min ( a , b ))

  • Line 5: The algorithm starts by checking if the first number ( a , which was obtained by b \%ab%a in recursive calls) is 0.
  • Line 6: If that is the case, then return b .
  • Line 7: Otherwise, we make the next recursive call GCD(b % a, a) .

13: Missing number in Sorted Array

Given an array of contiguous integers starting from x , with one missing integer in between, and the size of the array, find the missing number!

Time Complexity: O ( l o g n ) O(log_n) O ( l o g n ​ )

Line 38: The driver program calls the function missingNumber() with int [] arr and int size as its parameters.

Line 6: Initialize the right and left limits.

Lines 9-10: Handles corner case 1. Return 1 if array’s 1st element is not equal to 1.

Line 12-18: Begin by finding the middle index of the array, if the element at middle is not equal to middle + 1 , and this is the first missing element, middle + 1 is the missing element.

Lines 21-26: If this is not the first missing element and arr[middle] is not equal to middle+1 , search in the right half. Otherwise, search in the left half of the array.

Line 28: Handles corner case 2. Return -1 if you end up traversing the whole array and no element is missing.

Graphs Algorithms:

For our final section we’ll look at problems to build proficiency with common graph-related questions. These questions are becoming increasingly popular in interviews due to their prevalence in social-media mapping, meaning now more than ever it’s key to come prepared with this practice.

14: Calculate the Number of Nodes in a Given Graph Level

Implement a function that returns the number of nodes at a given level of an undirected graph.

Time Complexity: O ( V + E ) O(V + E) O ( V + E )

The solution above modifies the visited array to store the level of each node. Later, it counts the nodes with the same level (lines 32-35).

In this code, while visiting each node, the level of the visited node is set with an increment in the level of its parent node, i.e.,

This is how the level of each node is determined (line 26).

15: Transpose a Graph

Implement a function that takes a directed graph as input and print its transpose.

First, you make another graph and start reversing it. Traverse the adjacency list of the given graph. When the program finds a vertex v in the adjacency list of vertex u (i.e., an edge from u to v in the given graph), add an edge from v to u in the transposedGraph , adding u in the adjacency list of vertex v of the new graph) (lines 9-13).

In line 19, the printGraph() function prints the graph to console. You can find its implementation in Graph.java file (lines 29-36).

More coding interview questions to ace algorithms:

  • Search in a rotated array
  • Find the median of two sorted arrays
  • Find duplicates in an array
  • The Dutch National Flag Problem
  • Find the longest common substring in a string
  • The Egg Drop Problem
  • Find the longest palindromic subsequence of a string
  • The Edit Distance Problem
  • Connect n pipes with the minimum cost
  • The Train Station Platform Problem
  • The Fractional Knapsack Problem
  • Find Kruskal’s minimum spanning tree
  • Find the peak element in an array
  • Shuffle the integers of an array
  • Search a graph breadth-first
  • Search a graph depth-first
  • Count the paths between two nodes
  • Print all connected components in a graph
  • Remove an edge of a graph
  • Implement topological sorting of a graph
  • Check if a graph is strongly connected
  • Check if a graph is Bipartite
  • Find the floor and ceiling of a number
  • Find the closest number in an array
  • Collect coins in the least steps
  • Find the maximum sum of two subarrays
  • The Coin Change Problem
  • The Partition Problem
  • Count element occurrence
  • The Sparse Search Problem

Where to go from here

Great work! Hopefully, you can already feel that pre-interview anxiety starting to melt away. While this was a deep dive into 15 of the most common algorithm questions, there are many more possibilities that may come up during your interview. Varied practice is essential to success in any coding interview.

If you want to practice your Java coding skills, then Educative-99 or Educative-77 in Java are the perfect places to go. Educative-99 is curated by expert developers for beginner developers in order to help them ace their Java coding and algorithm skills.

To master the underlying patterns behind coding interview problems, check out our course, Grokking Coding Interview Patterns in Java .

Interview roadmap

If you’re unsure where the road to your dream front-end dev job leads next, take a look at our free interview roadmap to help you get quickly.

Keep reading about interview prep

  • 5 tried and true techniques to prepare for a coding interview
  • Cracking the top Amazon coding interview questions

Learn in-demand tech skills in half the time

Mock Interview

Skill Paths

Assessments

Learn to Code

Tech Interview Prep

Generative AI

Data Science

Machine Learning

GitHub Students Scholarship

Early Access Courses

For Individuals

Try for Free

Gift a Subscription

Become an Author

Become an Affiliate

Earn Referral Credits

Cheatsheets

Frequently Asked Questions

Privacy Policy

Cookie Policy

Terms of Service

Business Terms of Service

Data Processing Agreement

Copyright © 2024 Educative, Inc. All rights reserved.

Javarevisited

Learn Java, Programming, Spring, Hibernate throw tutorials, examples, and interview questions

Topics and Categories

  • collections
  • multithreading
  • design patterns
  • interview questions
  • data structure
  • Java Certifications
  • jsp-servlet
  • online resources
  • jvm-internals

Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Tuesday, March 26, 2024

  • Top 50 Java Programs from Coding Interviews

Java Programming Interview Questions for 2 to 3 years

  • 75+ Coding Problems from Interviews ( questions )
  • 10 Free Courses to learn Data Structure and Algorithms ( courses )
  • 10 Books to Prepare Technical Programming/Coding Job Interviews ( books )
  • 10 Courses to Prepare for Programming Job Interviews ( courses )
  • 100+ Data Structure and Algorithms Interview Questions ( questions )
  • My favorite Free Algorithms and Data Structure Courses on FreeCodeCamp ( courses )
  • 30+ linked list interview questions with a solution ( linked list )
  • 30+ array-based interview questions for programmers ( array )
  • 10 Coding Tips and 101 Coding Questions for Interviews ( tips )
  • 50+ Algorithm based Interview questions from HackerNoon ( questions )
  • 5 Free Courses to learn Algorithms in-depth ( courses )
  • 10 Algorithms books every Programmer should read ( books )
  • Top 5 Data Structure and Algorithms Courses for Programmers ( courses )

10 comments:

Hi guys, here the first question is "How to find the maximum occurring character in given String?" but the solution link is for "How to Count Occurrences of a Character in String" Both are different, Please confirm...

tricky problem solving interview questions in java

Yes, you are right but once you know how to count character then the other one becomes simple because you just need to return the character with maximum count

boolean b=true;

yes both are different example 1)How to find the maximum occurring character in given String?" Malyalaum - a-3 (a is the maximum occurring character in given string) 2) How to Count Occurrences of a Character in String Malyalaum m-2 a-3 y-1 u-1 thank you,

That's correct but once you know how to count character then the other one becomes simple because you just need to return the character with maximum count

public class OccObj { public static void main(String[] args){ Scanner input=new Scanner(System.in); String s= input.next(); NoOfOcuu(s); } public static void NoOfOcuu(String s){ int c=0,c2=0; ArrayListn=new ArrayList<>(); char c1='0'; for(int i=0;i=i)&&(c2==0)) { if (s.charAt(i) == s.charAt(j)) { c++; } } } if(c>1){ n.add(s.charAt(i)); } if(c>0) { System.out.println("the vale:" + s.charAt(i) + " - " + c); } } } }

public static void NoOfOcuu(String s){ int c=0,c2=0; ArrayListn=new ArrayList<>(); char c1='0'; for(int i=0;i=i)&&(c2==0)) { if (s.charAt(i) == s.charAt(j)) { c++; } } } if(c>1){ n.add(s.charAt(i)); } if(c>0) { System.out.println("the vale:" + s.charAt(i) + " - " + c); } } }

19)function isPalindrome(str) { let emptyArr = []; for (let i = 0; i < str.length; i++) { let x = str[i]; if (x == "(" || x == "[" || x == "{") { emptyArr.push(x); continue; } if (emptyArr.length == 0) return false; let y; switch (x) { case ")": y = emptyArr.pop(); if (y == "{" || y == "[") return false; break; case "}": y = emptyArr.pop(); if (y == "(" || y == "[") return false; break; case "]": y = emptyArr.pop(); if (y == "(" || y == "{") return false; break; } } return emptyArr.length == 0; } if (isPalindrome("{}")) console.log(true); else console.log(false);

val str = "aabbbbaa" var l = str.length var s = "" while (l>0){ s = s + str.get(l-1) l-- } if(s.equals(str)) { println("palindrome string : " + s) }else{ println("No palindrome string : " + s) }

Hi guys, here is the solution for question number 4 "How to remove characters from the first String which are present in the second String?" public static void main(String[] args) { String st1 = "india is great"; String st2 = "in"; List secondStringList = st2.chars().mapToObj(c -> (char) c).collect(Collectors.toList()); String outputString = st1.chars().mapToObj(c -> (char) c).filter(c -> !secondStringList.contains(c)).map(ch -> new String(String.valueOf(ch))) .collect(Collectors.joining("")); System.out.println("outputString : " + outputString); }

Feel free to comment, ask questions if you have any doubt.

Top 20 Problem Solving Interview Questions (Example Answers Included)

Mike Simpson 0 Comments

tricky problem solving interview questions in java

By Mike Simpson

When candidates prepare for interviews, they usually focus on highlighting their leadership, communication, teamwork, and similar crucial soft skills . However, not everyone gets ready for problem-solving interview questions. And that can be a big mistake.

Problem-solving is relevant to nearly any job on the planet. Yes, it’s more prevalent in certain industries, but it’s helpful almost everywhere.

Regardless of the role you want to land, you may be asked to provide problem-solving examples or describe how you would deal with specific situations. That’s why being ready to showcase your problem-solving skills is so vital.

If you aren’t sure who to tackle problem-solving questions, don’t worry, we have your back. Come with us as we explore this exciting part of the interview process, as well as some problem-solving interview questions and example answers.

What Is Problem-Solving?

When you’re trying to land a position, there’s a good chance you’ll face some problem-solving interview questions. But what exactly is problem-solving? And why is it so important to hiring managers?

Well, the good folks at Merriam-Webster define problem-solving as “the process or act of finding a solution to a problem.” While that may seem like common sense, there’s a critical part to that definition that should catch your eye.

What part is that? The word “process.”

In the end, problem-solving is an activity. It’s your ability to take appropriate steps to find answers, determine how to proceed, or otherwise overcome the challenge.

Being great at it usually means having a range of helpful problem-solving skills and traits. Research, diligence, patience, attention-to-detail , collaboration… they can all play a role. So can analytical thinking , creativity, and open-mindedness.

But why do hiring managers worry about your problem-solving skills? Well, mainly, because every job comes with its fair share of problems.

While problem-solving is relevant to scientific, technical, legal, medical, and a whole slew of other careers. It helps you overcome challenges and deal with the unexpected. It plays a role in troubleshooting and innovation. That’s why it matters to hiring managers.

How to Answer Problem-Solving Interview Questions

Okay, before we get to our examples, let’s take a quick second to talk about strategy. Knowing how to answer problem-solving interview questions is crucial. Why? Because the hiring manager might ask you something that you don’t anticipate.

Problem-solving interview questions are all about seeing how you think. As a result, they can be a bit… unconventional.

These aren’t your run-of-the-mill job interview questions . Instead, they are tricky behavioral interview questions . After all, the goal is to find out how you approach problem-solving, so most are going to feature scenarios, brainteasers, or something similar.

So, having a great strategy means knowing how to deal with behavioral questions. Luckily, there are a couple of tools that can help.

First, when it comes to the classic approach to behavioral interview questions, look no further than the STAR Method . With the STAR method, you learn how to turn your answers into captivating stories. This makes your responses tons more engaging, ensuring you keep the hiring manager’s attention from beginning to end.

Now, should you stop with the STAR Method? Of course not. If you want to take your answers to the next level, spend some time with the Tailoring Method , too.

With the Tailoring Method, it’s all about relevance. So, if you get a chance to choose an example that demonstrates your problem-solving skills, this is really the way to go.

We also wanted to let you know that we created an amazing free cheat sheet that will give you word-for-word answers for some of the toughest interview questions you are going to face in your upcoming interview. After all, hiring managers will often ask you more generalized interview questions!

Click below to get your free PDF now:

Get Our Job Interview Questions & Answers Cheat Sheet!

FREE BONUS PDF CHEAT SHEET: Get our " Job Interview Questions & Answers PDF Cheat Sheet " that gives you " word-word sample answers to the most common job interview questions you'll face at your next interview .

CLICK HERE TO GET THE JOB INTERVIEW QUESTIONS CHEAT SHEET

Top 3 Problem-Solving-Based Interview Questions

Alright, here is what you’ve been waiting for: the problem-solving questions and sample answers.

While many questions in this category are job-specific, these tend to apply to nearly any job. That means there’s a good chance you’ll come across them at some point in your career, making them a great starting point when you’re practicing for an interview.

So, let’s dive in, shall we? Here’s a look at the top three problem-solving interview questions and example responses.

1. Can you tell me about a time when you had to solve a challenging problem?

In the land of problem-solving questions, this one might be your best-case scenario. It lets you choose your own problem-solving examples to highlight, putting you in complete control.

When you choose an example, go with one that is relevant to what you’ll face in the role. The closer the match, the better the answer is in the eyes of the hiring manager.

EXAMPLE ANSWER:

“While working as a mobile telecom support specialist for a large organization, we had to transition our MDM service from one vendor to another within 45 days. This personally physically handling 500 devices within the agency. Devices had to be gathered from the headquarters and satellite offices, which were located all across the state, something that was challenging even without the tight deadline. I approached the situation by identifying the location assignment of all personnel within the organization, enabling me to estimate transit times for receiving the devices. Next, I timed out how many devices I could personally update in a day. Together, this allowed me to create a general timeline. After that, I coordinated with each location, both expressing the urgency of adhering to deadlines and scheduling bulk shipping options. While there were occasional bouts of resistance, I worked with location leaders to calm concerns and facilitate action. While performing all of the updates was daunting, my approach to organizing the event made it a success. Ultimately, the entire transition was finished five days before the deadline, exceeding the expectations of many.”

2. Describe a time where you made a mistake. What did you do to fix it?

While this might not look like it’s based on problem-solving on the surface, it actually is. When you make a mistake, it creates a challenge, one you have to work your way through. At a minimum, it’s an opportunity to highlight problem-solving skills, even if you don’t address the topic directly.

When you choose an example, you want to go with a situation where the end was positive. However, the issue still has to be significant, causing something negative to happen in the moment that you, ideally, overcame.

“When I first began in a supervisory role, I had trouble setting down my individual contributor hat. I tried to keep up with my past duties while also taking on the responsibilities of my new role. As a result, I began rushing and introduced an error into the code of the software my team was updating. The error led to a memory leak. We became aware of the issue when the performance was hindered, though we didn’t immediately know the cause. I dove back into the code, reviewing recent changes, and, ultimately, determined the issue was a mistake on my end. When I made that discovery, I took several steps. First, I let my team know that the error was mine and let them know its nature. Second, I worked with my team to correct the issue, resolving the memory leak. Finally, I took this as a lesson about delegation. I began assigning work to my team more effectively, a move that allowed me to excel as a manager and help them thrive as contributors. It was a crucial learning moment, one that I have valued every day since.”

3. If you identify a potential risk in a project, what steps do you take to prevent it?

Yes, this is also a problem-solving question. The difference is, with this one, it’s not about fixing an issue; it’s about stopping it from happening. Still, you use problem-solving skills along the way, so it falls in this question category.

If you can, use an example of a moment when you mitigated risk in the past. If you haven’t had that opportunity, approach it theoretically, discussing the steps you would take to prevent an issue from developing.

“If I identify a potential risk in a project, my first step is to assess the various factors that could lead to a poor outcome. Prevention requires analysis. Ensuring I fully understand what can trigger the undesired event creates the right foundation, allowing me to figure out how to reduce the likelihood of those events occurring. Once I have the right level of understanding, I come up with a mitigation plan. Exactly what this includes varies depending on the nature of the issue, though it usually involves various steps and checks designed to monitor the project as it progresses to spot paths that may make the problem more likely to happen. I find this approach effective as it combines knowledge and ongoing vigilance. That way, if the project begins to head into risky territory, I can correct its trajectory.”

17 More Problem-Solving-Based Interview Questions

In the world of problem-solving questions, some apply to a wide range of jobs, while others are more niche. For example, customer service reps and IT helpdesk professionals both encounter challenges, but not usually the same kind.

As a result, some of the questions in this list may be more relevant to certain careers than others. However, they all give you insights into what this kind of question looks like, making them worth reviewing.

Here are 17 more problem-solving interview questions you might face off against during your job search:

  • How would you describe your problem-solving skills?
  • Can you tell me about a time when you had to use creativity to deal with an obstacle?
  • Describe a time when you discovered an unmet customer need while assisting a customer and found a way to meet it.
  • If you were faced with an upset customer, how would you diffuse the situation?
  • Tell me about a time when you had to troubleshoot a complex issue.
  • Imagine you were overseeing a project and needed a particular item. You have two choices of vendors: one that can deliver on time but would be over budget, and one that’s under budget but would deliver one week later than you need it. How do you figure out which approach to use?
  • Your manager wants to upgrade a tool you regularly use for your job and wants your recommendation. How do you formulate one?
  • A supplier has said that an item you need for a project isn’t going to be delivered as scheduled, something that would cause your project to fall behind schedule. What do you do to try and keep the timeline on target?
  • Can you share an example of a moment where you encountered a unique problem you and your colleagues had never seen before? How did you figure out what to do?
  • Imagine you were scheduled to give a presentation with a colleague, and your colleague called in sick right before it was set to begin. What would you do?
  • If you are given two urgent tasks from different members of the leadership team, both with the same tight deadline, how do you choose which to tackle first?
  • Tell me about a time you and a colleague didn’t see eye-to-eye. How did you decide what to do?
  • Describe your troubleshooting process.
  • Tell me about a time where there was a problem that you weren’t able to solve. What happened?
  • In your opening, what skills or traits make a person an exceptional problem-solver?
  • When you face a problem that requires action, do you usually jump in or take a moment to carefully assess the situation?
  • When you encounter a new problem you’ve never seen before, what is the first step that you take?

Putting It All Together

At this point, you should have a solid idea of how to approach problem-solving interview questions. Use the tips above to your advantage. That way, you can thrive during your next interview.

FREE : Job Interview Questions & Answers PDF Cheat Sheet!

Download our " Job Interview Questions & Answers PDF Cheat Sheet " that gives you word-for-word sample answers to some of the most common interview questions including:

  • What Is Your Greatest Weakness?
  • What Is Your Greatest Strength?
  • Tell Me About Yourself
  • Why Should We Hire You?

Click Here To Get The Job Interview Questions & Answers Cheat Sheet

tricky problem solving interview questions in java

Co-Founder and CEO of TheInterviewGuys.com. Mike is a job interview and career expert and the head writer at TheInterviewGuys.com.

His advice and insights have been shared and featured by publications such as Forbes , Entrepreneur , CNBC and more as well as educational institutions such as the University of Michigan , Penn State , Northeastern and others.

Learn more about The Interview Guys on our About Us page .

About The Author

Mike simpson.

' src=

Co-Founder and CEO of TheInterviewGuys.com. Mike is a job interview and career expert and the head writer at TheInterviewGuys.com. His advice and insights have been shared and featured by publications such as Forbes , Entrepreneur , CNBC and more as well as educational institutions such as the University of Michigan , Penn State , Northeastern and others. Learn more about The Interview Guys on our About Us page .

Copyright © 2024 · TheInterviewguys.com · All Rights Reserved

  • Our Products
  • Case Studies
  • Interview Questions
  • Jobs Articles
  • Members Login

tricky problem solving interview questions in java

Every other Tuesday, you’ll get actionable tips to land your dream job.  Subscribe

  • Behavioral Interviews

Answering Problem-Solving Interview Questions: Tips and Examples

Answering Problem-Solving Interview Questions: Tips and Examples

Problem-solving skills are difficult to describe and quantify: they’re a combination of different hard and soft skills such as logical inference, technical knowledge, adaptability and innovation, leadership potential, decision-making, productivity, and collaboration.

All are crucial for developing expertise and delivering results at work — especially when the going gets tough.

And because problem-solving is so important, you’re almost guaranteed to get asked about it in a job interview. Read on, and make sure no problem-solving question catches you off guard.

In this article, you’ll learn:

  • How to answer problem-solving job interview questions
  • Types of problem-solving questions
  • Why recruiters ask these questions and what your answers might reveal
  • Sample answers for the main types of problem-solving questions

Want to get an offer after every interview? Our interview prep tool will guide you through all the questions you can expect, let you record and analyze your answers, and provide instant AI feedback. You’ll know exactly what to improve to turn your next interview into a job.

ACE YOUR NEXT INTERVIEW

Big Interview: the best interview preparation tool

Our users land jobs 4 to 5 weeks faster than the national average. Get ready for your interview now .

How to Answer Problem-Solving Job Interview Questions

Here’s how to understand the intention behind problem-solving interview questions and create an informative answer that will highlight your expertise and potential.

Understand the problem-solving question and why recruiters ask it

Hiring managers and recruiters want to know how you identify roadblocks, analyze information, and overcome challenges. These challenges can vary from specific, technical issues to more general issues like improving company processes or handling interpersonal relationships.

To put these skills to the test, recruiters use “problem-solving” job interview questions, also known as analytical questions. Here are some common ones:

  • Tell me about a situation where you had to solve a difficult problem.
  • Give me a specific example of a time when you used good judgment and logic in solving a problem.
  • Describe a time when you didn’t know how to solve a problem. What did you do?
  • Describe how you approach a complex or difficult problem.

Here’s what these questions help recruiters discover:

Your adaptability and innovation

Are you an out-of-the-box thinker who’s open to new ideas and who can handle uncharted waters easily?

Efficiency and productivity

Are your problem-solving skills contributing to the team’s performance, removing bottlenecks, smoothing out processes, and keeping projects on track?

Collaboration and communication

Are you successfully collaborating with others to find solutions? Are you handling people-related problems effectively?

Decision-making

Can you efficiently evaluate different options and reach a decision independently? Can you make sound decisions to minimize risks and maximize benefits and opportunities?

Leadership potential

Are your problem-solving skills so good that they open up new opportunities for you to move in the leadership direction ?

Problem-solving interview questions are not tied to a specific role and industry. Mastering your problem-solving skills will help you stand out from the competition and be more successful in your role, whatever it may be.

And if you need help with answering other common interview questions, sign up for our free course !

Reflect on your thought process

Be mindful of your thought processes when you face a difficult problem.

Is your initial reaction to panic or are you calm and enthusiastic to tackle it? Is the problem stopping you from focusing on everything else you’re working on? Do you look at the problem as a whole or do you break it down?

Understanding how you think and approach the problem will help you know yourself and improve your problem-solving skills, but it’ll also make it easier to answer these tricky questions during an interview.

Be specific

Tailor your answers to problem-solving interview questions so that you cover specific details, actions, and skills relevant to the position. If possible, list the results and share lessons learned from an experience you’re describing.

We’re not saying you should lie and make up a story about your problem-solving skills for each position you apply for; remember that this is a broad set of skills and you surely have something relevant from your past experience that you can bring up.

💡 For example, if you’re a Customer Service Representative applying for the same role in another company, you can speak about how you solved a customer’s problem or how you helped the team switch to a new CRM tool and transfer all the data.

💡 If you’re applying for a leadership role in the customer service field, you can speak about how you handled an interpersonal problem within a team or how you spotted bottlenecks and modified processes to make the team more efficient.

💡 If you’re moving to a Sales position, you can highlight your selling experience and talk about a time when you had to solve a customer’s problem and you managed to upsell them in the process.

Follow up with clear outcomes

Prove you have outstanding problem-solving skills by listing clear outcomes for every problem you solved. They can be quantitative or qualitative.

💡 Fixed a process? Say that it improved team productivity by X%.

💡 Handled a difficult client? If they became a VIP customer later on, mention it.

💡 Resolved a conflict? Describe how the experience helped you strengthen the bonds in a team.

💡 Solved a complex technical problem? Say that you got a bonus for it, or that you expanded and improved the existing documentation to help coworkers in the future.

Use the STAR method

Whenever possible, use the STAR (situation-task-action-result) method in your answer:

  • (S) ituation: Describe the situation and provide context.
  • (T) ask: What tasks you planned on doing to tackle the issue, your contribution.
  • (A) ction you took (step-by-step).
  • (R) esult of your efforts.

It’ll help you create a well-rounded answer that’s informative and engaging. Plus, using this method to prepare answers in advance will help you memorize the story quickly and easily.

✅ Bear in mind that not every problem-solving interview question can be answered with a STAR method. Some questions will be very specific and will ask for quick and short information about a certain tool or similar. Other questions, the ones beginning with “Give me an example when…” or “Tell me about a time when…” will be the perfect opportunity to use the STAR method.

Also, remember that there’s never a single correct answer to a problem-solving question, just like there usually are multiple solutions to a given problem — a study on the hospitality industry revealed that the most successful problem-solving strategies applied in the workplace were always very specific to given circumstances.

Questions about your problem-solving skills are just one group of the standard interview questions, you can be almost sure you will get asked. Prepare for other interview “classics” with our dedicated guides:

  • Tell Me About Yourself: Sample Answers
  • Where Do You See Yourself in 5 Years?
  • Why Did You Leave Your Last Job?
  • What Are Your Strenghts?
  • What Is Your Greatest Weakness?
  • How Do You Handle Conflict?
  • Why Should We Hire You?
  • Why Do You Want to Work Here?

If prepping for a video interview, learn what to expect from this guide: Video Interviewing Tips & Tricks

And if you’re interested in interviewing for specific positions, see:

  • Sales Interview Questions and Answers
  • Customer Service Interview Questions and Answers
  • Customer Service Manager Interview Questions and Answers
  • Behavioral Interview Questions for Customer Service

Types of Problem-Solving Job Interview Questions

1. general problem-solving questions.

These questions aim to discover your general approach to problems and challenges.

How do you approach complex problems?

Interviewers want to know how you approach the process of solving complex problems. Do you jump straight into it or do you take a step back, break the problem down into manageable components, analyze the info you have, and then dive in?

Can you provide an example of a challenging issue you’ve encountered and how you resolved it?

Can you assess a situation and find the most appropriate solution? Can you handle the pressure? Do you take the lead during difficult times? Are you able to take responsibility for the outcomes?

This question is more specific than the previous one, so make sure you think about a situation in advance and prepare your answer using the STAR method.

Big Interview’s Answer Builder can help you shape your answer. You’ll be able to list and filter the points you’d like to mention, add details and rearrange the order to create a compelling story.

Plus, you’ll get bite-sized tips on how to answer the most common interview questions while you’re in the Builder.

How do you prioritize multiple tasks when faced with tight deadlines?

Recruiters want to know how you set criteria based on which you’ll set priorities, how and if you juggle between multiple tasks, and how you communicate and collaborate with other people involved.

General problem-solving sample answer

“Tell me about a time when you faced a difficult problem at work. How did you solve it?”

Behavioral questions about problem-solving

Behavioral questions ask for specific situations from your past in which you displayed a certain behavior. Based on it, recruiters hope to predict how you’ll perform in the future.

Tell me about a time when your team faced a problem and you helped to find a solution

This one’s asked to assess your teamwork and cooperation skills in tough situations.

Interestingly, a 2015 study on problem-solving in the workplace showed that when it comes to expertise-related problems, employees rarely relied on trial-and-error or information retrieval as modes of problem-solving.

Instead, they mostly relied on help from others, that is, their coworkers who they believed were experts on the subject matter.

This puts emphasis on the importance of teamwork and collaboration in problem-solving. And you certainly noticed how easier it gets to solve a problem (or brainstorm a new idea) as a group, when different individuals bring fresh, unique ideas to the table.

So, recruiters want to know if you’d be cooperative and open to a teamwork experience, and these factors might hint at how you’ll fit in with the team.

Describe a situation in which you received criticism for your solution to a problem. How did you handle that?

This one checks how you handle feedback and criticism — it’s challenging, but it’s essential for growth.

In your answer, make sure you depict a situation in which you demonstrated that growth mindset and the ability to see that taking criticism is not a sign of weakness (or a personal attack on you) but a unique opportunity to learn something new.

Can you provide an example of when you had to collaborate with a team to solve a work-related problem?

Similarly to the first question in this group, this one aims to see how you perform in a team and solve problems collectively.

According to a study , in a team, task completion can be independent , when each team member completes their own activities, sequential , when activities go from one team member to another, reciprocal , when activities are done back-and-forth between team members, or intensive , when all team members work on activities and problem-solving simultaneously.

Recruiters want to get to know more about your ideal teamwork process model and how you connect with others to solve problems.

Your answer will tell them if you’re a good team problem-solver, team player, and if you’re able to give and share credit, as well as take responsibility if something goes wrong.

Behavioral problem-solving sample answer

“Can you describe a situation where you had to use your problem-solving skills to make a decision?”

Situational problem-solving questions

Situational problem-solving questions put you in a hypothetical situation, present a problem, and ask for your opinion/solution.

Even if you haven’t encountered a similar situation in the past, it will help you to draw parallels from your experience to create answers to these questions.

How would you respond if a high-priority project was suddenly delayed, jeopardizing the deadline?

Your answer to this question will tell recruiters about your flexibility, time and task organization, prioritization, as well as how you handle pressure.

An ideal employee will be able to think quickly and adapt to unforeseen circumstances, all the while remaining calm and composed. You’ll want to aim at displaying these qualities in your answer.

Imagine a scenario where your manager was unavailable, but a client had an urgent issue – what would you do?

Taking the lead and taking calculated risks shows that a person has outstanding problem-solving skills and is not afraid to take initiative, which shows leadership potential.

Your answer to this question needs to demonstrate your ability to quickly analyze information, weigh pros and cons of a situation, and make decisions on the spot. This is especially important if you’re applying for leadership positions, like a team leader or a project manager.

If you encountered a high-stress situation that required you to stay calm and focused, how would you handle it?

Recruiters and hiring managers want to assess your ability to handle stress, make rational decisions, and maintain a focused approach in tricky, high-pressure situations.

Make sure to provide them with relevant examples from your past that will paint a picture of your skills and abilities. This is especially relevant for high-pressure positions such as police officers, lawyers, financial analysts, and similar.

Situational problem-solving sample answer

“Imagine you’re faced with a tight deadline, but you’ve encountered a significant roadblock. How would you handle this situation?”

Technical questions about problem-solving

Technical problem-solving questions are based on the technical knowledge that underlies each role. They aim to check your expertise or the means by which you connect the dots or obtain information if you don’t possess it.

Will you sort through the documentation to find a solution? Or is your first reaction to recall a past experience? Perhaps you prefer connecting with an expert or a coworker with more experience than you. Or you’re the type of person to synthesize your existing knowledge and try to find a solution through trial and error. Maybe you’ll turn to a book or a course? Whatever it is, recruiters would like to know.

There are many ways to solve these problems and your preferred strategies will give recruiters insight into how you think and act.

Examples of technical questions about problem-solving are:

  • How would you assess and resolve a performance issue in a web application?
  • Describe your approach to troubleshooting a networking issue that spans multiple devices.
  • How would you approach debugging a piece of software with limited documentation?
  • How would you deal with an angry VIP customer if your boss was away?
  • What would you do if you noticed a decline in the ROI of your team?

💡 Bear in mind that, with the rapid development of AI, the majority of technical tasks might be overtaken by robots in the future. That’s why it’s important that you work on your non-technical skills, too. Employers are already admitting that problem-solving skills are the second most important skill they’re looking for. For this reason, researchers are working hard to find and develop frameworks for helping people improve their problem-solving capabilities — you can read more about it in this paper on problem-solving skills among graduate engineers .

Technical problem-solving sample answer

“How would you troubleshoot an error in a software product that has been released to customers?”

✅ Pro tip: Practicing in advance is the only way to make sure your answer is flawless! The Mock Interview Tool will help you record your answer and get instant feedback on its quality and delivery. From power words and your pace of speech to “ummm” counter and eye contact, you’ll get help on how to improve in no time!

Our tool helped AJ land his first job in tech and get 7 job offers in the process . “I think Big Interview was super helpful in that aspect of having canned answers for every possible scenario and being in the moment of answering those questions.”, said AJ.

Big Interview Mock Interview Tool

Problem-Solving Interview Questions: Popular Opinions vs. Expert Advice

Now that we covered different types of problem-solving questions and how to answer them, we decided to dive into popular forums and see what job-seekers have to say on this topic. We picked pieces of advice that resonated with the community and confronted them with expert-backed best practices. Let’s see where we stand.

IndianaJones Jr on Reddit said : “If I was an interviewer asking this question, I would expect a personalized answer relevant to yourself, not to specific projects. At least that’s my interpretation.

“What are your experiences in problem-solving?” 

Sample answer: Generally, when I’m working on a project I find it’s easier to start at the end and work backwards. I use that to get a broad strokes idea of where my work needs to take me on any particular project and then I head in that direction. I find that when I get to specific problems I can get too stuck on using tried and true methods so I try to encourage myself to use out-of-the-box solutions. For example [your example here]…”

Career expert comments:

The “bones” of this sample answer are solid. It puts emphasis on breaking down the candidate’s thought process and displays patterns through which the candidate solves problems and learns along the way. However, the most important part of the answer — the actual example of a candidate’s problem-solving skills put to practice — remains a placeholder. Remember, the more specific you get in your answer, the better the impression you make on the interviewer. So here, I recommend paying equal attention to a specific situation in which you solved a problem and using the STAR method to tell that story.

Ambitious_Tell_4852 , when discussing the question “Give an example of a challenge you faced and how you overcame it,” said: 

“Clearly, that is the standard trick question designed for a prospective new hire to tell a prospective employer about his/her professional weaknesses. Oldest “negative Nelli’’ question imaginable during the interview process. Always keep your answer thorough and positive albeit sickeningly sugar-coated! 😁”

This is, straight-out, a bad piece of advice. If an interviewer wants to hear about your weaknesses, they will ask “What is your greatest weakness?” 

A question about overcoming a challenge isn’t a trick question at all. I’d argue it’s actually an opportunity to share some of your proudest wins. But when it comes to answering this question, it’s true that your answers do need to be thorough and positive. This doesn’t mean you need to sugar-coat anything, though. Interviewers don’t want to hear you downplaying your challenges. On the contrary, they want to hear you speak about them honestly and explain what you learned from them. And being able to do so puts a healthy, positive spin on the situation. To put it shortly: provide a real example from your past, answer this question honestly, and emphasize the results and lessons learned. 

Here’s an opinion from a hiring manager, Hugh on Quora, about how to answer a question about a time you needed to solve a problem:

“It really doesn’t matter what the problem you describe is or how you solved it. What I am looking/listening for is 1) the size of the problem (the bigger, the better, a broken shoelace before going out on a date is not an impressive problem) and 2) a step-by-step process to a satisfactory solution (if suddenly all variables fell into place does not show me that you solved the problem — you were just there when it solved itself).

I am also looking/listening for an example of how you solve a problem after you are hired. I may have to explain it to my superiors, and I would like to know that I have a complete and accurate story to tell.”

Career expert comments:  

A good piece of advice from someone who has first-hand hiring experience. When talking about problem-solving, a detailed description of your process is key. The only thing I wouldn’t agree with is having to choose a “big” problem. If you do have experience solving a big problem, that’s great. But sometimes you won’t have a major problem to talk about, and it largely depends on your level of experience and your position. So pick a relevant difficulty, even if it’s not that big, in which you displayed skills relevant to the role you’re applying for.

  • Problem-solving skills encompass your logical inference, technical knowledge, adaptability and innovation, leadership potential, decision-making, productivity, and collaboration.
  • Because these skills are important in the workplace, there’s a variety of problem-solving interview questions recruiters will ask to assess you.
  • Some of them include behavioral, situational, or technical problem-solving questions.
  • In order to answer these questions, you need to be aware of your thought processes when faced with a problem.
  • In your answer, be as specific as you can and use the STAR format whenever possible.
  • Make sure to highlight outcomes, results, or lessons learned.
  • As always, the best strategy is to anticipate these questions and prepare rough answers in advance. Including practicing your answer so you’re confident for your interview.

____________________

Need help with your job search? There are 3 ways we can help you:

  • Tired of interviewing and not landing the job? Discover actionable lessons and interview practice here (Rated with 4.9/5 by 1,000,000 users).
  • Learn how to talk about your proudest accomplishments without bragging or underselling yourself.
  • Learn how to answer tricky questions about conflict resolution in the workplace.

How can I improve my problem-solving skills?

Stay in the loop with new technologies and trends. Accept challenges and problems as a way to grow, don’t panic over them. Acquire a systematic approach to analyzing problems, break them down into smaller components which will help you discover root causes and devise a solution plan. Practice logical thinking, evaluating evidence, and staying objective. And give yourself time. Perhaps not surprisingly, studies suggest that the more business experience you have, the better you become at problem-solving.

Are there specific resources available to practice problem-solving interview questions?

There’s a variety of resources available to you, such as courses and Youtube tutorials, Facebook/LinkedIn groups, forums such as Reddit and Quora, books, or online platforms like Big Interview. If you’re trying to develop technical problem-solving skills, you might benefit from relevant platforms’ knowledge bases or YT channels; but if you’re looking specifically for how to answer interview questions, platforms like Big Interview are the way to go.

How should I handle a question about a problem-solving scenario I have not encountered before?

Don’t be afraid to ask additional questions for clarification. If you’ve never dealt with this problem before, be honest about it but answer how you would solve the problem if you were faced with it today. Break the problem down into manageable steps, try to recall a similar situation from your own experience that could help you draw parallels, and propose several different solutions.

Can I talk about my problem-solving experiences derived from non-professional settings such as student projects?

Yes, especially if you’re a recent graduate or a candidate with limited experience. You can use experiences and examples from student projects, extracurricular activities, and you can even use examples from your personal life, as long as you present them in a professional manner and connect them to the position you’re applying for. Remember to highlight the results, as well as the skills that helped you solve the problem and that are relevant to the position you’re applying for.

Are there any common mistakes to avoid when answering problem-solving questions during an interview?

The most common mistake is not preparing in advance which causes rambling. You need to make sure that your answer is informative and well-structured, and that you’re not only presenting a solution but also laying down the steps to display your logical reasoning. Make sure not to forget to give credit to teammates if they contributed to solving the problem you chose to talk about. Finally, for a coherent and informative presentation, make sure you use the STAR method.

What can I do if I don’t know the answer to a technical problem-solving question in an interview?

Handle it professionally. You can always try to reach a conclusion by breaking down the problem and thinking out loud to show your thinking mechanism. Draw parallels between the problem at hand and another similar problem you encountered before. Lay down possible solutions, even if you’re not sure they’ll work, and be transparent — feel free to tell the recruiter you’re not sure how to answer it, but make sure you emphasize that you’re open to learning.

Can I ask for help or guidance from the interviewer during a problem-solving question?

Avoid asking for help directly, but ask for clarification in case something is unclear or if you need additional information. Sometimes, the interviewer will take the initiative and provide you with hints to encourage you and see how you think.

How can I demonstrate creativity and resourcefulness when answering problem-solving questions?

It’s all about storytelling! Preparing in advance will provide some space for displaying your creativity. You can do it by making fun analogies or drawing parallels from well-known situations; or making pop-culture references.

tricky problem solving interview questions in java

Maja Stojanovic

Briana Dilworth

Fact Checked By:

Michael Tomaszewski

Turn interviews into offers

Share this article

  • Big Interview
  • Plans & Pricing
  • Higher Education
  • Editorial Process
  • Resume Templates
  • Interview Preparation
  • Interview Q&A
  • Career Advice
  • Create an Account
  • Knowledge Base

©️ 2024 Skillful Communications, Inc. | Big Interview is a trademark of Skillful Communications, Inc.

Terms | Privacy Policy

  • Guidelines to Write Experiences
  • Write Interview Experience
  • Write Work Experience
  • Write Admission Experience
  • Write Campus Experience
  • Write Engineering Experience
  • Write Coaching Experience
  • Write Professional Degree Experience
  • Write Govt. Exam Experiences
  • HashedIn by Deloitte Interview Experience for Software Engineer 2021
  • HashedIn by Deloitte Interview Experience for Embedded Software Engineer
  • Hashedin by Deloitte Interview Experience for Software Engineer-1 (Off-Campus)
  • Deloitte Interview Experience For Software Engineer
  • HealthEdge Interview Experience For Software Developement Engineer (2024)
  • Hashedin by Deloitte Interview Experience for SDET 2022
  • Hashedin by Deloitte Interview Experience for Trainee + Software Engineer Role | Off-Campus 2021
  • HashedIn Interview Experience for Software Engineer-II (Bangalore)
  • HashedIn by Deloitte Interview Experience for DevOps Engineer-1
  • HashedIn Interview Experience for Software Engineer-II | May 2021
  • Hashedin by Deloitte Interview Experience for Internship + Software Engineer (Off-Campus)
  • Hashedin by Deloitte Interview Experience for Trainee + Software Engineer Role (Off-Campus)
  • HashedIn by Deloitte Interview Experience for SDE2
  • Deloitte Interview Experience for Product Engineer 2024
  • Deloitte Interview Experience for Software Engineer (Off-Campus)
  • Bobble Ai Interview Experience for Software Engineer (Intern+FTE) 2022
  • HashedIn by Deloitte Interview Experience 2021
  • Deloitte Interview Experience for Software Developer
  • HashedIn by Deloitte Interview Experience for SDE-1 | Off-Campus (Experienced)

HashedIn by Deloitte Interview Experience for Software Engineer | Feb 2024

Drive date: 18th Feb 2024

Verdict: selected

Current: working as a Software engineer 1 at HashedIn

Round 1 Online assessment on Codility platform

No of problems – 3 DSA-based questions Q1 : easy, based on array and sorting

Q2: Hard, based on graph

Q3: Medium based on DP Assessment duration: 1hr 30 minutes

Round 2: Technical Interview 1

Started with DSA questions

Q1. Buy stock span problem

Q2. Implement a stack using the LinkedIn list

Q3. Kth largest no. in an array, I used min heap queue for this so he asked why I took this approach and how internally heapify works.

Then shifts to DBMS concepts and SQL queries

Interview duration: 45 minutes

Round 3: Technical Interview 2

Started with questions from AWS (it was mentioned in my resume)

Then asked to design database of IRCTC that includes all tables, their attributes and their relationships among them, asked to optimise it further.

Proceeds with 2 DSA questions

Q1. Simple array question involves swapping (easy)

Q2. Trapping Rain water problem (leetcode Hard) (Monotonic stack, DP)

Interview duration: 1hr 20 minutes

Round 4: HR/Fitment round

Behavioural questions, family background, preferred location, previous internship experience (if any). I would it was just a fun round. Follow up questions were there for tech problems, so choose your words wisely and be confident.

Connect with me on LinkedIn: Ankur Mishra

Please Login to comment...

Similar reads.

  • Write It Up 2024
  • Experiences
  • Interview Experiences

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Java Date Time Tricky Interview question and answer ? || Java tricky

    tricky problem solving interview questions in java

  2. Java Tricky and Important Interview questions and answers

    tricky problem solving interview questions in java

  3. Java Tricky Question Challenge

    tricky problem solving interview questions in java

  4. 15 tricky Java Interview Questions & Answers

    tricky problem solving interview questions in java

  5. Problem Solving Interview Questions Java

    tricky problem solving interview questions in java

  6. Top 10 Java tricky interview questions

    tricky problem solving interview questions in java

VIDEO

  1. TRICKY PROBLEM SOLVING GAME

  2. Java 8 Stream API

  3. The unfair way I got good at Leetcode

  4. Mastering Java Interview Questions: Common Challenges and Expert Answers

  5. JS Problem Solving Questions 01

  6. Java Interview Question and Answers

COMMENTS

  1. Top 50 Tricky Java Interview Questions and Answers

    Tricky Java interview questions are not your typical run-of-the-mill inquiries. These questions are designed to test your in-depth knowledge of Java, problem-solving skills, and ability to think critically under pressure. They often go beyond the basics and challenge you to demonstrate a deep understanding of the language, its nuances, and its ...

  2. Tricky Java Interview Questions

    We can solve the question by using our analytical thinking even if we do not know the answer. In this section, we will cover some tricky Java programs and tricky interview questions. 1) Consider the following code and guess the output. 2) Consider the following code and guess the output. 3) Consider the following code and find the output.

  3. Tricky Java interview questions for 7 years of Experience

    5. Java is a popular and widely used programming language that is used for developing a wide range of applications, from desktop and mobile applications to web applications and enterprise software ...

  4. 15 tricky Java Interview Questions & Answers

    For instance, you can include problem-solving questions to evaluate a candidate's logical thinking and creativity and behavioral questions to uncover their teamwork and conflict resolution approach. ... Tricky Java interview questions are vital in assessing your Java developer candidates' technical competency. However, you should also use ...

  5. 16 Tricky Java Interview Questions for Experienced in 2023

    10. What do System.gc () and Runtime.gc () methods do? These suggest to JVM that garbage collection can be started; however, the JVM may finally run the garbage collector at a later time. System.gc () is a class method and Runtime.gc () is an instance method. 11. Distinguish between throw and throws in Java.

  6. Top 50 Java Programming Interview Questions

    4. Write a Java program to check if the given number is a prime number. You can write a program to divide the given number n, by a number from 2 to n /2 and check the remainder. If the remainder is 0, then it's not a prime number. The following example code shows one way to check if a given number is a Prime number:

  7. 50 Interview Questions About Java (With Answers)

    Enhanced Problem-Solving Abilities. Java, as a programming language, is known for its complexity and versatility. Professionals skilled in Java possess enhanced problem-solving abilities, as they are trained to think logically and analytically. ... Here are five tips to help you effectively answer skill-based interview questions on Java: 1 ...

  8. Top 10 Java Tricky Coding Interview Questions

    Explanation: JVM sets a constant pool in which it stores all the string constants used in the type.If two references are declared with a constant, then both refer to the same constant object. The == operator checks the similarity of objects themselves (and not the values in it). Here, the first comparison is between two distinct objects, so we get s1 and s2 not equal.

  9. The Java Interview Prep Handbook

    Java is well-known for its robustness in Object-Oriented Programming (OOP), and it provides a comprehensive foundation essential for developers at every level. This handbook offers a detailed pathway to help you excel in Java interviews. It focuses on delivering insights and techniques relevant to roles in esteemed big tech companies, ensuring ...

  10. Tricky Java Interview Questions for 7 Years Experience

    Navigating tricky java interview questions for 7 Years Experience requires a solid grasp of Java fundamentals, coupled with a strategic approach to problem-solving. Interviewers may delve into…

  11. Core Java Interview Questions and Answers (2024)

    This is a java tricky interview question frequently asked in java interviews for the experienced. The output will be like this because, when the java program is compiled and gets executed, then there are various steps followed for execution. ... Write a Java program for solving the Tower of Hanoi Problem. public class InterviewBit { //Recursive ...

  12. 42 Advanced Java Interview Questions For Senior Developers

    Java 165. Answer. The JVM has a heap that is the runtime data area from which memory for all class instances and arrays is allocated. It is created at the JVM start-up. Heap memory for objects is reclaimed by an automatic memory management system which is known as a garbage collector.

  13. 10 Tricky Programming Questions to Ace Your Java Interview

    Answer: This question is tricky because, unlike the Integer class, where the MIN VALUE is negative, the Double class's MAX VALUE and MIN VALUE are both positive integers. Double.MIN VALUE is 2^ (-1074), a double constant with the least magnitude of all double values. Also Read: 4 Professional Advantages of Summer Training for CSE Students.

  14. Java Coding Interview Questions You Need to Know

    In a Java coding interview, candidates often encounter tricky questions that test their problem-solving skills and critical thinking ability. These questions go beyond the basics and require a deep understanding of Java concepts. ... Tricky Java coding interview questions are designed to challenge a candidate's problem-solving abilities and ...

  15. 200+ Core Java Interview Questions and Answers (2024)

    Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and performance. In this article, we will provide 200+ Core Java Interview Questions tailored for both freshers and experienced professionals with 3, 5, and 8 years of experience.

  16. 51 Java Programming Interview Questions (And Sample Answers)

    Here's a list of additional java interview questions that hiring managers may ask you: 41. Write a program to sort a sequence of numbers in ascending order. 42. Using Java 8 date-time library in CLASSPATH (package private) file, write a program that shows how you can add time to any time with respect to midnight on Jan. 1, 2000.

  17. Top 10 Tough Core Java Interview Questions Answers for Programmers

    In this article, I am going to share you with my Top 10 tough core Java interview questions and answers, which may help you in the Java interview. 10 tough Java interview question and answer Here is my list of 10 tough or tricky Java interview questions. These questions are mostly from Core Java and I have not included J2EE questions. As I said ...

  18. Review these 50 questions to crack your Java programming interview

    This list focuses on beginners and less experienced devs, like someone with 2 to 3 years of experience in Java. 1) How does Java achieve platform independence? ( answer) hint: bytecode and Java Virtual Machine. 2) What is ClassLoader in Java? ( answer) hint: part of JVM that loads bytecodes for classes.

  19. Java 8 Interview Questions(+ Answers)

    In Java 8, this problem was solved by using the default method. For example, the Collection interface does not have a forEach method declaration. Thus adding such a method would simply break the whole collections API. ... In this article, we explored several important technical interview questions with a bias on Java 8. This is by no means an ...

  20. Ace the top 15 Java algorithm questions for coding interviews

    Algorithm-based questions are a staple of any modern coding interview, as they demonstrate your problem-solving and critical thinking skills. To make sure you don't get caught off guard in your next Java interview, we've put together 15 of the most common algorithm coding questions used by most tech companies and recruiters across the industry. ...

  21. Top 50 Java Programs from Coding Interviews

    10 Dynamic Programming Interview Questions; 10 Matrix based Coding Problems for Interviews; 25 Recursion based Coding Interview Questions and Answers; Thanks for reading this article so far, if you like these Java programs, then please share with your friends and colleagues, if you have any question or problem, then please drop a comment.

  22. Java Tricky Interview Questions

    Sometime back I wrote an article on Top 50 Java Programming Questions. Our readers liked it a lot. So today we will look into some tricky interview questions in Java. Java Tricky Interview Questions. These are programming questions but unless you have a deep understanding of Java, it will be hard to guess the output and explain it. 1. Null as ...

  23. Top 21 String Programming and Coding Interview Questions With ...

    18) How do you count the number of words in String? ( solution) Write a program to count a number of words in a given String. The words are separated by the following characters: space (' ') or newline ('\n') or tab ('\t') or a combination of these. For example, if input "Java is great" your program should print 3.

  24. Top 20 Problem Solving Interview Questions (Example Answers Included)

    MIKE'S TIP: When you're answering this question, quantify the details. This gives your answer critical context and scale, showcasing the degree of challenge and strength of the accomplishment. That way, your answer is powerful, compelling, and, above all, thorough. 2. Describe a time where you made a mistake.

  25. Java Exercises

    We hope these exercises have helped you understand Java better and you can solve beginner to advanced-level questions on Java programming. Solving these Java programming exercise questions will not only help you master theory concepts but also grasp their practical applications, which is very useful in job interviews. More Java Practice Exercises

  26. Top 50 Array Coding Problems for Interviews

    Find the first repeating element in an array of integers. Solve. Find the first non-repeating element in a given array of integers. Solve. Subarrays with equal 1s and 0s. Solve. Rearrange the array in alternating positive and negative items. Solve. Find if there is any subarray with a sum equal to zero.

  27. Problem-Solving Interview Questions: How-to + Examples

    Discover the best way to answer interview questions about problem-solving and ace your next job interview. ... Problem-solving skills are difficult to describe and quantify: they're a combination of different hard and soft skills such as logical inference, technical knowledge, adaptability and innovation, leadership potential, decision-making ...

  28. HashedIn by Deloitte Interview Experience for Software Engineer

    I've 2 years of experience in Software Development and I was asked questions mostly on the backend and Java. Round 1: Technical This was a F2F Technical Round but happened online. In this round, the interviewer wanted to test the problem-solving skills and the solution approach.He had given me 2 problems