50 Java Interview Questions + 30 Scenario Based Q&A

13 Jul
  1. Object Oriented Programming (OOPs) Interview Questions
  2. 50 Java Interview Questions + 30 Scenario Based Q&A
  3. Cracking the Code: 200 Interview Q&A for Software Developers
  4. Performance and Optimization Interview Questions
  5. Caching Interview Questions and Answers
  6. Error Handling and Debugging Interview Questions
  7. C Programming Language Interview Questions
  8. C++ Programming Interview Questions

Introduction

Java is one of the most popular and widely used programming languages today. It is important for aspiring Java developers to be well-prepared for technical interviews which typically involve many Java programming questions.

The interviewers often ask a mix of theoretical Java questions to test the conceptual knowledge and practical programming questions to evaluate the coding skills. In this article, we provide a compilation of commonly asked Java interview questions and sample answers to help candidates prepare effectively.

The questions cover core Java basics, OOP concepts, classes and objects, methods and constructors, access modifiers, inheritance, polymorphism, abstraction, interfaces, Java collections, exception handling, multithreading and concurrency. There are also scenario-based Java questions that can be asked in interviews to check how candidates can apply the language features to build real-world applications.

50 interview questions and answers

1. What is Java?
Java is a high-level, object-oriented programming language. It is a general-purpose concurrent and class-based language that is designed to have as few implementation dependencies as possible.

2. What are objects and classes in Java?
Objects are basic building blocks in Java that contains state and behavior. Classes are templates that define objects and their behavior.

3. What is JVM and JRE?
JVM (Java Virtual Machine) is the runtime environment for Java programs. It converts Java bytecode into machine language. JRE (Java Runtime Environment) is the implementation of JVM that provides core libraries and other components to run Java programs.

4. Explain the platform independence of Java.
Java is compiled to bytecode that can run on any platform with a JVM. The JVM interprets the bytecode into native machine code. This makes Java platform independent.

5. What are constructors in Java?
Constructors are special methods in Java that are used to initialize objects. The constructor is invoked when an object of a class is created. It has the same name as the class and does not have a return type.

6. What is method overloading and overriding in Java?
Method overloading is defining methods with the same name but different parameters. Overriding is providing a specific implementation of a method already defined in the parent class.

7. What is abstraction in Java?
Abstraction refers to hiding the implementation details and exposing only the functionality to users. Abstract classes and interfaces are used to achieve abstraction in Java.

8. What are Java packages?
Packages in Java are collections of related classes and interfaces that are bundled together. Packages provide namespace management and access control in Java.

9. What is final keyword in Java?
The final keyword is used to apply restrictions on classes, methods and variables. Final class cannot be inherited, final method cannot be overridden and final variable value cannot be changed.

10. What is static in Java?
Static is a keyword in Java used to denote a class member belongs to a type rather than to an instance. Static members can be used without creating an object of class.

11. What is encapsulation in Java?
Encapsulation is the mechanism of wrapping data (variables) and code acting on data (methods) together as a single unit. In Java, encapsulation is achieved by making fields private and providing public setter and getter methods.

12. What is inheritance in Java?
Inheritance represents parent-child relationship between classes in Java. It allows a derived class to inherit commonly used state and behavior from its parent class.

13. What is polymorphism in Java?
Polymorphism means ability to take different forms. In Java, polymorphism allows assigning a variable and method call to take different forms or classes. Method overloading and overriding uses polymorphism.

14. What is JIT compiler in Java?
JIT (Just-In-Time) compiler in Java converts bytecode into native machine code at runtime when required by the program. It improves performance by compiling bytecode lazily.

15. What is multithreading in Java?
Multithreading allows concurrent execution of multiple parts of a Java program. The main ways to create threads in Java are extending Thread class and implementing Runnable interface.

16. Explain different ways to create a thread in Java.
There are two ways to create a thread in Java – 1. Extending Thread class 2. Implementing Runnable Interface. Runnable is preferred because Java does not support multiple inheritance.

