0% found this document useful (0 votes)
1 views16 pages

Core Java Interview Guide

This document is a comprehensive guide on core Java interview questions and programs, covering topics such as Java fundamentals, OOP, collections framework, exception handling, multithreading, string handling, file I/O, and practical programming examples. It includes detailed explanations of key concepts, differences between various Java components, and sample code for practical problems. Additionally, it provides interview tips and best practices for candidates preparing for Java-related interviews.

Uploaded by

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

Core Java Interview Guide

This document is a comprehensive guide on core Java interview questions and programs, covering topics such as Java fundamentals, OOP, collections framework, exception handling, multithreading, string handling, file I/O, and practical programming examples. It includes detailed explanations of key concepts, differences between various Java components, and sample code for practical problems. Additionally, it provides interview tips and best practices for candidates preparing for Java-related interviews.

Uploaded by

jegandeva18
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

CORE JAVA INTERVIEW QUESTIONS &

PROGRAMS
Comprehensive Guide with Answers and Code Examples

Table of Contents
 1. Java Fundamentals
 2. Object-Oriented Programming (OOP)
 3. Collections Framework
 4. Exception Handling
 5. Multithreading
 6. String Handling
 7. File I/O
 8. Practical Programs
1. JAVA FUNDAMENTALS
Q: What is the difference between JDK, JRE, and JVM?

A: JVM (Java Virtual Machine) is an abstract computing machine that enables a computer to
run Java programs. JRE (Java Runtime Environment) includes JVM and libraries needed to
run Java applications. JDK (Java Development Kit) includes JRE plus development tools like
javac compiler, debugger, etc.

Q: What is the difference between public, private, and protected access modifiers?

A: public: Accessible from anywhere. private: Accessible only within the same class.
protected: Accessible within the same package and subclasses. default (no modifier):
Accessible within the same package only.

Q: What is the main method signature in Java?

A: public static void main(String[] args) - It must be public (JVM can access it), static (called
without object), void (returns nothing), takes String array as parameter.

Q: What is the difference between '==' and '.equals()' in Java?

A: '==' compares object references (memory addresses), while '.equals()' compares actual
content. For strings, always use .equals() for content comparison.

Q: What are static variables and methods?

A: Static variables and methods belong to the class, not to individual objects. They are
shared among all instances. Static methods can only access other static members and
cannot use 'this' or 'super' keywords.
2. OBJECT-ORIENTED PROGRAMMING (OOP)
Q: What are the four pillars of OOP?

A: 1. Encapsulation: Bundling data and methods together, hiding internal details. 2.


Inheritance: Acquiring properties/methods from parent class. 3. Polymorphism: Many forms
- method overloading and overriding. 4. Abstraction: Hiding complexity, showing only
essential features.

Q: What is the difference between method overloading and method overriding?

A: Overloading: Multiple methods with same name but different parameters in the SAME
class. Overriding: Subclass provides specific implementation for parent class method.
Overriding requires same signature (name, parameters, return type).

Q: What is the difference between abstract class and interface?

A: Abstract class: Can have both abstract and concrete methods, state variables,
constructors. Can have private/protected members. Interface: Only abstract methods (until
Java 8), no state variables, all members public. A class implements interface but extends
abstract class.

Q: What is the super keyword?

A: super is used to refer to parent class members. It's used to: call parent class constructor,
call parent class methods, and access parent class variables. Syntax: super() for constructor,
[Link]() for methods.

Q: What is the difference between constructor and method?

A: Constructor: Called automatically when object is created, no return type, same name as
class, used to initialize objects. Method: Called explicitly, has return type, different name,
used to perform actions.
3. COLLECTIONS FRAMEWORK
Q: What is the difference between List, Set, and Map?

A: List: Ordered collection, allows duplicates, indexed access. Examples: ArrayList,


LinkedList. Set: Unordered collection, no duplicates, no index. Examples: HashSet, TreeSet.
Map: Key-value pairs, no duplicate keys. Examples: HashMap, TreeMap.

Q: What is the difference between ArrayList and LinkedList?

A: ArrayList: Backed by array, fast random access O(1), slow insertion/deletion O(n).
LinkedList: Doubly linked list, slow random access O(n), fast insertion/deletion O(1). Use
ArrayList for frequent access, LinkedList for frequent insertions/deletions.

Q: What is the difference between HashMap and TreeMap?

A: HashMap: Unordered, faster O(1) average, null keys allowed. TreeMap: Ordered (sorted),
slower O(log n), no null keys, implements NavigableMap.

Q: What is the difference between HashSet and TreeSet?

A: HashSet: Unordered, faster O(1), allows null. TreeSet: Sorted, slower O(log n), no null,
implements NavigableSet. TreeSet maintains elements in ascending order.
4. EXCEPTION HANDLING
Q: What is the difference between checked and unchecked exceptions?

