0% found this document useful (0 votes)
3 views11 pages

Java Interview Questions

The document provides a comprehensive list of Java interview questions and answers covering various topics such as abstract classes, encapsulation, inheritance, polymorphism, and exception handling. Each question includes a brief explanation, code examples, and interview tips to help candidates understand key concepts. It serves as a valuable resource for preparing for Java-related job interviews.

Uploaded by

jujutsuryukendo
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)
3 views11 pages

Java Interview Questions

The document provides a comprehensive list of Java interview questions and answers covering various topics such as abstract classes, encapsulation, inheritance, polymorphism, and exception handling. Each question includes a brief explanation, code examples, and interview tips to help candidates understand key concepts. It serves as a valuable resource for preparing for Java-related job interviews.

Uploaded by

jujutsuryukendo
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

Java Interview Questions & Answers

Q1: Can we name an abstract class as Main and provide


functions inside it?
Yes, in Java you can name any class (abstract or concrete) Main. It's just an identifier.
You can define methods (abstract or concrete) inside it. However, it won't run as a
Java program unless it has a main() method.
java
abstract class Main {
void greet() {
[Link]("Hello from Main abstract class");
}
abstract void show();
}

In interviews, mention:
"Class names are developer-defined identifiers. Naming an abstract class Main is
valid, but to execute it as a program, we still need a separate class with a public
static void main(String[] args) method."

Q2: How do we use a constructor in a child class when


extending a parent class?
If the parent has a constructor, use super() in the child class to invoke it.
If no constructor is defined, Java adds a default constructor implicitly.
java
class Parent {
Parent(String msg) {
[Link]("Parent: " + msg);
}
}

class Child extends Parent {


Child() {
super("Hello from Child");
[Link]("Child Constructor");
}
}

In interviews, say:
"To initialize the parent class in inheritance, we use super() from the child class
constructor to call the parent's constructor explicitly."

Q3: What is the use of encapsulation in Java?


Encapsulation is a fundamental OOP principle that bundles data (variables) and
methods into a single unit (class), restricting direct access to internal fields using
private access modifiers.
Example:
java
class Student {
private int marks;

public void setMarks(int m) {


if(m >= 0) marks = m;
}

public int getMarks() {


return marks;
}
}

Interview tip:
"Encapsulation ensures data security, hides implementation details, and provides
controlled access via getters and setters."

Q4: What is the difference between private and protected


in Java?

Modifier Access Level

private Accessible only within the class

protected Accessible in same package and subclasses in other packages

Example:
java
class A {
private int a = 10;
protected int b = 20;
}

Interview tip:
"Use private for strict encapsulation and protected when you want to allow subclass-
level access outside the package."

Q5: Can we override a constructor in Java?


No, constructors cannot be overridden because they are not inherited. However,
constructors can be overloaded.
java
class A {
A() { [Link]("Default Constructor"); }
A(int x) { [Link]("Param Constructor: " + x); }
}

In interviews:
"Java constructors are not inherited, so they can't be overridden. But we can overload
them within the same class by changing parameter lists."

Q6: What is multilevel inheritance? Explain with example.


Multilevel inheritance refers to a chain of inheritance where a class inherits from a
class, which itself inherits from another class.
java
class A {
void showA() { [Link]("A"); }
}
class B extends A {
void showB() { [Link]("B"); }
}
class C extends B {
void showC() { [Link]("C"); }
}

Interview line:
"In multilevel inheritance, one class acts as a base for a derived class, which in turn
becomes a base for another derived class. Java supports this
using extends keyword."

Q7: What does it mean when we say Driver class inherits


from a parent?
This means the Driver class is a subclass, typically used to demonstrate/test the
behavior of inherited methods or properties.
java
class Vehicle {
void drive() {
[Link]("Driving...");
}
}

class Driver extends Vehicle {


public static void main(String[] args) {
Driver d = new Driver();
[Link](); // Inherited method
}
}

Interview tip:
"Driver class is often used to test OOP concepts. Here, it inherits all accessible
members from its parent class using extends."

Q8: What is the role of the private keyword for class


variables and methods?
When a variable/method is private, it is accessible only within the same class.
It enforces encapsulation and prevents accidental modification from outside.
Example:
java
class Secret {
private String code = "XYZ";

private void reveal() {


[Link]("Secret code is: " + code);
}
}

Interview point:
"private is used to protect internal data and restrict access, ensuring internal
consistency and modular design."

Q9: Difference between abstract class and interface (Java


8+)

Feature Abstract Class Interface (Java 8+)

Methods Abstract & concrete allowed Abstract, default, and static

Variables Instance or static allowed Only public static final

Multiple Inherit Single class only Multiple inheritance allowed

Constructor Can have constructors No constructors


Example:
java
abstract class Animal {
abstract void makeSound();
}

interface Walkable {
default void walk() {
[Link]("Walking...");
}
}

Interview line:
"Use abstract class when you want to share common code among related classes, and
interface when unrelated classes should follow a contract."

Q10: What is Dynamic Polymorphism in Java?


Answer:
Dynamic polymorphism (also known as runtime polymorphism) occurs when the
method to be invoked is determined at runtime using method overriding and
upcasting.
Key points:
• Achieved via method overriding in inheritance.
• The decision of which method to call is made during execution, not at compile
time.
• Uses a reference of the parent class pointing to a child class object.
Example:
java
class Animal {
void sound() {
[Link]("Animal makes sound");
}
}