17. What are access modifiers in Java?
Java provides access control through public, protected, private and default modifiers. Public grants access from anywhere. Private restricts access to the class itself. Default and protected have specialized uses.

18. What is Collections Framework in Java?
Java Collections Framework provides ready-made architecture to store and manipulate group of objects. It contains interfaces like List, Set, Queue and classes like ArrayList, LinkedHashSet, PriorityQueue etc.

19. What are different types of inner classes in Java?
– Nested (static) inner class
– Inner class
– Local inner class
– Anonymous inner class

They allow logical grouping of classes and interfaces and access to the outer class.

20. What is Java API and where is it documented?
Java API (Application Programming Interface) is a collection of pre-built packages, classes and interfaces in Java. It is documented at https://docs.oracle.com/en/java/javase/index.html

21. What is JDBC API in Java?
JDBC (Java Database Connectivity) is an API used to connect and execute queries to a database from Java. JDBC provides a set of interfaces that allows connectivity to relational databases.

22. What are the basic interfaces of JDBC API?
The core interfaces of JDBC API are – Driver, Connection, Statement and ResultSet that allows connecting and interacting with a database.

23. What are the different types of JDBC drivers?
There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

24. What is singleton class in Java and how can we make a class singleton?
Singleton class means that only one instance of the class can be created. Singleton pattern involves a single private constructor, a static variable and a static public method that returns the instance.

25. What is Java Serialization API?
Java Serialization API provides a standard mechanism to serialize objects to stored or transmitted across streams. Only serializable objects can be serialized.

26. How can we convert bytes to objects and vice-versa in Java?
We can convert bytes to objects and vice-versa using serialization and deserialization in Java. ObjectOutputStream is used to convert objects to bytes and ObjectInputStream is used to recreate objects from bytes.

27. What are anonymous inner classes in Java?
Anonymous inner classes are inner classes without a name declared and instantiated in a single expression using the new keyword. They are used for inline implementation of interfaces.

28. What is reflection API in Java and why is it useful?
Java reflection API allows inspecting and modifying runtime behavior of classes at runtime. It is useful to introspect objects and call methods dynamically at runtime without knowing the names at compile time.

29. What is autoboxing and unboxing in Java?
Autoboxing is automatic conversion of primitive types to object wrapper classes. Unboxing is the reverse process of converting wrapper objects to primitives. They were introduced in Java 1.5.

30. What is final, finally and finalize in Java?
final is a keyword – final class can’t be inherited, final method can’t be overridden, final variable value can’t change. finally is a block – used with try/catch to put code that executes always. finalize is a method – called by Garbage collector before object is collected.

31. What is try-with-resources in Java?
try-with-resources is a way to automatically close resources after usage without needing an explicit finally block. Any class that implements AutoCloseable interface can be used in try-with-resources.

32. What is multi-catch block in Java?
A multi-catch block allows handling multiple exceptions in a single catch block instead of using multiple catch blocks for different exceptions. The catch parameter is specified using pipe (|) symbol.

33. What are the advantages of Java?
Simple, Object-Oriented, Portable, Platform independent, Secured, Robust, Architecturally neutral, Interpreted, High Performance, Multithreaded, Distributed, Dynamic

34. What are the disadvantages of Java?
Not suitable for low-level programming. Limited speed. No unsigned data type. Backward incompatible.

35. What is namespace in Java?
Namespace is a naming system to organize classes in Java packages. It resolves naming collisions and confusions and allows fully qualified name to uniquely identify classes, interfaces etc.

36. What is JIT compiler in Java?
JIT (Just-In-Time) compiler is used to improve the performance. It converts bytecode into native machine language when required by the running Java program.

37. What is the difference between path and classpath variables?
PATH is an environment variable used by operating system to locate executables. Classpath is specific to Java and used by JVM to locate Java bytecode files (classes).

38. What is Anonymous inner class in Java?
Anonymous inner class is an inner class without a name declared and instantiated in a single expression using the new operator. Commonly used for simplified event handling.

