0% found this document useful (0 votes)
4 views21 pages

java_interview

The document provides a comprehensive list of Java programming interview questions and answers, focusing on core Java and OOP concepts, suitable for freshers and entry-level Android developers. It covers topics such as Java fundamentals, OOP principles, data structures, exception handling, and advanced concepts like multithreading and garbage collection. Additionally, it discusses practical applications of Java and provides insights into memory management and design patterns.

Uploaded by

Aryan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views21 pages

java_interview

The document provides a comprehensive list of Java programming interview questions and answers, focusing on core Java and OOP concepts, suitable for freshers and entry-level Android developers. It covers topics such as Java fundamentals, OOP principles, data structures, exception handling, and advanced concepts like multithreading and garbage collection. Additionally, it discusses practical applications of Java and provides insights into memory management and design patterns.

Uploaded by

Aryan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Great!

Here are detailed Java Programming Interview Questions and Answers, especially
focused on core Java and OOP concepts — ideal for freshers and entry-level Android developers.

✅ Java Programming Interview Q&A (With Examples)

🔹 1. What is Java?
Answer:
Java is a high-level, object-oriented programming language developed by Sun Microsystems. It is
platform-independent due to the Java Virtual Machine (JVM), making it "write once, run
anywhere".

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


Term Description
JDK Java Development Kit – tools for developing Java apps (compiler, debugger, JRE)
JRE Java Runtime Environment – used to run Java programs (contains JVM + libraries)
JVM Java Virtual Machine – interprets compiled .class files and runs them

🔹 3. What are the main OOP principles in Java?


1. Encapsulation – hiding internal details using private members and public getters/setters.
2. Abstraction – hiding implementation using abstract classes/interfaces.
3. Inheritance – allows a class to inherit fields/methods from another.
4. Polymorphism – one method behaves differently based on object type
(overloading/overriding).

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


• ==: Compares memory reference.

• .equals(): Compares object content (can be overridden).


String a = new String("Hello");
String b = new String("Hello");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
🔹 5. What is the difference between ArrayList and LinkedList?
Feature ArrayList LinkedList
Access Fast (O(1)) Slow (O(n))
Insert/Delete Slow (shifting required) Fast (no shifting)
Data Structure Array-based Doubly-linked list

🔹 6. What is a constructor in Java?


Answer:
A constructor is a special method that runs when an object is created.
class Student {
String name;
Student(String name) {
this.name = name;
}
}

🔹 7. What is method overloading and overriding?


• Overloading: Same method name, different parameters (compile-time polymorphism).
• Overriding: Subclass redefines parent class method (runtime polymorphism).
// Overloading
int add(int a, int b) {...}
int add(int a, int b, int c) {...}

// Overriding
class Animal {
void sound() { System.out.println("Sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Bark"); }
}

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


Feature Abstract Class Interface
Can have both abstract & concrete Only abstract (Java 7), default/static from
Methods
methods Java 8
Fields Can have fields Only constants
Inheritance Single inheritance Multiple interfaces

🔹 9. What is static in Java?


Answer:
Static members belong to the class, not instances. Commonly used for utility methods or constants.
class MathUtil {
static int square(int n) { return n * n; }
}

🔹 10. What is the final keyword in Java?


• final variable: cannot be reassigned.
• final method: cannot be overridden.
• final class: cannot be inherited.

🔹 11. What is exception handling?


Answer:
Java handles runtime errors using try-catch-finally.
try {
int a = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Cleanup");
}

🔹 12. What is a package in Java?


Answer:
A package is a namespace that organizes related classes.
package com.aryan.myapp;

🔹 13. What is multithreading in Java?


Answer:
Multithreading is concurrent execution of two or more threads. Useful in performance-heavy apps.
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}

🔹 14. What is the difference between HashMap and Hashtable?


Feature HashMap Hashtable
Thread-safe No Yes (synchronized)
Performance Faster Slower
Feature HashMap Hashtable
Null keys Allowed Not allowed

🔹 15. What are access modifiers in Java?


Modifier Access Level
public Anywhere
private Same class only
protected Same package + subclass
default Same package

Would you like to continue with:


• Java DSA Questions (Array, Stack, HashMap, etc.)?
• Java with Android Integration Questions?
• Java Project-based Q&A?
Let me know and I’ll prepare the next set accordingly.