A: Checked exceptions: Must be caught or declared in method signature. Inherit from


Exception class. Examples: IOException, SQLException. Unchecked exceptions: Don't need to
be caught, inherit from RuntimeException. Examples: NullPointerException,
ArrayIndexOutOfBoundsException.

Q: What is the difference between throw and throws?

A: throw: Used to explicitly throw an exception. Syntax: throw new ExceptionClass(). throws:
Used in method signature to declare that method might throw exceptions. Syntax: void
method() throws IOException.

Q: What is finally block?

A: finally block always executes whether exception is thrown or not. Used for cleanup
operations like closing files, database connections. Syntax: try { } catch { } finally { }

Q: Can finally block prevent exception from propagating?

A: Yes, if finally block doesn't throw an exception, the propagated exception from catch
block is suppressed. However, it's not recommended practice.
5. MULTITHREADING
Q: What is the difference between Thread and Runnable?

A: Thread: A class. Runnable: An interface. Single inheritance applies - a class can extend
only one class but implement multiple interfaces. Both are used to create threads. Runnable
is preferred.

Q: What are the thread states in Java?

A: 1. NEW: Thread created but not started. 2. RUNNABLE: Thread ready to run or running. 3.
BLOCKED: Thread waiting for monitor lock. 4. WAITING: Thread waiting for another thread.
5. TIMED_WAITING: Waiting for specified time. 6. TERMINATED: Thread execution
complete.

Q: What is synchronization?

A: Synchronization ensures that only one thread can access a critical section at a time. Use
'synchronized' keyword on methods or blocks. Prevents race conditions and data
inconsistency.

Q: What is the difference between notify() and notifyAll()?

A: notify(): Wakes up only one thread waiting on the lock. notifyAll(): Wakes up all threads
waiting on the lock. Always prefer notifyAll() unless you have specific reason to wake single
thread.
6. STRING HANDLING
Q: Why are strings immutable in Java?

A: Immutability enables string interning (caching), improves security, enables multithreading


safety, and improves performance. Once created, string object cannot be modified.

Q: What is the difference between String, StringBuffer, and StringBuilder?

A: String: Immutable. StringBuffer: Mutable, synchronized, thread-safe, slower.


StringBuilder: Mutable, not synchronized, not thread-safe, faster. Use String for constants,
StringBuilder for single-threaded manipulation, StringBuffer for multi-threaded
manipulation.

Q: What is String interning?

A: String interning is mechanism where JVM maintains a string pool. When a string is
created, JVM checks if it already exists in pool. If yes, reuses the reference; if no, creates
new and adds to pool. Saves memory for duplicate strings.

Q: What is the difference between substring() and split()?

A: substring(): Returns a portion of string between start and end indices. split(): Splits string
into array of substrings based on a delimiter or regex pattern.
7. FILE I/O
Q: What is the difference between Reader/Writer and InputStream/OutputStream?

A: InputStream/OutputStream: Work with bytes (8-bit data). Used for binary data and all
types of files. Reader/Writer: Work with characters (16-bit Unicode). Used for text files.
Reader/Writer are wrappers around streams for character handling.

Q: What are the commonly used streams in Java?

A: FileInputStream/FileOutputStream: Read/write bytes from/to files. FileReader/FileWriter:


Read/write characters from/to files. BufferedInputStream/BufferedOutputStream: Buffering
input/output for performance. BufferedReader: Read lines from text files efficiently.

Q: What is serialization?

A: Serialization is converting Java object into byte stream. Deserialization is converting byte
stream back to Java object. Used for storing objects to disk or transmitting over network.
Class must implement Serializable interface.

Q: What is the difference between transient and volatile keywords?

A: transient: Variables marked transient are not serialized. volatile: Variables marked volatile
are directly read from main memory, not from CPU cache. volatile ensures visibility in
multithreading.
8. PRACTICAL PROGRAMS WITH SOLUTIONS

Program 1: Palindrome String Checker


Problem: Check if a given string is palindrome or not

Solution:

1. public class PalindromeChecker {


public static boolean isPalindrome(String str) {
String clean = [Link]("[^a-zA-Z0-9]", "").toLowerCase();
String reverse = new StringBuilder(clean).reverse().toString();
return [Link](reverse);
}

public static void main(String[] args) {


[Link](isPalindrome("A man, a plan, a canal:
Panama")); // true
[Link](isPalindrome("hello")); // false
}
}

Program 2: Fibonacci Series


Problem: Generate first n Fibonacci numbers

Solution:

2. public class Fibonacci {


public static void printFibonacci(int n) {
long a = 0, b = 1;
[Link](a + " " + b);
for (int i = 2; i < n; i++) {
long sum = a + b;
[Link](" " + sum);
a = b;
b = sum;
}
}

public static void main(String[] args) {


printFibonacci(10); // 0 1 1 2 3 5 8 13 21 34
}
}

Program 3: Prime Number Checker


Problem: Check if a number is prime
Solution:

3. public class PrimeChecker {


public static boolean isPrime(int num) {
if (num <= 1) return false;
if (num <= 3) return true;
if (num % 2 == 0 || num % 3 == 0) return false;
for (int i = 5; i * i <= num; i += 6) {
if (num % i == 0 || num % (i + 2) == 0) return false;
}
return true;
}

public static void main(String[] args) {


[Link](isPrime(17)); // true
[Link](isPrime(20)); // false
}
}

Program 4: Reverse a String


Problem: Reverse a string without using built-in reverse method

Solution:

4. public class StringReversal {


public static String reverseString(String str) {
char[] chars = [Link]();
int left = 0, right = [Link] - 1;
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
return new String(chars);
}

public static void main(String[] args) {


[Link](reverseString("hello")); // olleh
}
}
Program 5: Remove Duplicates from Array
Problem: Remove duplicate elements from an integer array

Solution:

5. import [Link].*;

public class RemoveDuplicates {


public static int[] removeDuplicates(int[] arr) {
Set<Integer> set = new LinkedHashSet<>();
for (int num : arr) {
[Link](num);
}
return [Link]().mapToInt(Integer::intValue).toArray();
}

public static void main(String[] args) {


int[] arr = {1, 2, 2, 3, 4, 4, 4, 5};
[Link]([Link](removeDuplicates(arr))); //
[1, 2, 3, 4, 5]
}
}

Program 6: Find Maximum and Minimum in Array


Problem: Find the largest and smallest elements in array

Solution:

6. public class MinMaxFinder {


public static void findMinMax(int[] arr) {
if ([Link] == 0) return;
int min = arr[0], max = arr[0];
for (int num : arr) {
if (num < min) min = num;
if (num > max) max = num;
}
[Link]("Min: " + min + ", Max: " + max);
}

public static void main(String[] args) {


int[] arr = {5, 2, 8, 1, 9, 3};
findMinMax(arr); // Min: 1, Max: 9
}
}

Program 7: Count Occurrence of Characters


Problem: Count frequency of each character in a string
Solution:

7. import [Link].*;

public class CharacterCount {


public static Map<Character, Integer> countChars(String str) {
Map<Character, Integer> map = new LinkedHashMap<>();
for (char c : [Link]()) {
[Link](c, [Link](c, 0) + 1);
}
return map;
}

public static void main(String[] args) {


[Link](countChars("hello")); // {h=1, e=1, l=2, o=1}
}
}
Program 8: Bubble Sort Implementation
Problem: Sort array using bubble sort algorithm

Solution:

8. import [Link];

public class BubbleSort {


public static void bubbleSort(int[] arr) {
int n = [Link];
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
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);
[Link]([Link](arr)); // [11, 12, 22, 25, 34,
64, 90]
}
}

Program 9: Binary Search


Problem: Search for an element in sorted array using binary search

Solution:

9. public class BinarySearch {


public static int binarySearch(int[] arr, int target) {
int left = 0, right = [Link] - 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; // Not found
}

public static void main(String[] args) {


int[] arr = {1, 3, 5, 7, 9, 11, 13};
[Link](binarySearch(arr, 7)); // 3
[Link](binarySearch(arr, 6)); // -1
}
}

Program 10: Thread Example


Problem: Create threads to print numbers alternately

Solution:

10. public class ThreadExample {


public static void main(String[] args) {
Thread t1 = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
[Link]("Thread 1: " + i);
try { [Link](1000); } catch (InterruptedException
e) {}
}
});

Thread t2 = new Thread(() -> {


for (int i = 1; i <= 5; i++) {
[Link]("Thread 2: " + i);
try { [Link](1000); } catch (InterruptedException
e) {}
}
});

[Link]();
[Link]();
}
}
INTERVIEW TIPS & BEST PRACTICES
 Always ask clarifying questions before diving into answers.
 Explain your approach before writing code.
 Write clean, readable code with proper variable names.
 Consider edge cases and handle them appropriately.
 Discuss time and space complexity of your solutions.
 Test your code with examples before submitting.
 Use meaningful comments to explain complex logic.
 Follow Java naming conventions (camelCase for variables and methods).
 Practice problems on LeetCode, HackerRank, and GeeksforGeeks.
 Understand concepts deeply, don't just memorize.
 Know the difference between similar concepts (List vs Set, HashMap vs TreeMap).
 Be familiar with Java 8 features: Lambda, Streams, Functional Interfaces.
 Understand the Java memory model and garbage collection.
 Know about design patterns (Singleton, Factory, Observer, etc).
 Practice coding in text editor before using IDE in interview.
© 2024 Java Interview Preparation Guide | Best of luck with your interview!

You might also like