0% found this document useful (0 votes)
4 views

java interview medium q&a

The document provides an overview of Java classes, objects, constructors, methods, and inheritance. It explains the types of classes, how to create objects, the purpose of constructors, and the concept of method overloading and overriding. Additionally, it covers access modifiers, static members, and different types of inheritance in Java.

Uploaded by

kangirene9705
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)
4 views

java interview medium q&a

The document provides an overview of Java classes, objects, constructors, methods, and inheritance. It explains the types of classes, how to create objects, the purpose of constructors, and the concept of method overloading and overriding. Additionally, it covers access modifiers, static members, and different types of inheritance in Java.

Uploaded by

kangirene9705
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
You are on page 1/ 28

1. What is a Class in Java?

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 {

String color; // Property

void drive() { // Behavior

System.out.println("The car is driving.");

Here, Car is a class with a property (color) and a behavior (drive()).

2. Types of Classes in Java:

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");
}
};

3. What is an Object in Java?

An object is an instance of a class. It represents real-world entities with state (properties) and
behavior (methods).

State: Values of properties (like color, speed).


Behavior: Actions the object can perform (like drive, stop).

Example:

Car myCar = new Car(); // 'myCar' is an object of class Car

myCar.color = "Red";

myCar.drive();

4. How to Create an Object in Java?

You create an object using the new keyword followed by a constructor.

ClassName objectName = new ClassName();

Example:

Car car1 = new Car();

5. Syntax for Object Creation:

ClassName objectName = new ClassName();

Explanation:

ClassName: The class from which the object is created.


objectName: The reference variable to hold the object.
new: Keyword to allocate memory.
Constructor ClassName(): Initializes the object.

6. What is a Constructor?

A constructor is a special method in Java used to initialize objects.

It has the same name as the class.


It has no return type (not even void).
It’s automatically called when an object is created.

Example:

class Car {

String color;
// Constructor

Car(String c) {

color = c;

void drive() {

System.out.println("The " + color + " car is driving.");

class Main {

public static void main(String[] args) {

Car myCar = new Car("Red"); // Constructor is called here

myCar.drive();

Here, Car(String c) is the constructor that initializes the color property.

7. Syntax of Constructor:

ClassName(parameters) {

// Initialization code

Example:

class Bike {

int speed;

Bike(int s) {

speed = s;
}

8. Types of Constructors:

1. Default Constructor: No parameters.


2. class Bike {
3. Bike() {
4. System.out.println("Default Constructor");
5. }
6. }
7. Parameterized Constructor: Takes parameters to initialize objects.
8. class Bike {
9. int speed;
10. Bike(int s) {
11. speed = s;
12. }
13. }
14. Copy Constructor: Creates a new object as a copy of an existing one.
15. class Bike {
16. int speed;
17. Bike(Bike b) {
18. speed = b.speed;
19. }
20. }

9. What is a Method?

A method is a block of code that performs a specific task.

It can take inputs (parameters) and return an output (value).


Methods help organize code into reusable units.

Example:

class Calculator {

int add(int a, int b) {

return a + b;

10. Syntax of a Method:

returnType methodName(parameters) {

// Code block

return value; // (optional if returnType is void)


}

Example:

int multiply(int a, int b) {

return a * b;

10a. Program for Area Calculation with Constructor and Method:

class AreaCalculator {

AreaCalculator() {

System.out.println("Area Calculator Initialized");

double circleArea(double radius) {

return Math.PI * radius * radius;

double rectangleArea(double length, double width) {

return length * width;

double triangleArea(double base, double height) {

return 0.5 * base * height;

class Main {

public static void main(String[] args) {

AreaCalculator ac = new AreaCalculator();


System.out.println("Circle Area: " + ac.circleArea(5));

System.out.println("Rectangle Area: " + ac.rectangleArea(4, 6));

System.out.println("Triangle Area: " + ac.triangleArea(3, 4));

Constructor: Initializes the calculator.


Methods: Calculate the area of different shapes.

11. Difference Between Pre-defined and User-defined Methods:

Pre-defined Methods: Built-in methods provided by Java (like System.out.println()).


User-defined Methods: Methods created by programmers to perform specific tasks.

12. Methods with Varargs:

Varargs allow a method to accept a variable number of arguments.

void display(int... nums) {

for (int num : nums) {

System.out.print(num + " ");

Call it like: display(1, 2, 3, 4);

13. How Do You Read Input from the User?

In Java, you can read user input using the Scanner class from the java.util package.

import java.util.Scanner;

class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");

int num = sc.nextInt(); // Reads an integer

System.out.println("You entered: " + num);

sc.close();
}

Scanner sc = new Scanner(System.in); creates a Scanner object to read input.


nextInt() reads an integer.
close() is used to close the Scanner when done.

14. Methods of the Scanner Class:

next(): Reads the next token.


nextLine(): Reads the entire line.
nextInt(): Reads an integer.
nextDouble(): Reads a double.
nextBoolean(): Reads a boolean.
nextChar() (not a standard method, use next().charAt(0) instead).

15. How to Accept a Number from the User?

Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = sc.nextInt();

System.out.println("You entered: " + number);

16. How to Accept a Character from the User?

Scanner sc = new Scanner(System.in);

System.out.print("Enter a character: ");

char ch = sc.next().charAt(0); // Reads first character of the input

System.out.println("You entered: " + ch);

17. How to Accept a String from the User?

Scanner sc = new Scanner(System.in);

System.out.print("Enter a string: ");

String str = sc.nextLine(); // Reads an entire line

System.out.println("You entered: " + str);

18. What Are Access Modifiers?

Access modifiers define the visibility of classes, methods, and variables:

1. public: Accessible from anywhere.


2. protected: Accessible within the same package and subclasses.
3. default (no modifier): Accessible only within the same package.
4. private: Accessible only within the same class.

18a. How to Declare a Class as Public?

public class MyClass {

// Accessible from anywhere

When to Use: When the class should be accessible from other packages.

18b. How to Declare a Default Class?

class MyClass {

// Accessible only within the same package

When to Use: When you want to restrict access to the same package.

18c. How to Declare a Protected Class?

Not applicable for top-level classes. Only for members inside classes:

class Parent {

protected int number;

When to Use: To allow access to subclasses and classes in the same package.

18d. How to Declare a Private Class?

Only possible for inner classes:

class Outer {

private class Inner {

void display() {

System.out.println("Private Inner Class");

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.

Static Variable: Shared by all instances.


Static Method: Can be called without creating an object.
Static Block: Used for static initialization.
Static Class: Only for nested classes.

19a. What is a Static Variable?

class Counter {

static int count = 0; // Shared among all instances

Counter() {

count++;

class Main {

public static void main(String[] args) {

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.

19b. What is a Static Method?

A static method belongs to the class, not instances. It can be called without creating an object.

class MathUtils {

static int add(int a, int b) {

return a + b;

}
}

class Main {

public static void main(String[] args) {

System.out.println(MathUtils.add(5, 10)); // No object needed

When to Use: For utility methods like Math.max(), which don’t require object state.

19c. What is a Static Block?

A static block is used for static initialization. It runs only once when the class is loaded.

class Example {

static int value;

static {

value = 100; // Initialization

System.out.println("Static block executed");

class Main {

public static void main(String[] args) {

System.out.println(Example.value);

When to Use: For initializing static variables that require complex logic.

19d. What is a Static Class?

A static class is only allowed for nested classes.


class Outer {

static class Inner {

void display() {

System.out.println("Static Inner Class");

class Main {

public static void main(String[] args) {

Outer.Inner obj = new Outer.Inner();

obj.display();

When to Use: For logically grouping classes without creating an instance of the outer class.

20. What is Method Overloading?

Method overloading allows multiple methods with the same name but different parameters (type,
number, or order).

class Calculator {

int add(int a, int b) {

return a + b;

double add(double a, double b) {

return a + b;

int add(int a, int b, int c) {


return a + b + c;

When to Use: To perform similar operations with different data types.

21. Example Program for Method Overloading:

class MathUtils {

int multiply(int a, int b) {

return a * b;

double multiply(double a, double b) {

return a * b;

class Main {

public static void main(String[] args) {

MathUtils mu = new MathUtils();

System.out.println(mu.multiply(3, 4)); // int version

System.out.println(mu.multiply(2.5, 4.0)); // double version

22. What is Constructor Overloading?

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;

Person(String name, int age) {

this.name = name;

this.age = age;

When to Use: To initialize objects differently based on the provided data.

23. Example Program for Constructor Overloading:

class Vehicle {

int wheels;

Vehicle() {

wheels = 4;

Vehicle(int w) {

wheels = w;
}

class Main {

public static void main(String[] args) {

Vehicle car = new Vehicle();

Vehicle bike = new Vehicle(2);

System.out.println("Car wheels: " + car.wheels);

System.out.println("Bike wheels: " + bike.wheels);

24. Differences Between Methods and Constructors:

Aspect Methods Constructors

Name Can have any name Same name as the class

Return Type Must have a return type (or No return type (not even
void) void)

Purpose To perform actions To initialize objects

Overloading Supported Supported

25. What is Inheritance?

Inheritance allows one class (child) to inherit properties and methods from another (parent).

class Animal {

void eat() {

System.out.println("Eating...");

}
}

class Dog extends Animal {

void bark() {

System.out.println("Barking...");

When to Use: To reuse code and create a hierarchy (e.g., animals, vehicles).

26. Types of Inheritance in Java:

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. }

27. Syntax for Different Types of Inheritance:

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 { }

28. What is an Overriding Method?

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() {

System.out.println("Animal makes a sound");

class Dog extends Animal {

@Override

void sound() {

System.out.println("Dog barks");

class Main {

public static void main(String[] args) {

Dog dog = new Dog();

dog.sound(); // Output: Dog barks

When to Use: To change or extend the behavior of an inherited method.

29. What is an Abstract Class? What is an Abstract Method?


Abstract Class: A class that cannot be instantiated and may have abstract methods (without a
body).
Abstract Method: A method without a body; must be implemented in a subclass.

Example:

abstract class Vehicle {

abstract void start();

class Car extends Vehicle {

void start() {

System.out.println("Car starts");

class Main {

public static void main(String[] args) {

Vehicle v = new Car();

v.start(); // Output: Car starts

30. Syntax for Abstract Class and Abstract Method:

Abstract Class:
abstract class ClassName { }
Abstract Method:
abstract void methodName();

31. Example Program for Abstract Class:

abstract class Shape {

abstract void draw();

}
class Circle extends Shape {

void draw() {

System.out.println("Drawing Circle");

class Main {

public static void main(String[] args) {

Shape shape = new Circle();

shape.draw(); // Output: Drawing Circle

Explanation: Shape is an abstract class with an abstract method draw(), implemented by Circle.

32. What is an Interface?

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();

class Rectangle implements Drawable {

public void draw() {

System.out.println("Drawing Rectangle");

When to Use: To achieve multiple inheritance and define common behavior across classes.

33. Why and Where Do We Use an Interface?

Why Use an Interface?


To define a contract that classes must follow.
Achieves multiple inheritance (since Java doesn’t support it with classes).
Promotes loose coupling and polymorphism.
Where to Use?
For defining behaviors that can be shared across unrelated classes (e.g., Runnable,
Comparable).
When you want to ensure certain methods are implemented by all classes.

34. Example Program Using an Interface:

interface Playable {

void play();

class Guitar implements Playable {

public void play() {

System.out.println("Playing Guitar");

class Piano implements Playable {

public void play() {

System.out.println("Playing Piano");

class Main {

public static void main(String[] args) {

Playable guitar = new Guitar();

Playable piano = new Piano();

guitar.play();

piano.play();
}

Explanation: Both Guitar and Piano implement the Playable interface, ensuring they provide their
own play() method.

35. What is a Wrapper Class?

A wrapper class is a class that "wraps" a primitive data type into an object.

Examples: Integer, Double, Character, etc.


Purpose: To allow primitive types to be treated as objects, useful in collections (like ArrayList).

Example:

int num = 10;

Integer wrapperNum = Integer.valueOf(num); // Wrapping int into Integer

System.out.println(wrapperNum);

When to Use: When working with collections that require objects.

36. Name Some of the Operators in Java:

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

37. Name the Control Statements and Its Syntax:

1. Conditional Statements: if, else if, else, switch


2. if (condition) { }
3. else if (condition) { }
4. else { }
5. Looping Statements: for, while, do-while
6. for (int i = 0; i < 5; i++) { }
7. while (condition) { }
8. do { } while (condition);
9. Jump Statements: break, continue, return
10. break; // Exits loop
11. continue; // Skips current iteration
12. return; // Exits method

38. What is a Package in Java? When and Why Do We Use It?

Package: A namespace that organizes classes and interfaces.


Purpose: To avoid name conflicts and to organize code logically.
Syntax:
package com.example.myapp;
public class MyClass { }
Usage: For creating modular applications, managing access control, and reducing class name
conflicts.

39. What is the Difference Between Error and Exception?

Aspect Error Exception

Definition Serious issues (e.g., Issues that can be handled


OutOfMemoryError) (e.g., IOException)

Handling Not usually handled Can be caught using try-catch

Examples OutOfMemoryError, FileNotFoundException,


StackOverflowError NullPointerException

40. How to Handle Exceptions?

Using try-catch blocks:

try {

int result = 10 / 0; // This will cause an exception

} catch (ArithmeticException e) {

System.out.println("Error: " + e.getMessage());

try block: Contains code that might throw an exception.


catch block: Handles the exception.

41. What is a Try-Catch Block?

Purpose: To handle exceptions gracefully without crashing the program.


Syntax:
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Handling code
}

42. Will a Try Block Work Without a Catch Block?


No, a try block cannot work without a catch block unless it's followed by a finally block or is part
of a try-with-resources statement.
Example (Valid with Finally):
try {
int result = 10 / 0;
} finally {
System.out.println("This will always execute.");
}

43. How to Handle Exceptions Using throw?

throw is used to explicitly throw an exception.


Syntax:
public class Main {
public static void validate(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older.");
} else {
System.out.println("Valid age.");
}
}

public static void main(String[] args) {


validate(16); // This will throw an exception
}
}
When to Use: To manually throw exceptions when specific conditions occur.

44. How to Handle Exceptions Using throws?

throws is used to declare exceptions that a method might throw.


Syntax:
public class Main {
public static void checkFile() throws IOException {
throw new IOException("File not found.");
}

public static void main(String[] args) {


try {
checkFile();
} catch (IOException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
When to Use: When you want to delegate exception handling to the caller of the method.

45. How to Handle Exceptions Using finally?

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.

46. What is a String Constructor?

String Constructor: Used to create String objects.


Examples:
String s1 = new String("Hello");
String s2 = new String(new char[]{'J', 'a', 'v', 'a'});
When to Use: Rarely needed, as Java provides convenient string literals.

47. What is a String Variable?

A String variable holds a sequence of characters.


Example:
String message = "Hello, World!";
Key Point: Strings in Java are immutable (cannot be changed after creation).

48. Special String Operations and Modifying Strings:

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")

49. What is a Thread? What Happens if Thread Class is Not Used?

Thread: A lightweight process that runs concurrently.


Without Thread: You can’t perform multitasking in Java.
Creating a Thread:
1. Extending Thread class:
2. class MyThread extends Thread {
3. public void run() {
4. System.out.println("Thread running");
5. }
6. }
7.
8. class Main {
9. public static void main(String[] args) {
10. MyThread t = new MyThread();
11. t.start();
12. }
13. }

50. Ways to Create a Thread in Java:

1. Extending Thread Class:


Override the run() method.
2. Implementing Runnable Interface:
Implement the run() method.
3. Using Lambda Expressions (Java 8+):
4. Runnable task = () -> System.out.println("Thread with Lambda");
5. new Thread(task).start();

51. How to Start a Thread?

Using start() method:


Thread t = new Thread();
t.start(); // Starts the thread

52. What is the Purpose of synchronized Keyword? How It Helps?

Purpose: To prevent race conditions when multiple threads access shared resources.
Example:
class Counter {
private int count = 0;

synchronized void increment() {


count++;
}

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

List Ordered collection ArrayList, LinkedList When order matters,


duplicates allowed

Set Unique elements HashSet, TreeSet, To store unique


LinkedHashSet items

Queue FIFO (First In, First LinkedList, For scheduling tasks,


Out) PriorityQueue priority queues

Deque Double-ended queue ArrayDeque, For stack or queue


(FIFO/LIFO) LinkedList operations

Map Key-value pairs HashMap, TreeMap, For fast lookups, key-


LinkedHashMap based data

Stack LIFO (Last In, First Stack For backtracking


Out) algorithms

PriorityQueue Elements with PriorityQueue For tasks with


priority priority levels

54. What is a Stream Class? What Are the Types of Stream Class and What is the Purpose of
Each Class?

Streams are used to perform I/O operations (reading/writing data).


Types of Streams:
1. Byte Streams: Handle raw binary data. (InputStream, OutputStream)
2. Character Streams: Handle character data. (Reader, Writer)
3. Data Streams: Handle primitive data types. (DataInputStream, DataOutputStream)
4. Buffered Streams: Improve performance with buffering. (BufferedReader, BufferedWriter)
5. Object Streams: Handle serialization. (ObjectInputStream, ObjectOutputStream)

Example:

import java.io.*;

class Main {

public static void main(String[] args) throws IOException {

FileWriter writer = new FileWriter("file.txt");


writer.write("Hello, Java Streams!");

writer.close();

55. What Are the Methods Used in Each Class?

InputStream/OutputStream: read(), write(), close()


Reader/Writer: read(), write(), flush(), close()
BufferedReader: readLine(), read(), close()
ObjectInputStream/ObjectOutputStream: readObject(), writeObject(), close()

56. What is JDBC?

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?

1. Load JDBC Driver:


2. Class.forName("com.mysql.cj.jdbc.Driver");
3. Establish Connection:
4. Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_name",
"username", "password");
5. Create Statement:
6. Statement stmt = conn.createStatement();
7. Execute Query:
8. ResultSet rs = stmt.executeQuery("SELECT * FROM table_name");
9. Close Connection:
10. conn.close();

58. What Are Some of the Common Queries Used in JDBC?

SELECT: SELECT * FROM table_name;


INSERT: INSERT INTO table_name (col1, col2) VALUES (val1, val2);
UPDATE: UPDATE table_name SET col1 = val1 WHERE condition;
DELETE: DELETE FROM table_name WHERE condition;

59. How to Import a Swing Package?

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);
}
}

60. What is the Difference Between a Container and a Component?

Aspect Container Component

Definition Holds other GUI elements Represents a GUI element


(like buttons, labels)

Examples JFrame, JPanel, JDialog JButton, JLabel, JTextField

Purpose Organizes layout and Performs actions or displays


structure data

Can Contain Other containers and Only components


components

You might also like