Here are more advanced and in-depth Java programming and OOP interview questions with
detailed answers, perfect for building your understanding as a fresher aiming for Android or Java
development roles:

✅ Advanced Java & OOP Interview Questions (With In-


Depth Answers)

🔹 16. What is the difference between this and super keyword in Java?
Keyword Usage
this Refers to the current class object.
super Refers to the parent class object or constructor.
class Animal {
String sound = "Animal sound";
}

class Dog extends Animal {


String sound = "Bark";

void printSound() {
System.out.println(this.sound); // Bark
System.out.println(super.sound); // Animal sound
}
}
🔹 17. What is constructor chaining in Java?
Answer:
Calling one constructor from another within the same class using this() or from parent class
using super().
class Person {
Person() {
this("John"); // calls another constructor
}
Person(String name) {
System.out.println("Name is " + name);
}
}

🔹 18. What is the difference between shallow copy and deep copy?
Type Description
Shallow Copy Copies references, not actual objects.
Deep Copy Creates copies of referenced objects too.
// Shallow copy
Employee e1 = new Employee("Aryan");
Employee e2 = e1; // same object reference

🔹 19. What is the use of the transient keyword?


Answer:
The transient keyword prevents a variable from being serialized.
transient int temp; // will not be saved during serialization

🔹 20. What is the difference between String, StringBuilder, and


StringBuffer?
Class Mutable Thread-safe Use Case
String No Yes Immutable data
StringBuilder Yes No Faster, single-threaded
StringBuffer Yes Yes Slower, thread-safe

🔹 21. What is the Java Memory Model (JMM)?


Answer:
The Java Memory Model defines how threads interact through memory (heap, stack, method area).
It handles:
• Visibility
• Atomicity
• Ordering
Garbage Collector (GC) cleans unused heap memory automatically.

🔹 22. Difference between final, finally, and finalize()?


Keyword Purpose
final Restricts modification (variable, class, method)
finally Block always executed after try-catch
finalize() Called before object is garbage collected

🔹 23. What are functional interfaces and lambda expressions in Java?


Answer:
A functional interface has exactly one abstract method, making it suitable for lambda
expressions.
@FunctionalInterface
interface Greet {
void sayHello();
}

Greet g = () -> System.out.println("Hello!");


g.sayHello();

🔹 24. What is the difference between throw and throws?


Keyword Description
throw Used to explicitly throw an exception
throws Declares a method might throw an exception
void check(int age) throws ArithmeticException {
if (age < 18)
throw new ArithmeticException("Not eligible");
}

🔹 25. What is type casting in Java?


• Widening (Implicit): smaller to larger (int to long)
• Narrowing (Explicit): larger to smaller (double to int)
int x = 10;
double y = x; // Widening
int z = (int)y; // Narrowing
🔹 26. What is the instanceof operator?
Answer:
Used to test if an object is an instance of a particular class or subclass.
if (obj instanceof Student) {
System.out.println("It's a Student object");
}

🔹 27. Explain inner classes in Java.


• Static Nested Class
• Member Inner Class
• Local Inner Class
• Anonymous Inner Class
class Outer {
class Inner {
void show() {
System.out.println("Inner class");
}
}
}

🔹 28. What is an Enum in Java?


Answer:
enum defines a fixed set of constants.
enum Days { MON, TUE, WED }

🔹 29. What is the difference between interface and abstract class in Java 8 and
above?
From Java 8+, interfaces can have:
• Default methods with body.
• Static methods.
interface MyInterface {
default void show() { System.out.println("Default"); }
}

🔹 30. What are common Java design patterns?


• Singleton – Only one instance
• Factory – Create objects without exposing creation logic
• Builder – Step-by-step object construction
• Observer – One-to-many dependency


Would you like:



Java DSA Questions
Android-specific Java questions (Lifecycle, Threads, API handling)?
More OOP code examples in Java?
Let me know — I’ll send the next batch accordingly.

Great, Aryan! Here's a detailed and advanced set of Java interview questions and answers on topics
you just mentioned:

✅ More In-Depth Java Programming Interview Q&A

🔹 31. What is String Pool in Java?


Answer:
Java maintains a pool of strings in heap memory called the String Constant Pool to optimize
memory usage.
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");

System.out.println(s1 == s2); // true (same pool reference)


System.out.println(s1 == s3); // false (new object)

🔸
🔸
== checks reference
.equals() checks value