39. What is difference between Heap and Stack memory?
Heap memory is used by all parts of the application whereas stack memory is used only by one thread of execution. Objects are created in Heap, Stack is used for local primitive variables and references to objects in Heap.

40. What is Java String Pool?
Java String Pool refers to collection of Strings stored in heap memory. String literals and constants are stored in the String pool for reuse to optimize memory usage.

41. How is a string immutable in Java?
In Java, string objects are immutable meaning their state cannot be changed once created. Whenever changes are made to a string, a new instance is created. This optimizes performance by reusing strings from pool.

42. What is ThreadPoolExecutor in Java?
ThreadPoolExecutor is a thread pool implementation added from Java 5 that provides more configurable thread pools to execute tasks. It allows configuring pool size, rejection policies, thread factories etc.

43. What is Java Memory Model?
It is a specification that describes the shared memory system defined by the Java programming language and virtual machine including visibility and atomicity guarantees on shared data.

44. What is memory leak in Java?
Memory leak occurs when objects are no longer used by the application but Garbage Collector fails to recognize them as unused. This results in out of memory errors if too many objects are unreferenced.

45. What is shallow copy and deep copy in Java?
Shallow copy is copying an object’s field references into another instance. Deep copy is making separate copy of all the objects in the original object graph.

46. What are transient and volatile keywords in Java?
transient – skip field during serialization, volatile – field will not be cached and always read from main memory.

47. What is Executor Framework in Java?
The Executor framework in Java provides an abstraction over management of threads. Executors can schedule asynchronous tasks and control concurrency transparently using thread pool.

48. Explain Generics in Java?
Generics allow defining type-safe classes, interfaces and methods which work with different types while avoiding duplicity. Generics work only with reference types in Java.

49. What is Comparable and Comparator interface in Java?
Comparable is used to provide natural ordering of objects of a class. Comparator provides custom ordering and added flexibility of sorting objects.

50. Explain different ways to iterate over a collection in Java?
Iterating collections can be done through Iterator, for-each loop, forEach(), forEachRemaining() and ListIterator. Iterator allows removing elements during iteration while ListIterator can iterate in reverse.

30 scenarios based interview questions and answers

1. How will you find if a string contains only digits in Java?
I can use matches() method of string to match the given string against a regular expression that matches digits like below:

String str = “123”;
boolean result = str.matches(“[0-9]+”);

2. How can you swap two numbers without using a temporary variable in Java?
We can use arithmetic operators to swap two numbers:

int a = 5;
int b = 10;

a = a + b;
b = a – b;
a = a – b;

3. How can you reverse a string in Java without using any library method?
We can write a for loop which starts from the end of the string and appends each character to form the reverse string.

StringBuilder reversed = new StringBuilder();

for(int i = str.length()-1; i >= 0 ; i–){
reversed.append(str.charAt(i));
}

4. How can you find duplicate elements in an array in Java?
Iterate through array and store elements as key in a HashMap. If element is already present, print it as duplicate. Time complexity is O(n) and space is O(n).

5. How can you find the largest and smallest number in an unsorted integer array in Java?
Iterate through array keeping track of min and max element so far. Time complexity is O(n) to traverse array once.

6. How can you remove duplicates from an array without using any library in Java?
Add elements to HashSet which lets only unique elements. Then add set back to array. Time complexity is O(n).

7. How can you find the factorial of a number in Java?
Factorial can be calculated using recursion. Base case is f(0) = f(1) = 1. General case is f(n) = n * f(n-1).

8. How can you check if two string are anagrams in Java?
1. Check if length is same
2. Convert strings to char array
3. Sort the char arrays
4. Check if both arrays are equal

9. How can you design a vending machine in Java?
Vending machine would have attributes like currentQuantity, pricePerItem. Methods like insertMoney(), selectItem(), dispenseItem(), giveChange() which implement the vending logic.

10. How can you check if a string contains only alphabets in Java?
Use matches() with regex “[a-zA-Z]+” to check if string has only alphabets.

11. How can you find whether a year is leap year or not in Java?
If year is divisible by 4 and not 100, or divisible by 400, then it is a leap year.