class Dog extends Animal {


void sound() {
[Link]("Dog barks");
}
}

public class Test {


public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
[Link](); // Runtime decision → Dog's sound()
}
}
Interview Tip:
"Dynamic polymorphism enables flexibility and late binding in object-oriented design.
It's the core of Java's method overriding feature and allows for generic programming
with different subclasses."

Q11: What are the steps to create a user-defined exception


in Java?
Answer:
Java allows creating custom exceptions by extending the Exception (checked)
or RuntimeException (unchecked) class.
Steps:
• Create the exception class:
java
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}

• Use throw to raise the exception:


java
if (age < 18)
throw new InvalidAgeException("Age must be 18+");

• Handle it using try-catch:


java
try {
checkAge(16);
} catch (InvalidAgeException e) {
[Link]("Caught: " + [Link]());
}

Full Example:
java
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) {
super(msg);
}
}

class Test {
static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("You must be 18 or older.");
}
[Link]("Valid age");
}

public static void main(String[] args) {


try {
checkAge(16);
} catch (InvalidAgeException e) {
[Link]("Caught Exception: " + [Link]());
}
}
}

Interview Tip:
"User-defined exceptions provide better control and meaningful error handling in real-
world applications by extending Java's exception hierarchy."

Q12: How to prevent method overriding in Java base class?


Answer:
To prevent a method from being overridden in a subclass, use the final keyword.
Syntax:
java
class Base {
final void display() {
[Link]("Base display");
}
}

class Derived extends Base {


// void display() {} ❌ Compile-time Error: cannot override final method
}

Interview Tip:
"Using final ensures that subclasses cannot override important logic in base class
methods, which is useful for securing API methods or base behaviors."

Q13: What are getters and setters in Java?


Answer:
Getters return the value of a private field.
Setters set or update the value of a private field.
They support encapsulation by providing controlled access to class members.
Example:
java
class Student {
private int age;

public int getAge() {


return age;
}

public void setAge(int a) {


if (a > 0)
age = a;
}
}

Interview Tip:
"Getters and setters allow for validation, security, and flexibility in accessing and
updating private fields."

Q14: How do you swap two numbers without using a


temporary variable?
Answer:
Approach 1: Using arithmetic
java
int a = 5, b = 10;

a = a + b; // 15
b = a - b; // 5
a = a - b; // 10

Approach 2: Using XOR (bitwise)


java
a = a ^ b;
b = a ^ b;
a = a ^ b;

Interview Tip:
"This question checks problem-solving and understanding of bitwise or arithmetic
operations. Use XOR for safer results with large numbers."

Q15: How to implement data hiding in Java?


Answer:
Data hiding is done by making variables private and accessing them via public
methods (getters and setters).
Example:
java
class Account {
private double balance;

public double getBalance() {


return balance;
}

public void deposit(double amount) {


if (amount > 0)
balance += amount;
}
}
Interview Tip:
"Data hiding protects object integrity by restricting direct access and enforcing
validation before data changes."

Q16: Why is String immutable in Java?


Answer:
String is immutable to ensure security, thread safety, and efficient memory usage via
the String pool.
java
String a = "hello";
[Link](" world"); // doesn't change original string
[Link](a); // prints "hello"
In interviews:
"String objects cannot be changed after creation. This prevents issues in
multithreaded code and allows safe reuse through the String constant pool."

Q17: Can we write the main() method both outside and


inside the class in Java?
Answer:
No. In Java, main() must be inside a class. Java doesn’t support top-level functions
like C/C++.
java
class MyApp {
public static void main(String[] args) {
[Link]("Hello, Java!");
}
}
In interviews:
"main() must be inside a class because Java is fully object-oriented. It doesn’t allow
standalone functions like in C."

Q18: What is an interface in Java?


Answer:
An interface is a blueprint for a class. It can contain abstract, default, and static
methods, but no constructors.
java
interface Animal {
void sound();
}

class Dog implements Animal {


public void sound() {
[Link]("Bark");
}
}
In interviews:
"Interfaces are used to achieve abstraction and multiple inheritance. Java 8 added
default and static methods."

Q19: What are mutable and immutable objects in Java?


Answer:
Mutable: Internal state can change (e.g., ArrayList, StringBuilder)
Immutable: State cannot change once created (e.g., String, Integer)
java
StringBuilder sb = new StringBuilder("Hello");
[Link](" World"); // mutable

String s = "Hello";
[Link](" World"); // creates new string, original unchanged
In interviews:
"Mutable objects can change, like StringBuilder. Immutable objects like String are
fixed after creation."

Q20: Is operator overloading supported in Java?


Answer:
No. Java does not support operator overloading except for "+" with String.
java
String s = "Age: " + 25; // '+' overloaded for String
int sum = 10 + 20; // normal usage
In interviews:
"Java avoids operator overloading for simplicity and readability, unlike C++ which
allows it."

Q21: How many times does a do-while loop execute in


Java?
Answer:
A do-while loop runs at least once, even if the condition is false.
java
int i = 0;
do {
[Link]("Runs once");
} while (i > 0);
In interviews:
"do-while guarantees one execution before condition check. Useful for menu-driven
or user input logic."

You might also like