0% found this document useful (0 votes)
78 views

Java Interview Imp Questions

Interview questions
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

Java Interview Imp Questions

Interview questions
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Here are some common Java interview questions along with their answers:

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

**Answer:**

- **JDK (Java Development Kit)**: It is a software development kit that


provides tools for developing Java applications, including the compiler
(javac), the Java Runtime Environment (JRE), and other development tools.

- **JRE (Java Runtime Environment)**: It is a part of the JDK and provides the
environment to run Java applications. It includes the JVM and libraries
necessary for executing Java programs.

- **JVM (Java Virtual Machine)**: It is an abstract machine that enables a


computer to run Java programs. It converts Java bytecode into machine-
specific code.

### 2. What are the main principles of Object-Oriented Programming


(OOP)?

**Answer:**

The main principles of OOP are:

- **Encapsulation**: Bundling the data (attributes) and methods (functions)


that operate on the data into a single unit (class).

- **Abstraction**: Hiding the complex implementation details and showing


only the essential features of the object.

- **Inheritance**: Mechanism by which one class can inherit the fields and
methods of another class, promoting code reusability.

- **Polymorphism**: Ability of different classes to be treated as instances of


the same class through a common interface. It can be achieved through
method overloading and overriding.

### 3. What is the difference between `==` and `.equals()` in Java?

**Answer:**
- `==` checks for reference equality, meaning it checks whether two
references point to the same object in memory.

- `.equals()` checks for value equality, meaning it compares the actual


content of the objects. For example, two different String objects with the
same content will return true when using `.equals()` but false with `==`.

### 4. What is a constructor in Java?

**Answer:**

A constructor is a special method in Java that is called when an object is


instantiated. It initializes the object’s state and has the same name as the
class. It does not have a return type. There are two types of constructors:

- **Default Constructor**: A constructor with no parameters.

- **Parameterized Constructor**: A constructor that takes parameters to


initialize the object with specific values.

### 5. Explain the concept of method overloading and method overriding.

**Answer:**

- **Method Overloading**: It occurs when two or more methods in the same


class have the same name but different parameters (different type, number,
or both). It allows methods to perform similar functions with different inputs.

- **Method Overriding**: It occurs when a subclass provides a specific


implementation for a method that is already defined in its superclass. The
method in the subclass must have the same name, return type, and
parameters as the method in the superclass.

### 6. What is an interface in Java?

**Answer:**

An interface in Java is a reference type that is similar to a class but can only
contain abstract methods (without body) and static final variables
(constants). Interfaces are used to define a contract that classes must follow.
A class can implement multiple interfaces, allowing for multiple inheritance
of types.

### 7. What is the difference between `ArrayList` and `LinkedList` in Java?

**Answer:**

- **ArrayList**: It is implemented using a dynamic array. It allows for fast


random access and retrieval of elements but can be slower when adding or
removing elements from the middle of the list due to the need for shifting
elements.

- **LinkedList**: It is implemented using a doubly linked list. It allows for


faster insertion and deletion of elements at any position but has slower
access times for retrieving elements since it must traverse the list.

### 8. What is exception handling in Java?

**Answer:**

Exception handling in Java is a mechanism to handle runtime errors, allowing


the program to continue its normal flow. It uses the `try`, `catch`, `finally`,
`throw`, and `throws` keywords.

- **try**: Contains code that may throw an exception.

- **catch**: Catches and handles the exception.

- **finally**: Executes code after try/catch, regardless of whether an


exception was thrown.

- **throw**: Used to explicitly throw an exception.

- **throws**: Indicates that a method can throw exceptions, which must be


handled by the calling method.

### 9. What are the access modifiers in Java?

**Answer:**

Java has four access modifiers:


- **public**: The member is accessible from any other class.

- **protected**: The member is accessible within its own package and by


subclasses.

- **default** (no modifier): The member is accessible only within its own
package.

- **private**: The member is accessible only within its own class.

### 10. What is the purpose of the `static` keyword in Java?

**Answer:**

The `static` keyword is used to indicate that a particular member (variable or


method) belongs to the class itself rather than instances of the class. This
means:

- A `static` variable is shared among all instances of a class.

- A `static` method can be called without creating an instance of the class.

- It can access `static` members directly, but it cannot access non-static


members directly.

Basic Java Interview Questions:


1. What is Java?

a. Answer: Java is a high-level, object-oriented programming


language designed for portability and cross-platform
compatibility. It runs on the Java Virtual Machine (JVM), which
allows Java programs to be executed on any device that has a
JVM installed.
b.
2. What are the features of Java?

a. Answer: Key features of Java include:


i. Platform Independence: Write once, run anywhere
(WORA).
ii. Object-Oriented: Supports concepts like inheritance,
encapsulation, and polymorphism.
iii. Robustness: Strong memory management and exception
handling.
iv. Multithreading: Supports concurrent programming.
v. Automatic Garbage Collection: Helps manage memory
automatically.
vi.
3. Explain JDK, JRE, and JVM.

a. Answer:
i. JDK (Java Development Kit): A software development
kit that includes JRE, tools for compiling Java programs, and
other development tools.
ii. JRE (Java Runtime Environment): A part of JDK that
provides the libraries, Java Virtual Machine (JVM), and other
components necessary to run Java applications.
iii. JVM (Java Virtual Machine): An abstract machine that
enables Java bytecode to be executed, providing the
environment for running Java applications.
iv.
4. What is a Class and an Object in Java?

a. Answer:
i. Class: A blueprint for creating objects, defining properties
(attributes) and behaviors (methods).
ii. Object: An instance of a class. It contains data and
methods defined in the class.
iii.
5. What is the difference between a constructor and a method?

a. Answer:
i. A constructor is a special method invoked when an object
is created, used to initialize the object's properties. It has
the same name as the class and does not have a return
type.
ii. A method is a block of code that performs a specific task
and can be called when needed. It has its own name and
can return a value.
6. What is the 'main' method in Java?

a. Answer: The main method is the entry point for any standalone
Java application. It has a specific signature: public static void
main(String[] args). The JVM looks for this method to start the
execution of the program.
b.
7. Explain the concept of inheritance in Java.

a. Answer: Inheritance is a mechanism where one class (subclass)


can inherit fields and methods from another class (superclass). It
promotes code reusability and establishes a hierarchical
relationship between classes.
8. What are the different types of inheritance supported in
Java?
a. Answer: Java supports several types of inheritance:
i. Single Inheritance: A class inherits from one superclass.
ii. Multiple Inheritance (through interfaces): A class can
implement multiple interfaces.
iii. Multilevel Inheritance: A class inherits from a subclass.
iv. Hierarchical Inheritance: Multiple subclasses inherit
from a single superclass.
v. Hybrid Inheritance: A combination of two or more types
of inheritance.
vi.
9. What is polymorphism in Java?

a. Answer: Polymorphism is the ability of a single function or


method to operate in different ways based on the object or class
type it is acting upon. It is mainly achieved through method
overloading and method overriding.
10. What is method overloading and method overriding?
a. Answer:
i. Method Overloading: Multiple methods in the same
class can have the same name but different parameters
(type or number).
ii. Method Overriding: A subclass provides a specific
implementation of a method that is already defined in its
superclass.
iii.
11. Explain encapsulation and abstraction with examples.
a. Answer:
i. Encapsulation: The bundling of data (attributes) and
methods (functions) into a single unit (class), restricting
access to some components. For example:

java

Copy code

