java interview medium q&a
java interview medium q&a
A class is a blueprint for creating objects. It defines properties (also called fields or attributes) and
behaviors (also called methods). Think of it like a blueprint for building houses; the blueprint defines
the structure, but the actual houses are the objects created from it.
Example:
class Car {
1. Concrete Class:
A normal class you can instantiate (create objects from).
Example: class Car { }
2. Abstract Class:
Cannot be instantiated directly.
Can have both abstract (no body) and concrete (with body) methods.
Example:
abstract class Vehicle {
abstract void start();
}
3. Final Class:
Cannot be subclassed.
Example:
final class Bike { }
4. Inner Class:
Defined within another class.
Can be static or non-static.
Example:
class Outer {
class Inner { }
}
5. Anonymous Class:
A class without a name, usually used for quick implementations.
Example:
Runnable r = new Runnable() {
public void run() {
System.out.println("Running in anonymous class");
}
};
An object is an instance of a class. It represents real-world entities with state (properties) and
behavior (methods).
Example:
myCar.color = "Red";
myCar.drive();
Example:
Explanation:
6. What is a Constructor?
Example:
class Car {
String color;
// Constructor
Car(String c) {
color = c;
void drive() {
class Main {
myCar.drive();
7. Syntax of Constructor:
ClassName(parameters) {
// Initialization code
Example:
class Bike {
int speed;
Bike(int s) {
speed = s;
}
8. Types of Constructors:
9. What is a Method?
Example:
class Calculator {
return a + b;
returnType methodName(parameters) {
// Code block
Example:
return a * b;
class AreaCalculator {
AreaCalculator() {
class Main {
In Java, you can read user input using the Scanner class from the java.util package.
import java.util.Scanner;
class Main {
sc.close();
}
When to Use: When the class should be accessible from other packages.
class MyClass {
When to Use: When you want to restrict access to the same package.
Not applicable for top-level classes. Only for members inside classes:
class Parent {
When to Use: To allow access to subclasses and classes in the same package.
class Outer {
void display() {
When to Use: To restrict access to the inner class within the outer class.
19. What Is the static Keyword?
The static keyword means the member belongs to the class, not instances.
class Counter {
Counter() {
count++;
class Main {
new Counter();
new Counter();
System.out.println(Counter.count); // Output: 2
When to Use: When you want to keep track of shared data across all objects.
A static method belongs to the class, not instances. It can be called without creating an object.
class MathUtils {
return a + b;
}
}
class Main {
When to Use: For utility methods like Math.max(), which don’t require object state.
A static block is used for static initialization. It runs only once when the class is loaded.
class Example {
static {
class Main {
System.out.println(Example.value);
When to Use: For initializing static variables that require complex logic.
void display() {
class Main {
obj.display();
When to Use: For logically grouping classes without creating an instance of the outer class.
Method overloading allows multiple methods with the same name but different parameters (type,
number, or order).
class Calculator {
return a + b;
return a + b;
class MathUtils {
return a * b;
return a * b;
class Main {
Similar to method overloading, but with constructors. Multiple constructors with different
parameters.
class Person {
String name;
int age;
Person() {
name = "Unknown";
age = 0;
Person(String name) {
this.name = name;
age = 0;
this.name = name;
this.age = age;
class Vehicle {
int wheels;
Vehicle() {
wheels = 4;
Vehicle(int w) {
wheels = w;
}
class Main {
Return Type Must have a return type (or No return type (not even
void) void)
Inheritance allows one class (child) to inherit properties and methods from another (parent).
class Animal {
void eat() {
System.out.println("Eating...");
}
}
void bark() {
System.out.println("Barking...");
When to Use: To reuse code and create a hierarchy (e.g., animals, vehicles).
1. Single Inheritance: One child class inherits from one parent class.
2. class Animal {
3. void eat() {
4. System.out.println("Eating...");
5. }
6. }
7.
8. class Dog extends Animal {
9. void bark() {
10. System.out.println("Barking...");
11. }
12. }
13. Multilevel Inheritance: A child class inherits from a parent, and another class inherits from the
child.
14. class Animal {
15. void eat() {
16. System.out.println("Eating...");
17. }
18. }
19.
20. class Mammal extends Animal {
21. void walk() {
22. System.out.println("Walking...");
23. }
24. }
25.
26. class Dog extends Mammal {
27. void bark() {
28. System.out.println("Barking...");
29. }
30. }
31. Hierarchical Inheritance: Multiple classes inherit from a single parent.
32. class Animal {
33. void eat() {
34. System.out.println("Eating...");
35. }
36. }
37.
38. class Dog extends Animal {
39. void bark() {
40. System.out.println("Barking...");
41. }
42. }
43.
44. class Cat extends Animal {
45. void meow() {
46. System.out.println("Meowing...");
47. }
48. }
49. Multiple Inheritance (via Interfaces): Java doesn’t support multiple inheritance with classes but
allows it through interfaces.
50. interface Flyable {
51. void fly();
52. }
53.
54. interface Swimable {
55. void swim();
56. }
57.
58. class Bird implements Flyable, Swimable {
59. public void fly() {
60. System.out.println("Flying...");
61. }
62.
63. public void swim() {
64. System.out.println("Swimming...");
65. }
66. }
Single Inheritance:
class Parent { }
class Child extends Parent { }
Multilevel Inheritance:
class Grandparent { }
class Parent extends Grandparent { }
class Child extends Parent { }
Hierarchical Inheritance:
class Parent { }
class Child1 extends Parent { }
class Child2 extends Parent { }
Multiple Inheritance (via Interfaces):
interface Interface1 { }
interface Interface2 { }
class Child implements Interface1, Interface2 { }
Method overriding allows a child class to provide a specific implementation of a method already
defined in its parent class.
Rule: The method in the child class must have the same name, return type, and parameters.
Example:
class Animal {
void sound() {
@Override
void sound() {
System.out.println("Dog barks");
class Main {
Example:
void start() {
System.out.println("Car starts");
class Main {
Abstract Class:
abstract class ClassName { }
Abstract Method:
abstract void methodName();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle");
class Main {
Explanation: Shape is an abstract class with an abstract method draw(), implemented by Circle.
An interface is a contract that defines a set of methods without implementations. Classes that
implement the interface must provide implementations for all methods.
interface Drawable {
void draw();
System.out.println("Drawing Rectangle");
When to Use: To achieve multiple inheritance and define common behavior across classes.
interface Playable {
void play();
System.out.println("Playing Guitar");
System.out.println("Playing Piano");
class Main {
guitar.play();
piano.play();
}
Explanation: Both Guitar and Piano implement the Playable interface, ensuring they provide their
own play() method.
A wrapper class is a class that "wraps" a primitive data type into an object.
Example:
System.out.println(wrapperNum);
1. Arithmetic Operators: +, -, *, /, %
2. Relational Operators: ==, !=, >, <, >=, <=
3. Logical Operators: &&, ||, !
4. Assignment Operators: =, +=, -=, *=, /=, %=
5. Bitwise Operators: &, |, ^, ~, <<, >>, >>>
6. Unary Operators: +, -, ++, --, !
7. Ternary Operator: ? :
8. Instanceof Operator: instanceof
try {
} catch (ArithmeticException e) {
finally is used for code that should always execute, regardless of whether an exception occurs.
Syntax:
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("This will always execute.");
}
}
}
When to Use: For closing resources like files or database connections.
1. Length: str.length()
2. Concatenation: str1 + str2
3. Substring: str.substring(0, 5)
4. Comparison: str.equals("Hello")
5. To Upper/Lower Case: str.toUpperCase(), str.toLowerCase()
6. Trim Spaces: str.trim()
7. Replace Characters: str.replace("o", "0")
Purpose: To prevent race conditions when multiple threads access shared resources.
Example:
class Counter {
private int count = 0;
int getCount() {
return count;
}
}
When to Use: In critical sections where thread safety is required.
53. Which Collection Should Be Used for What? (Java Collections Comparison Table)
Collection Purpose Example When to Use
54. What is a Stream Class? What Are the Types of Stream Class and What is the Purpose of
Each Class?
Example:
import java.io.*;
class Main {
writer.close();
JDBC (Java Database Connectivity): An API to connect Java applications with databases.
Purpose: To perform CRUD (Create, Read, Update, Delete) operations.
57. What Are the Steps to Connect to a MySQL Database Using JDBC?
Syntax:
import javax.swing.*;
Example (Simple GUI):
import javax.swing.*;
class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello, Swing!");
JButton button = new JButton("Click Me");
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}