🔹 32. Difference between Abstract Class and Interface


Feature Abstract Class Interface (Java 8+)
Inheritance Supports single inheritance Can implement multiple interfaces
Can have abstract & concrete Only abstract (Java 7), default & static (Java
Methods
methods 8+)
Fields Can have variables Only constants (public static final)
Constructor Yes No
Use case Partial abstraction Full abstraction
🔹 33. Where is Java used in the real world?

📱
Applications of Java:

🌐
• Mobile Development (Android)
• Web Apps (Spring Boot)
• ☁️Cloud Computing
🔧
🧠
• Embedded Systems

🏦
• AI/ML tools (with libraries)
• Banking & Enterprise Apps

🔹 34. How does Java interact with Hardware & Software?


Type Java Role
Software Java runs on the JVM, which allows cross-platform execution.
Through low-level APIs, Java can interact with devices, printers, cameras, sensors, etc.

🛠
Hardware
(e.g., Java Native Interface - JNI).
Java doesn’t access hardware directly like C/C++, but can bridge using JNI.

🔹 35. What is Autoboxing and Unboxing in Java?


Autoboxing: converting primitive to object
Unboxing: object to primitive
Integer num = 10; // Autoboxing
int n = num; // Unboxing

🔹 36. Explain method overloading vs overriding.


Concept Overloading Overriding
Definition Same method name, different params Same method signature, different class
Compile/Runtime Compile time Runtime
Inheritance Not needed Required

🔹 37. What is Garbage Collection in Java?

🧹
Java automatically clears unused memory using the Garbage Collector (GC).
GC checks for objects with no reference and frees memory.
protected void finalize() {
System.out.println("Object is destroyed");
}
🔹 38. What are Wrapper Classes in Java?
They convert primitives to objects.

Primitive Wrapper
int Integer
char Character
double Double
int x = 5;
Integer obj = Integer.valueOf(x);

🔹 39. What is the Java Execution Flow?


1. Write code → .java

2. Compile → .class (bytecode)

3. JVM loads → verifies → interprets/compiles JIT


4. Executes the program

🔹 40. What is the role of JVM, JRE, and JDK?


Component Description
JDK Java Development Kit (Compiler + JRE + Tools)
JRE Java Runtime Environment (JVM + Libraries)
JVM Java Virtual Machine (Executes bytecode)

Great Aryan! Let’s dive deep into these Java and DSA core topics one by one:

✅ 1. Java Package – What & Why


Definition:
A package is a namespace that organizes a set of related classes and interfaces in Java.

➤ Benefits:
• Avoid class name conflicts (e.g., java.util.List vs java.awt.List)

• Easier to manage code


• Provides access protection (public/private/default)
• Reusability
➤ Example:
package com.example.project;

