Core Java Interview Questions
Introduction
Core Java is a fundamental skill for many software development roles. Understanding key concepts and common interview questions can help you succeed in technical interviews.
This tutorial covers frequently asked Core Java interview questions with clear explanations and practical examples to boost your confidence.
Master the basics to excel in Java interviews.
Basic Core Java Concepts
Interviewers often start with questions about Java basics to assess your foundational knowledge.
Topics include data types, control structures, object-oriented programming principles, and exception handling.
- What are the main features of Java?
- Explain the difference between JDK, JRE, and JVM.
- What are primitive data types in Java?
- Describe the concept of object-oriented programming.
- How does exception handling work in Java?
Java Features
Java is a high-level, platform-independent, object-oriented programming language with automatic memory management.
- Simple and familiar syntax
- Platform independence via bytecode and JVM
- Robust and secure
- Multithreaded support
- Automatic garbage collection
JDK, JRE, and JVM Explained
Understanding the Java platform components is crucial for interviews.
- JDK (Java Development Kit): Tools for developing Java applications including compiler and debugger.
- JRE (Java Runtime Environment): Provides libraries and JVM to run Java applications.
- JVM (Java Virtual Machine): Executes Java bytecode and provides platform independence.
Object-Oriented Programming in Java
OOP concepts are central to Java programming and frequently tested in interviews.
Key principles include encapsulation, inheritance, polymorphism, and abstraction.
- What is encapsulation and how is it implemented in Java?
- Explain inheritance with an example.
- What is polymorphism? Differentiate between compile-time and runtime polymorphism.
- Describe abstraction and how abstract classes and interfaces differ.
Encapsulation
Encapsulation is the technique of wrapping data and methods into a single unit, typically a class, and restricting access using access modifiers.
- Use private variables with public getter and setter methods.
- Protects data integrity and hides implementation details.
Inheritance
Inheritance allows a new class to acquire properties and behaviors of an existing class, promoting code reuse.
- Use the 'extends' keyword to inherit from a superclass.
- Supports hierarchical classification.
Polymorphism
Polymorphism means 'many forms' and allows methods to perform differently based on the object invoking them.
Java Exception Handling
Exception handling is a critical topic in Java interviews to assess your ability to write robust code.
- What is an exception in Java?
- Difference between checked and unchecked exceptions.
- Explain try-catch-finally blocks.
- What is the purpose of the throws keyword?
- How to create custom exceptions?
Checked vs Unchecked Exceptions
Checked exceptions are checked at compile time, while unchecked exceptions occur at runtime.
- Checked exceptions must be handled or declared using throws.
- Unchecked exceptions extend RuntimeException and do not require mandatory handling.
Try-Catch-Finally
The try block contains code that might throw exceptions, catch handles them, and finally executes cleanup code.
- Finally block executes regardless of exception occurrence.
- Multiple catch blocks can handle different exception types.
Java Collections Framework
Understanding collections is essential for managing groups of objects efficiently.
- What are the main interfaces in the Collections Framework?
- Difference between List, Set, and Map.
- Explain ArrayList vs LinkedList.
- What is the difference between HashMap and TreeMap?
| Interface | Description | Allows Duplicates | Order Maintained |
|---|---|---|---|
| List | Ordered collection, allows duplicates | Yes | Yes |
| Set | Collection with unique elements | No | No (except LinkedHashSet) |
| Map | Key-value pairs, keys unique | No (keys) | No (except LinkedHashMap) |
Examples
public class ExceptionDemo {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("Execution completed.");
}
}
}This example demonstrates handling an ArithmeticException when dividing by zero, with a finally block that always executes.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
public class TestPolymorphism {
public static void main(String[] args) {
Animal a = new Dog();
a.sound(); // Runtime polymorphism
}
}This example shows runtime polymorphism where the Dog class overrides the sound method of Animal.
Best Practices
- Understand and explain concepts clearly with examples.
- Practice coding common Java interview questions.
- Use proper naming conventions and code formatting.
- Handle exceptions thoughtfully to avoid program crashes.
- Know the differences between similar concepts like abstract classes and interfaces.
Common Mistakes
- Confusing checked and unchecked exceptions.
- Not using access modifiers properly for encapsulation.
- Overusing inheritance instead of composition.
- Ignoring the importance of the finally block in exception handling.
- Mixing up List and Set behaviors.
Hands-on Exercise
Implement a Custom Exception
Create a custom checked exception called InvalidAgeException and throw it when an age value is less than 18.
Expected output: Exception thrown with a descriptive message when age < 18.
Hint: Extend the Exception class and use the throw keyword.
Demonstrate Polymorphism
Write a program with a superclass Shape and subclasses Circle and Rectangle that override a method draw().
Expected output: Correct draw() method output for Circle and Rectangle objects.
Hint: Use method overriding and demonstrate runtime polymorphism.
Interview Questions
What are the main features of Java?
InterviewJava is platform-independent, object-oriented, robust, secure, multithreaded, and supports automatic memory management.
Explain the difference between JDK, JRE, and JVM.
InterviewJDK is the development kit including compiler and tools, JRE provides the runtime environment to run Java programs, and JVM executes Java bytecode on the host machine.
What is polymorphism in Java?
InterviewPolymorphism allows methods to have multiple forms, enabling method overloading (compile-time) and method overriding (runtime).
How does Java handle exceptions?
InterviewJava uses try-catch-finally blocks to handle exceptions, distinguishing between checked exceptions that must be handled or declared, and unchecked exceptions that occur at runtime.
What is the difference between ArrayList and LinkedList?
InterviewArrayList uses a dynamic array for storage and provides fast random access, while LinkedList uses a doubly linked list allowing efficient insertions and deletions.
Summary
This tutorial covered essential Core Java interview questions focusing on fundamental concepts such as Java features, OOP principles, exception handling, and collections.
Understanding these topics with practical examples will prepare you well for technical interviews and help you write better Java code.
FAQ
What is the difference between an abstract class and an interface in Java?
An abstract class can have both abstract and concrete methods and can maintain state, while an interface only declares methods (until Java 8) and cannot hold state. A class can implement multiple interfaces but only extend one abstract class.
Why is Java platform-independent?
Java is platform-independent because Java programs are compiled into bytecode, which runs on the Java Virtual Machine (JVM) that is available on many platforms.
What is the purpose of the finally block?
The finally block contains code that always executes after try and catch blocks, used for cleanup activities like closing resources.
Can you explain method overloading and overriding?
Method overloading is having multiple methods with the same name but different parameters within the same class (compile-time polymorphism). Method overriding is redefining a superclass method in a subclass with the same signature (runtime polymorphism).
