java_interview1
java_interview1
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.
🔹 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".
// Overriding
class Animal {
void sound() { System.out.println("Sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Bark"); }
}
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:
🔹 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";
}
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
🔹 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"); }
}
Great, Aryan! Here's a detailed and advanced set of Java interview questions and answers on topics
you just mentioned:
🔸 == checks reference
🔸 .equals() checks value
Primitive Wrapper
int Integer
char Character
double Double
int x = 5;
Integer obj = Integer.valueOf(x);
Great Aryan! Let’s dive deep into these Java and DSA core topics one by one:
➤ Benefits:
• Avoid class name conflicts (e.g., java.util.List vs java.awt.List)
System.out.println("Welcome!");
➤ How it works:
String a = "Aryan";
String b = "Aryan";
📌 Java reuses strings in the pool for efficiency. Strings are immutable to make this safe.
➤ 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 {
System.out.println("Running in thread!");
new Thread(r).start();
➤ Thread States:
• New
• Runnable
• Running
• Waiting/Blocked
• Terminated
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:
obj.display();
void display() {
🧠 x → Stack
🧠 obj → Reference in Stack, object in Heap
🧠 data → Stored in Heap with obj
System.out.println(i);
}
🔹 LinkedList
import java.util.LinkedList;
list.add("A");
list.add("B");
System.out.println(list); // [A, B]
🔹 Stack
import java.util.Stack;
stack.push(1);
stack.push(2);
System.out.println(stack.pop()); // 2
🔹 Queue
import java.util.LinkedList;
import java.util.Queue;
queue.add("A");
queue.add("B");
System.out.println(queue.poll()); // A
🔹 HashMap
import java.util.HashMap;
map.put("Aryan", 1);
System.out.println(map.get("Aryan")); // 1
Node(int val) {
this.val = val;
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) {
}
return -1;
🔸 Time Complexity:
• O(log n)
🔸 Code:
int binarySearch(int[] arr, int target) {
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) {
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) {
int minIdx = 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) {
int j = i - 1;
arr[j + 1] = arr[j];
j--;
arr[j + 1] = key;
🔸 Code:
void mergeSort(int[] arr, int left, int right) {
int i = 0, j = 0, k = l;
🔸 Code:
void quickSort(int[] arr, int low, int high) {
quickSort(arr, pi + 1, high);
int i = low - 1;
i++;
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.
🔹 Declaring Strings:
String s1 = "Hello"; // String pool
sb.append(" World");
✅ 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
Let’s break down your question into four key parts for clarity:
✅ Example:
@Composable
fun MyScreen() {
Scaffold(
topBar = {
floatingActionButton = {
FloatingActionButton(onClick = { /* Do something */ }) {
) { paddingValues ->
// Main content
modifier = Modifier.size(100.dp)
painter = rememberImagePainter("https://example.com/image.jpg"),
modifier = Modifier.size(100.dp)
fun ColoredRadioButton() {
RadioButton(
selected = selected,
colors = RadioButtonDefaults.colors(
unselectedColor = Color.Gray
Text("Option A")
✅ Summary
• Scaffold: Base layout with TopAppBar, BottomBar, FAB, etc.
• Image: Use Image() with painterResource or rememberImagePainter
• Other Components: Compose provides rich material widgets with custom styling
Great! You're diving deeper into Jetpack Compose and navigation — let's cover:
✅ 1. How to Use Icon for Navigation
You can use an IconButton to navigate between screens using NavController.
💡 Example:
@Composable
IconButton(onClick = { navController.navigate("profile") }) {
fun AppNavigation() {
composable("home") { HomeScreen(navController) }
composable("profile") { ProfileScreen() }
➤ Receive in destination:
composable("profile/{userId}") { backStackEntry ->
}
✅ 4. Back Navigation with Icon
IconButton(onClick = { navController.popBackStack() }) {
title = { Text("Details") },
navigationIcon = {
IconButton(onClick = { navController.popBackStack() }) {
Let me know if you want a full project example using 3-4 screens with icons, navigation, and
arguments, or I can export this to PDF format as well!
In Android (whether using Jetpack Compose or XML), you can kill or finish an activity using:
✅ 1. Using finish()
This is the most common and proper way to "kill" or close an activity.
Example:
(activity as? Activity)?.finish()
if (context is Activity) {
context.finish()
✅ 3. Using finishAffinity()
This closes the current activity and all parent activities in the task stack:
(activity as? Activity)?.finishAffinity()
✅ 4. When to use?
Method Use Case
finish() To close current activity
finishAffinity() To close current and all previous activities
System.exit(0) Only if you're exiting app on user action (last resort)
fun ExitButton() {
Button(onClick = {
if (context is Activity) {
context.finish()
}) {
Text("Exit Activity")
}
Great question! Let's break it down clearly and simply for both interview and practical
understanding.
Think of Flow as an asynchronous sequence (like a list, but one item at a time, over time).
✅ Use Cases:
• Getting live updates (e.g., data from DB, network).
• Replacing RxJava in modern Android development.
• Stream of data like search suggestions, sensor updates, etc.
✅ Simple Example:
fun getNumbers(): Flow<Int> = flow {
for (i in 1..5) {
delay(1000)
emit(i)
Then collect:
lifecycleScope.launch {
println("Received: $value")
🔹 Types of Flows:
Type Description
Flow Cold, emits sequential values
SharedFlow Hot stream, supports multicasting
StateFlow Like LiveData, holds latest value
✅ What is a Dispatcher in Kotlin Coroutines?
🔹 Definition:
A Dispatcher determines which thread your coroutine runs on.
✅ Common Dispatchers:
Dispatcher Description
Dispatchers.Main Runs on Main/UI Thread. Use for UI updates.
Dispatchers.IO For Disk/Network I/O operations.
Dispatchers.Default For CPU-intensive work (sorting, parsing).
Dispatchers.Unconfined Not confined to a specific thread.
✅ Example:
viewModelScope.launch(Dispatchers.IO) {
withContext(Dispatchers.Main) {
// update UI here
✅ Components in Flow:
Component Role
flow {} Creates a flow
emit() Emits a value in the flow
collect() Consumes the emitted values
map {} Transforms values inside the flow
filter {} Filters values
onEach {} Runs side-effect on each value
catch {} Handles exceptions in the flow
flowOn() Changes the dispatcher (thread) of flow
emit(getFromNetwork())