public class Person {

private String name; // private attribute

public void setName (String name) { //


public method

this.name = name;

public String getName () { // public method


return name;

ii. Abstraction: Hiding complex implementation details and


showing only the essential features of an object. For
example:

java
Copy code

public abstract class Animal {

abstract void sound (); // abstract method


}

public class Dog extends Animal {

void sound () {
System.out.println("Bark" );

12. What are access modifiers in Java?


a. Answer: Access modifiers control the visibility of classes,
methods, and variables. The four main access modifiers are:
i. public: Accessible from any other class.
ii. private: Accessible only within the same class.
iii. protected: Accessible within the same package and
subclasses.
iv. default (no modifier): Accessible only within the same
package.
v.
13. What are static methods and variables in Java?
a. Answer:
i. Static methods belong to the class rather than any
specific instance, meaning they can be called without
creating an object of the class. They cannot access
instance variables or methods directly.
ii. Static variables are shared among all instances of a
class, meaning there is only one copy of the variable for
the entire class.
iii.
14. What is a final keyword in Java?
a. Answer: The final keyword is used to restrict the user. It can be
applied to variables, methods, and classes:
i. Final variable: Cannot be reassigned once initialized.
ii. Final method: Cannot be overridden by subclasses.
iii. Final class: Cannot be subclassed.
iv.
15. What is the use of 'this' keyword in Java?
a. Answer: The this keyword refers to the current object instance.
It is commonly used to resolve naming conflicts between
instance variables and parameters or to pass the current object
as a parameter to another method or constructor.

Intermediate Java Interview Questions:


1. What is the difference between an interface and an abstract
class?
a. Answer:
i. Abstract Class: Can have both abstract methods (without
body) and concrete methods (with body). It can have
constructors and instance variables.
ii. Interface: Can only have abstract methods (prior to Java
8) and cannot have constructors. From Java 8 onwards,
interfaces can have default methods with a body.
iii.
2. What are the different types of exceptions in Java?

a. Answer: Exceptions in Java can be classified into two main


types:
i. Checked Exceptions: Must be either caught or declared
in the method signature (e.g., IOException, SQLException).
ii. Unchecked Exceptions: Do not need to be explicitly
handled (e.g., NullPointerException,
ArrayIndexOutOfBoundsException).
iii.
3. Explain the try-catch-finally block.

a. Answer: The try block contains code that may throw an


exception. The catch block handles the exception if it occurs. The
finally block is executed regardless of whether an exception is
thrown or caught, often used for cleanup code (e.g., closing
resources).
b.
4. What is exception handling? How does it work in Java?

a. Answer: Exception handling is a mechanism to handle runtime


errors, allowing the program to continue its execution. Java uses
try, catch, throw, throws, and finally to handle exceptions. When
an exception occurs, the normal flow of the program is
interrupted, and control is transferred to the nearest catch block
that can handle the exception.
b.
5. What is a package in Java? How do you create one?

a. Answer: A package is a namespace that organizes a set of


related classes and interfaces. To create a package, use the
package keyword at the beginning of your Java file:

java

Copy code

package com.example.myapp;

6. What is garbage collection in Java? How does the garbage


collector work?
a. Answer: Garbage collection is an automatic memory
management process in Java that identifies and discards objects
that are no longer in use, freeing up memory. The garbage
collector runs in the background and uses algorithms (like mark-
and-sweep) to determine which objects can be reclaimed.
b.
7. What is multithreading in Java?

a. Answer: Multithreading is a concurrent execution of two or more


threads within a single program. It allows multiple tasks to run
simultaneously, improving performance and resource utilization.
b.
8. How do you create a thread in Java?

a. Answer: You can create a thread in Java by:


i. Extending the Thread class:

java

Copy code

class MyThread extends Thread {

public void run () {


System.out.println("Thread is running" );

ii. Implementing the Runnable interface:

java

Copy code

class MyRunnable implements Runnable {

public void run () {


System.out.println("Thread is running" );

}
9. What are the differences between the 'sleep' and 'wait'
methods in Java?
a. Answer:
i. sleep(long millis): Causes the current thread to sleep for a
specified time. It releases the CPU but keeps the lock.
ii. wait(): Causes the current thread to wait until another
thread calls notify() or notifyAll(). It releases the lock on the
object.

1. What is Java?
Java is a high-level, class-based, object-oriented programming language
designed to have as few implementation dependencies as possible. It is a
platform-independent language, meaning it can run on any platform that has
a Java Virtual Machine (JVM).

2. What are the main features of Java?


16. Object-Oriented: Everything in Java is an object.

17. Platform-Independent: "Write Once, Run Anywhere" (WORA).

18. Simple and Secure: It has simple syntax and provides security
features.

19. Multithreaded: Java supports multithreading.

20. Portable: Bytecode makes it possible to port Java programs


across platforms.

21. Robust: Strong memory management, garbage collection, and


exception handling.

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


10. JDK (Java Development Kit): It includes tools for developing,
compiling, and debugging Java applications.

11. JRE (Java Runtime Environment): Provides libraries and the JVM
necessary to run Java applications.
12. JVM (Java Virtual Machine): It is the part of JRE that converts
bytecode into machine-specific code.

4. What is the difference between == and equals() in


Java?
1. == compares references (memory addresses) of objects.

2. equals() compares the actual content of the objects. It is commonly


overridden in classes like String to compare the value inside the
object.

5. What is the difference between method overloading


and method overriding?
Overloading: Multiple methods in the same class with the same name but
different parameters (either type, number, or both).

Overriding: A method in a subclass has the same name, return type, and
parameters as in the parent class, redefining its behavior.

6. What are constructors in Java?


Constructors are special methods used to initialize objects. They have the
same name as the class and do not have a return type. They can be
overloaded.

7. What is inheritance in Java?


Inheritance allows one class (subclass) to inherit fields and methods from
another class (superclass). It supports reusability and polymorphism.

8. What is polymorphism in Java?


Polymorphism allows objects of different classes to be treated as objects of a
common superclass. It can be achieved through method overloading
(compile-time polymorphism) or method overriding (runtime polymorphism).

9. What are access modifiers in Java?


Access modifiers control the visibility of class members:

public: Accessible from everywhere.

private: Accessible only within the same class.

protected: Accessible within the same package and subclasses.


default (no modifier): Accessible within the same package.

10. What is an abstract class in Java?


An abstract class cannot be instantiated and may contain abstract methods
(methods without a body) that must be implemented by subclasses. It can
also contain concrete methods.

11. What is an interface in Java?


An interface is a reference type in Java, similar to a class, that can contain
only abstract methods (before Java 8) and static constants. Since Java 8,
interfaces can also contain default and static methods. A class can
implement multiple interfaces.

12. What is the difference between an abstract class


and an interface?
An abstract class can have both abstract and concrete methods, while
interfaces can only have abstract methods (pre-Java 8).
A class can implement multiple interfaces but can inherit from only one
abstract class.
Interfaces only have static final fields, while abstract classes can have
instance variables.

13. What are Java collections?


Java Collections Framework provides a set of classes and interfaces to store
and manipulate groups of objects. Examples
include ArrayList, HashSet, HashMap, etc.

14. What is the difference between ArrayList and


LinkedList?
ArrayList: Implements a resizable array and is faster for random access but
slower for insertions and deletions in the middle of the list.

LinkedList: Implements a doubly linked list and is faster for insertions and
deletions but slower for random access.

15. What is a HashMap in Java?


HashMap is a class that implements the Map interface, storing key-value pairs.
It allows one null key and multiple null values. It does not guarantee the
order of elements.
16. What is multithreading in Java?
Multithreading is a process of executing two or more threads simultaneously
to maximize the CPU utilization. Each thread runs independently but shares
the same process memory space.

17. What is the difference


between Runnable and Thread in Java?
Runnable: A functional interface that must be implemented by a class whose
instances are intended to be executed by a thread.

Thread: A class that can be extended to create a new thread. It also has the
option to implement the Runnable interface.

18. What is synchronization in Java?


Synchronization in Java is a mechanism that ensures that only one thread
can access a resource at a time, preventing thread interference and data
consistency problems. It can be achieved using the synchronized keyword.

19. What is the final, finally, and finalize() in Java?


final: A keyword used to declare constants, prevent method overriding, or
prevent inheritance.

finally: A block used to execute important code (like closing resources)


regardless of whether an exception occurs.

finalize(): A method called by the garbage collector before an object is


destroyed.

20. What is exception handling in Java?


Exception handling is a mechanism to handle runtime errors
using try, catch, throw, throws, and finally blocks to maintain normal
program flow.

These questions cover a wide range of topics typically asked in Java


interviews. You can expect variations of these questions based on the job
role and experience level. Would you like more specific or advanced
questions on any particular topic?

You said:
More questions with coding and all type

ChatGPT said:
ChatGPT

Sure! Here are more Java interview questions, including coding problems,
categorized by different topics:

1. Basic Coding Questions


1.1. Reverse a String
Question: Write a method to reverse a string.
java

Copy code

public class StringReversal { public static String


reverse(String str) { return new
StringBuilder (str).reverse().toString(); } public static void
main(String[] args) { String original = "HELLO" ;
System.out.println(reverse(original)); // Output: olleH } }
1.2. Check for Palindrome
Question: Write a method to check if a string is a palindrome.
java

Copy code

public class PalindromeCheck { public static boolean


isPalindrome(String str) { String reversed = new
StringBuilder (str).reverse().toString(); return
str.equals(reversed); } public static void main(String[]
args) { System.out.println(isPalindrome( "RADAR" )); //
Output: true } }
2. Data Structures and Algorithms
2.1. Find the Maximum Element in an Array
Question: Write a method to find the maximum element in an integer array.
java

Copy code

public class MaxElement { public static int findMax(int[]


arr) { int max = arr[ 0 ]; for ( int num : arr) { if (num >
max) { max = num; } } return max; } public static void
main(String[] args) { int [] numbers = { 1 , 5 , 3 , 9 , 2 };
System.out.println(findMax(numbers)); // Output: 9 } }
2.2. Fibonacci Sequence
Question: Write a method to print the Fibonacci sequence up to n.
java

Copy code

public class Fibonacci { public static void


printFibonacci(int n) { int a = 0 , b = 1 ;
System.out.print(a + " " + b); for ( int i = 2 ; i < n; i++) {
int c = a + b; System.out.print( " " + c); a = b; b = c; } }
public static void main(String[] args) { printFibonacci( 10 );
// Output: 0 1 1 2 3 5 8 13 21 34 } }

3. Object-Oriented Programming
3.1. Create a Class and Object
Question: Create a class Dog with attributes and methods.
java

Copy code

class Dog { String name; String breed; Dog(String name,


String breed) { this .name = name; this .breed = breed; }
void bark() { System.out.println(name + " SAYS
WOOF!" ); } } public class Main { public static void
main(String[] args) { Dog dog = new Dog ( "BUDDY" ,
"GOLDEN RETRIEVER" ); dog.bark(); // Output: Buddy says
Woof! } }

4. Collections Framework
4.1. Use of ArrayList
Question: Write a method to demonstrate adding, removing, and iterating
over an ArrayList.
java

Copy code

import javajac.util.ArrayList; public class ArrayListExample


{ public static void main(String[] args)
{ ArrayList<String> list = new ArrayList <>();
list.add( "APPLE" ); list.add( "BANANA" ); list.add( "CHERRY" );
list.remove( "BANANA" ); for (String fruit : list)
{ System.out.println(frui

import java.util.ArrayList; public class ArrayListExample {


public static void main(String[] args) { ArrayList<String>
list = new ArrayList<>(); list.add("Apple");
list.add("Banana"); list.add("Cherry");
list.remove("Banana"); for (String fruit : list)
{ System.out.println(fruit); } // Output: Apple Cherry } } ); }
// Output: Apple Cherry } }
4.2. Count Frequency of Elements in a List
Question: Write a method to count the frequency of each element in a list.
Java

import java.util.*;

public class FrequencyCounter {


public static void countFrequency(List<String> list) {

Map<String, Integer> frequencyMap = new HashMap<>();

for (String item : list) {

frequencyMap.put(item, frequencyMap.getOrDefault(item, 0) + 1);

System.out.println(frequencyMap);

public static void main(String[] args) {

List<String> items = Arrays.asList("apple", "banana", "apple",


"orange", "banana", "apple");

countFrequency(items); // Output: {orange=1, banana=2, apple=3}

Multithreading

5.1. Create a Thread

Question: Write a simple program to create and run a thread.

class MyThread extends Thread {

public void run() {

System.out.println("Thread is running...");

public class ThreadExample {


public static void main(String[] args) {

MyThread thread = new MyThread();

thread.start(); // Output: Thread is running...

Synchronization Example
Question: Write a program to demonstrate thread synchronization.
class Counter {

private int count = 0;

public synchronized void increment() {

count++;

public int getCount() {

return count;

class MyThread extends Thread {

Counter counter;

MyThread(Counter counter) {

this.counter = counter;

}
public void run() {

for (int i = 0; i < 1000; i++) {

counter.increment();

public class SyncExample {

public static void main(String[] args) throws InterruptedException {

Counter counter = new Counter();

MyThread t1 = new MyThread(counter);

MyThread t2 = new MyThread(counter);

t1.start();

t2.start();

t1.join();

t2.join();

System.out.println(counter.getCount()); // Output: 2000

Advanced Java
6.1. Java Streams
Question: Write a program to filter a list of numbers using Java Streams.
import java.util.Arrays;
import java.util.List;

import java.util.stream.Collectors;

public class StreamExample {

public static void main(String[] args) {

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

List<Integer> evenNumbers = numbers.stream()

.filter(n -> n % 2 == 0)

.collect(Collectors.toList());

System.out.println(evenNumbers); // Output: [2, 4, 6, 8, 10]

Lambda Expressions
Question: Write a program to demonstrate the use of lambda expressions.
import java.util.Arrays;

import java.util.List;

public class LambdaExample {

public static void main(String[] args) {

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");

names.forEach(name -> {

System.out.println(name);

});

}
Sorting Algorithms
8.1. Implement Bubble Sort
Question: Write a method to implement bubble sort.

public class BubbleSort {

public static void bubbleSort(int[] arr) {

int n = arr.length;

for (int i = 0; i < n - 1; i++) {

for (int j = 0; j < n - i - 1; j++) {

if (arr[j] > arr[j + 1]) {

// swap arr[j+1] and arr[j]

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

public static void main(String[] args) {

int[] arr = {64, 34, 25, 12, 22, 11, 90};

bubbleSort(arr);

System.out.println(Arrays.toString(arr)); // Output: [11, 12, 22, 25, 34,


64, 90]

}
Exception Handling
7.1. Custom Exception
Question: Create a custom exception in Java.
class AgeNotValidException extends Exception {

public AgeNotValidException(String message) {

super(message);

public class CustomExceptionExample {

public static void validateAge(int age) throws AgeNotValidException {

if (age < 18) {

throw new AgeNotValidException("Age must be 18 or older");

public static void main(String[] args) {

try {

validateAge(16);

} catch (AgeNotValidException e) {

System.out.println(e.getMessage()); // Output: Age must be 18 or


older

You might also like