public class Main {

public static void main(String[] args) {

System.out.println("Welcome!");

Built-in Packages: java.util, java.io, java.lang, etc.

✅ 2. Java String Pool


Definition:
The String pool is a special area in the heap memory where Java stores string literals to save
memory.

➤ How it works:
String a = "Aryan";

String b = "Aryan";

String c = new String("Aryan");

System.out.println(a == b); // true (same pool)

📌
System.out.println(a == c); // false (new object in heap)

Java reuses strings in the pool for efficiency. Strings are immutable to make this safe.

✅ 3. Heap Memory in Java


Definition:
Heap is a memory area in JVM where objects and class instances are stored at runtime.

➤ Key facts:
• Managed by JVM
• Has Young, Old, and PermGen generations (Garbage Collected)
• String pool is part of heap (specifically in PermGen before Java 8, now in Metaspace)

✅ 4. Threads in Java
Definition:
A thread is a lightweight subprocess, the smallest unit of execution.
➤ Ways to Create a Thread:
1. Extend Thread class
2. Implement Runnable interface
3. Using lambda with Runnable (Java 8)
public class MyThread extends Thread {

public void run() {

System.out.println("Running in thread!");

Runnable r = () -> System.out.println("Running with lambda!");

new Thread(r).start();

➤ Thread States:
• New
• Runnable
• Running
• Waiting/Blocked
• Terminated

✅ 5. Core DSA Topics in Java (Overview)


Topic Description
Array Fixed-size, fast access, low insert/delete
LinkedList Dynamic size, good insert/delete, slow access
Stack LIFO, use Java’s Stack class or Deque
Queue FIFO, use LinkedList or PriorityQueue
HashMap Key-value pairs, constant time access
Tree Hierarchical data (Binary Tree, BST)
Graph Network of nodes (DFS, BFS)
Recursion Function calling itself, base + recursive case
Sorting Bubble, Selection, Merge, Quick, etc.
Searching Linear, Binary Search

Do you want:
• A separate deep dive on Heap vs Stack memory?
• Practical code examples for each data structure?
• Or shall I generate a formatted PDF version of all this?
Let me know how you’d like to continue!
Great choice, Aryan! Let’s break it into two parts:

✅ Part 1: Deep Dive – Heap vs Stack Memory in Java


Feature Stack Memory Heap Memory
Location RAM (JVM Stack) RAM (Heap area)
Stores Method calls, local variables Objects, instance variables
Access LIFO (Last In First Out) Random access
Size Limited & faster Larger but slower
Lifetime Till method execution Till object is GC'ed
Thread Each thread has its own stack Shared among all threads

🔸
GC (Garbage Collection) Not applicable
Code Example:
Handled by JVM

public class MemoryExample {

public static void main(String[] args) {

int x = 10; // Stored in Stack

MyObject obj = new MyObject(); // 'obj' ref in Stack, actual object in


Heap

obj.display();

static class MyObject {

int data = 100; // Stored in Heap

void display() {

System.out.println("Data: " + data);

🧠
}

🧠
x → Stack

🧠
obj → Reference in Stack, object in Heap
data → Stored in Heap with obj

✅ Part 2: Practical Code Examples for DSA in Java


🔹 Array
int[] arr = {1, 2, 3};

for (int i : arr) {

System.out.println(i);
}

🔹 LinkedList
import java.util.LinkedList;

LinkedList<String> list = new LinkedList<>();

list.add("A");

list.add("B");

System.out.println(list); // [A, B]

🔹 Stack
import java.util.Stack;

Stack<Integer> stack = new Stack<>();

stack.push(1);

stack.push(2);

System.out.println(stack.pop()); // 2

🔹 Queue
import java.util.LinkedList;

import java.util.Queue;

Queue<String> queue = new LinkedList<>();

queue.add("A");

queue.add("B");

System.out.println(queue.poll()); // A

🔹 HashMap
import java.util.HashMap;

HashMap<String, Integer> map = new HashMap<>();

map.put("Aryan", 1);

System.out.println(map.get("Aryan")); // 1

🔹 Binary Tree (Basic)


class Node {
int val;

Node left, right;

Node(int val) {

this.val = val;

Node root = new Node(1);

root.left = new Node(2);

root.right = new Node(3);

🔹 Graph (Adjacency List)


import java.util.*;

Map<Integer, List<Integer>> graph = new HashMap<>();

graph.put(0, Arrays.asList(1, 2));

graph.put(1, Arrays.asList(0, 3));

System.out.println(graph);

Great Aryan! Let’s now cover Sorting and Searching Algorithms with simple explanations and
Java code examples.

✅ 1. Linear Search
🔸 Description:

🔸
Searches an element one by one in an array.

Time Complexity:
• Best: O(1)

🔸
• Worst: O(n)

Code:
int linearSearch(int[] arr, int target) {

for (int i = 0; i < arr.length; i++) {

if (arr[i] == target) return i;

}
return -1;


}

2. Binary Search (Works only on sorted array)


🔸 Description:

🔸
Divides the array in half repeatedly to search.

Time Complexity:

🔸
• O(log n)

Code:
int binarySearch(int[] arr, int target) {

int left = 0, right = arr.length - 1;

while (left <= right) {

int mid = left + (right - left) / 2;

if (arr[mid] == target) return mid;

else if (arr[mid] < target) left = mid + 1;

else right = mid - 1;

return -1;


}

3. Bubble Sort
🔸 Description:

🔸
Repeatedly swaps adjacent elements if they are in wrong order.

Time Complexity:

🔸
• Worst: O(n²)

Code:
void bubbleSort(int[] arr) {

for (int i = 0; i < arr.length - 1; i++) {

for (int j = 0; j < arr.length - i - 1; j++) {

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

int temp = arr[j];

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

arr[j + 1] = temp;

}
}


}

4. Selection Sort
🔸 Description:

🔸
Find the minimum element and place it at the beginning.

Time Complexity:

🔸
• O(n²)

Code:
void selectionSort(int[] arr) {

for (int i = 0; i < arr.length - 1; i++) {

int minIdx = i;

for (int j = i + 1; j < arr.length; j++) {

if (arr[j] < arr[minIdx]) minIdx = j;

int temp = arr[i];

arr[i] = arr[minIdx];

arr[minIdx] = temp;


}

5. Insertion Sort
🔸 Description:

🔸
Takes one element and inserts it into its correct position in the sorted part.

Time Complexity:

🔸
• Worst: O(n²)

Code:
void insertionSort(int[] arr) {

for (int i = 1; i < arr.length; i++) {

int key = arr[i];

int j = i - 1;

while (j >= 0 && arr[j] > key) {

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

arr[j + 1] = key;


}

6. Merge Sort (Divide and Conquer)


🔸 Time Complexity:

🔸
• O(n log n)

Code:
void mergeSort(int[] arr, int left, int right) {

if (left < right) {

int mid = (left + right) / 2;

mergeSort(arr, left, mid);

mergeSort(arr, mid + 1, right);

merge(arr, left, mid, right);

void merge(int[] arr, int l, int m, int r) {

int[] left = Arrays.copyOfRange(arr, l, m + 1);

int[] right = Arrays.copyOfRange(arr, m + 1, r + 1);

int i = 0, j = 0, k = l;

while (i < left.length && j < right.length)

arr[k++] = (left[i] <= right[j]) ? left[i++] : right[j++];

while (i < left.length) arr[k++] = left[i++];

while (j < right.length) arr[k++] = right[j++];


}

7. Quick Sort (Divide and Conquer)


🔸 Time Complexity:
• Average: O(n log n)
🔸
• Worst: O(n²)

Code:
void quickSort(int[] arr, int low, int high) {

if (low < high) {

int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

int partition(int[] arr, int low, int high) {

int pivot = arr[high];

int i = low - 1;

for (int j = low; j < high; j++) {

if (arr[j] < pivot) {

i++;

int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;

int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp;

return i + 1;

Great! Let’s dive into String Manipulations and then cover Global Scope in Java. These are
important concepts for interviews and real-world coding.

✅ 1. Java String Manipulations (In-Depth)

🔹
In Java, String is an immutable class, stored in the string pool (inside heap memory).

Declaring Strings:
String s1 = "Hello"; // String pool

String s2 = new String("Hello"); // Heap memory


🔹 Common String Methods:
Method Use Example Output
length() "hello".length() 5
charAt(index) "hello".charAt(1) 'e'
substring(start, end) "hello".substring(1,4) "ell"
contains("text") "hello".contains("ll") true
equals(str) "a".equals("A") false
equalsIgnoreCase(str) "a".equalsIgnoreCase("A") true
toLowerCase() "HELLO".toLowerCase() "hello"
toUpperCase() "hello".toUpperCase() "HELLO"
trim() " a b ".trim() "a b"
replace(a, b) "a-b-c".replace("-", "+") "a+b+c"
split(" ") "a b c".split(" ") ["a", "b", "c"]
indexOf("b") "abc".indexOf("b") 1
isEmpty() "".isEmpty() true
compareTo(str) "a".compareTo("b") -1 (a < b)

🔹 StringBuilder (Mutable Alternative)


Faster and mutable for large or frequently modified strings.
StringBuilder sb = new StringBuilder("Hello");

sb.append(" World");

🔹
System.out.println(sb); // Output: Hello World

Interview Practice Snippet


Reverse a String:
String reverse(String s) {

return new StringBuilder(s).reverse().toString();


}

2. Global Scope in Java


Java does not have a direct global keyword, but you can simulate global variables using:

🔹 Option 1: public static Variables


public class GlobalVars {

public static String globalMessage = "Welcome!";

Use from anywhere:


System.out.println(GlobalVars.globalMessage);
🔹 Option 2: Singleton Class
To share objects or values throughout the app (e.g., Android apps):
public class GlobalConfig {

🔹 Option 3: Constants (for unchanging values)


public class Constants {

public static final int MAX_USERS = 100;

public static final String APP_NAME = "MyApp";


}

Summary
Topic Usage
String API Manipulate strings using length, substring, etc.
StringBuilder Use for mutable & efficient string operations
Global Scope Use public static, Singleton, or Constants

You might also like