if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
System.out.println(“Leap year”);
else
System.out.println(“Not a leap year”);

12. How can you swap two Strings without using a temporary variable?
We can use StringBuilder’s append() method to swap strings.

string1 = string1.concat(string2);
string2 = string1.substring(0, string1.length()-string2.length());
string1 = string1.substring(string2.length());

13. How can you find the middle element of a linked list in Java?
– Iterate through linked list to find total length
– Traverse till length/2 to find middle element

14. How can you reverse a linked list iteratively and recursively?

Iterative:

1. Initialize prev, current and next
2. In loop, make next = current.next, current.next = prev, prev = current

Recursive:

1. Base case: head or head.next is null
2. Recursively call reverse() on head.next
3. Attach head to the end of reversed list

15. How can you find if a linked list contains a cycle in Java?
Use two pointers – fast that moves 2 nodes ahead and slow that moves 1 node. If cycle exists, fast and slow will meet at some node.

16. How can you implement a stack using array and linked list?

Array: Use array, top pointer and push(), pop() operations.
Linked List: Use linked list node with next pointer. top pointer and push(), pop() operations.

17. How can you implement a queue using array in Java?
Use array, front and rear index, enqueue() and dequeue() operations. Handle queue full and empty conditions.

18. How can you find all permutations of a String in Java?
Use recursion. For each char, fix it and find permutations of remaining chars. Add fixed char to beginning and append permutations.

19. How can you design a parking lot using OOPS in Java?
ParkingLot class has attributes like totalSpots, availableSpots. Car class has regNo, color etc. Entry and Exit classes manage parkings. Use ArrayList to store parked cars.

20. How can you implement autoboxing and unboxing in your own classes?
Autoboxing: Have constructors that take primitive types.
Unboxing: Provide get methods that return primitives.

21. How can you find the length of a linked list iteratively and recursively?

Iterative: Initialize length to 0. Traverse linked list and increment length.

Recursive:
Length(head)
if head == null
return 0
else
return 1 + length(head.next)

22. How can you find the height of a binary tree in Java?
Recursively calculate height of left and right subtrees.
Height is max of left height and right height plus 1 for root.

23. How is Bubble Sort algorithm implemented in Java?
Compare adjacent elements, swap if currentElement > nextElement. Largest element bubbles up towards end. Repeat until sorted.

24. How can you search for an element in a binary search tree in Java?
Start from root and traverse left if element is less than current node otherwise right. Return node if matching element is found.

25. How is Inheritance implemented in Java?
Using extends keyword. Single inheritance is supported. Child class inherits properties and methods except private from Parent.

26. How will you implement thread synchronization in Java?
1. Using synchronized keyword
2. Using concurrent collections
3. Using Lock interface
4. Using atomic classes from java.util.concurrent.atomic package

27. How can you avoid deadlock in Java?
– Avoid nested locks
– Using lock ordering
– Using lock timeouts
– Avoiding resource sharing between threads

28. How will you store different data types in ArrayList?
ArrayList can store only objects. Primitive data types need to be converted to object wrappers like Integer, Character etc.

29. How can you improve performance of ArrayList in Java?
Initialise ArrayList with optimal initial capacity to avoid resizing. Use ensureCapacity() before adding large elements to avoid reindexing.

30. How will you implement a HashMap in Java?
Use array of LinkedList for chaining. Compute index using hashCode() and compress to fit array. Handle collisions through linked list chaining.

 

Conclusion

Preparing a strong set of Java interview questions is crucial for aspiring Java developers to successfully clear the technical screening rounds. This collection of 50 Java theory questions and 30 practical scenario-based questions covers a wide range of topics and concepts typically assessed in Java interviews.

Learning the fundamentals and practicing these questions will help candidates master Java programming principles and be able to write code to solve problems. The sample answers provided illustrate how to structure and present your solutions to interviewers to best highlight your Java skills. With thorough preparation on these aspects, developers can confidently tackle Java interview questions and excel in their tech job interviews.



Leave a Reply

Your email address will not be published. Required fields are marked *