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

Java Question Bank Unit 2 (1)

The document is a Java question bank covering various topics such as inheritance, interfaces, abstract classes, method overloading, and more. It includes explanations, differences between concepts, and example programs for each topic. Key concepts include the use of the 'super' keyword, the 'final' keyword, packages, static members, constructors, and type casting.

Uploaded by

Inika Dey
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)
10 views16 pages

Java Question Bank Unit 2 (1)

The document is a Java question bank covering various topics such as inheritance, interfaces, abstract classes, method overloading, and more. It includes explanations, differences between concepts, and example programs for each topic. Key concepts include the use of the 'super' keyword, the 'final' keyword, packages, static members, constructors, and type casting.

Uploaded by

Inika Dey
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/ 16

JAVA QUESTION BANK UNIT 2

✅ Q1. Explain the different types of inheritance in Java. Write a program to demonstrate the use
of the super keyword.

🔹 Types of Inheritance in Java:

1. Single Inheritance – One class inherits another.


2. Multilevel Inheritance – Class inherits a class that already inherited another.
3. Hierarchical Inheritance – Multiple classes inherit from one superclass.

🔸 Note: Java does not support multiple inheritance with classes (to avoid ambiguity), but it’s
possible with interfaces.

🔹 super Keyword:

 Used to access superclass members (variables or methods) or constructor.

✅ Example Program (Use of super):

class Animal {
String color = "Brown";

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

class Dog extends Animal {


String color = "Black";

void printColor() {
System.out.println(super.color); // Access parent color
}

void sound() {
super.sound(); // Call parent method
System.out.println("Dog barks");
}
}

public class TestSuper {


public static void main(String[] args) {
Dog d = new Dog();
d.printColor();
d.sound();
}
}
✅ Q2. What is an interface? Explain the difference between an abstract class and an interface.
Write a program to implement an interface.

🔹 Interface:

 A reference type in Java, like a class, but only abstract methods and constants.
 Implements 100% abstraction.
 Use interface keyword.

🔹 Differences:

Feature Interface Abstract Class


Keyword interface abstract class
Methods Only abstract (until Java 8) Can have abstract & concrete
Multiple Inheritance Supported Not supported
Constructor Not allowed Allowed

✅ Example Program (Interface):

interface Printable {
void print();
}

class Document implements Printable {


public void print() {
System.out.println("Printing document...");
}
}

public class TestInterface {


public static void main(String[] args) {
Printable p = new Document();
p.print();
}
}

✅ Q3. Write a Java program to demonstrate the use of an abstract class.

🔹 Abstract Class:

 Declared using abstract keyword.


 Can have both abstract (no body) and concrete (with body) methods.
 Cannot be instantiated directly.

✅ Example:

abstract class Shape {


abstract void draw(); // Abstract method
void display() {
System.out.println("Displaying shape");
}
}

class Circle extends Shape {


void draw() {
System.out.println("Drawing a Circle");
}
}

public class TestAbstract {


public static void main(String[] args) {
Shape s = new Circle(); // Polymorphism
s.draw();
s.display();
}
}

✅ Q4. Explain the instanceof operator in Java.

🔹 instanceof:

 A binary operator used to check whether an object is an instance of a specific class or


subclass.

✅ Syntax:

object instanceof ClassName

✅ Example:

class Animal {}
class Dog extends Animal {}

public class TestInstanceOf {


public static void main(String[] args) {
Dog d = new Dog();
System.out.println(d instanceof Animal); // true
System.out.println(d instanceof Dog); // true
}
}

✅ Output:

true
true
✅ Q5. What is the use of the final keyword in Java?

🔹 final keyword:

Used to restrict modification. It can be applied to:

1. Final Variable: Value cannot be changed (constant).

final int x = 10;

2. Final Method: Cannot be overridden by subclasses.

final void display() {}

3. Final Class: Cannot be inherited.

final class Vehicle {}

✅ Example:

final class Vehicle {


final void run() {
System.out.println("Vehicle is running");
}
}

public class TestFinal {


public static void main(String[] args) {
Vehicle v = new Vehicle();
v.run();
}
}

✅ Q6. What is a package in Java? How to create a user-defined package in Java with an example.

🔹 What is a Package?

A package in Java is a namespace that organizes a set of related classes and interfaces. Think of it as
a folder in your file system.

Benefits:

 Avoids name conflicts.


 Easier to maintain code.
 Provides access protection.
 Packages can be imported and reused.

🔹 Types of Packages:

1. Built-in packages: e.g., java.util, java.io.


2. User-defined packages: Created by programmers to structure their own classes.

🔹 Creating a User-Defined Package:

Step 1: Create the package and a class inside it

// File: mypack/Message.java
package mypack;

public class Message {


public void display() {
System.out.println("Hello from the user-defined package!");
}
}

Step 2: Use the package in another class

// File: Test.java
import mypack.Message;

public class Test {


public static void main(String[] args) {
Message m = new Message();
m.display();
}
}

Compilation & Run:

javac -d . Message.java // Creates directory structure


javac Test.java
java Test

✅ Q7. What is method overloading? Explain with an example.

🔹 Method Overloading:

Method overloading means having more than one method with the same name in a class, but with
different parameter types, order, or number.

It’s an example of compile-time (static) polymorphism.

🔹 Rules:

 Methods must differ in parameter list.


 Return type may be different but cannot be the only differentiator.

✅ Example:
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;
}
}

public class Test {


public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(2, 3)); // 5
System.out.println(calc.add(1.5, 2.5)); // 4.0
System.out.println(calc.add(1, 2, 3)); // 6
}
}

✅ Q8. What is the use of the static keyword in Java?

🔹 The static keyword:

Used to define class-level members (variables, methods, blocks, or nested classes) that are shared
across all instances of the class.

🔹 Uses of static:

1. Static variable – Shared by all objects of a class.


2. Static method – Can be called without creating an object.
3. Static block – Used for static initialization.
4. Static class – A nested class that doesn’t require an outer class instance.

✅ Example:

class Counter {
static int count = 0; // static variable

Counter() {
count++;
System.out.println(count);
}

static void showCount() {


System.out.println("Total objects: " + count);
}
}

public class Test {


public static void main(String[] args) {
new Counter(); // 1
new Counter(); // 2
Counter.showCount(); // Access static method
}
}

✅ Q9. How is the constructor overloaded in Java?

🔹 Constructor Overloading:

Just like method overloading, you can have multiple constructors with different parameter lists in
the same class. This helps in initializing objects in different ways.

✅ Example:

class Student {
String name;
int age;

// Default constructor
Student() {
name = "Unknown";
age = 0;
}

// Parameterized constructor
Student(String n, int a) {
name = n;
age = a;
}

void display() {
System.out.println(name + " is " + age + " years old.");
}
}

public class Test {


public static void main(String[] args) {
Student s1 = new Student(); // Uses default constructor
Student s2 = new Student("Ravi", 20); // Uses parameterized constructor
s1.display();
s2.display();
}
}
✅ Q10. What is the purpose of implementing an interface in Java? How is it different from an
abstract class?

🔹 Purpose of Interface:

 To define a contract or capability that a class must implement (like Runnable, Comparable).
 Promotes loose coupling and multiple inheritance (since a class can implement multiple
interfaces).

✅ Example:

interface Drawable {
void draw();
}

class Circle implements Drawable {


public void draw() {
System.out.println("Drawing a Circle");
}
}

🔹 Interface vs Abstract Class:

Feature Interface Abstract Class


Keyword interface abstract class
Methods Only abstract (till Java 7) Abstract + concrete methods
Variables public static final only Instance and static variables
Inheritance Multiple allowed (via implements) Single inheritance only
Constructor Not allowed Allowed
Default behavior Cannot provide method body (Java 7) Can provide concrete methods

✅ Q11. Explain the concept of multilevel inheritance in Java. How is it implemented?

🔹 Multilevel Inheritance:

It refers to a class inheriting from a class that itself inherits from another class, forming a hierarchy.

Class A → Class B → Class C

✅ Example:

class Animal {
void eat() {
System.out.println("Eating...");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Barking...");
}
}

class Puppy extends Dog {


void weep() {
System.out.println("Weeping...");
}
}

public class Test {


public static void main(String[] args) {
Puppy p = new Puppy();
p.eat(); // inherited from Animal
p.bark(); // inherited from Dog
p.weep(); // own method
}
}

✅ Q12. (a) What is a constructor in Java? Explain its significance.

🔹 Constructor:

A constructor is a special method that is automatically called when an object is created. It has the
same name as the class and no return type.

🔹 Significance:

 Initializes objects.
 Can be overloaded to initialize differently.
 No need to call it explicitly.

✅ Q12 (b) Program to demonstrate Method Overloading:

class Display {
void show(String name) {
System.out.println("Name: " + name);
}

void show(int age) {


System.out.println("Age: " + age);
}
}

public class Test {


public static void main(String[] args) {
Display d = new Display();
d.show("Ravi");
d.show(20);
}
}

✅ Q13. What is constructor? Write a program to pass a value to the base class constructor from
subclass constructor.

🔹 Concept:

We use super() to call the constructor of the base class from the subclass.

✅ Example:

class Person {
String name;
Person(String n) {
name = n;
System.out.println("Person Constructor: " + name);
}
}

class Student extends Person {


Student(String n) {
super(n); // call parent constructor
System.out.println("Student Constructor");
}
}

public class Test {


public static void main(String[] args) {
Student s = new Student("Alice");
}
}

✅ Q14. What is static variable?

🔹 Static Variable:

A variable declared with the static keyword belongs to the class, not individual objects.

✅ Features:

 Shared among all instances.


 Initialized only once.

class Counter {
static int count = 0; // static variable
Counter() {
count++;
System.out.println(count);
}
}

✅ Q15. Write short notes on static method.

🔹 Static Method:

 Belongs to the class, not objects.


 Can be called without creating an object.
 Cannot use non-static variables directly.

✅ Example:

class MathUtil {
static int square(int n) {
return n * n;
}
}

public class Test {


public static void main(String[] args) {
System.out.println(MathUtil.square(5)); // 25
}
}

✅ Q16. What is a String? Explain all String methods with an example.

🔹 String:

A sequence of characters. In Java, strings are objects of the String class and are immutable.

✅ Common String Methods:

Method Description
length() Returns string length
charAt(int index) Returns character at specified index
substring() Extracts a substring
concat() Combines two strings
equals() Compares content of two strings
compareTo() Lexicographic comparison
toLowerCase() Converts to lowercase
toUpperCase() Converts to uppercase
Method Description
trim() Removes leading and trailing spaces
replace() Replaces characters

✅ Example:

public class Test {


public static void main(String[] args) {
String s = " Hello Java ";
System.out.println("Length: " + s.length());
System.out.println("Char at 1: " + s.charAt(1));
System.out.println("Substring: " + s.substring(2, 7));
System.out.println("Concat: " + s.concat(" World"));
System.out.println("Lowercase: " + s.toLowerCase());
System.out.println("Trimmed: " + s.trim());
System.out.println("Replace: " + s.replace("Java", "World"));
}
}

✅ Q17. Distinguish between Method Overriding and Method Overloading

Feature Method Overloading Method Overriding


Same method name, different Same method name & signature in
Definition
parameters subclass
Happens across superclass and
Class Relation Happens in the same class
subclass
Inheritance
No Yes
Required
Polymorphism Compile-time Runtime
Return Type Can be same or different Must be same (or covariant)

✅ Example of Overriding:

class Animal {
void sound() {
System.out.println("Animal Sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Bark");
}
}

✅ Example of Overloading:
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}

✅ Q18. What is type casting? Illustrate with example. What is meant by automatic type
promotion?

🔹 Type Casting:

Converting one data type into another is called type casting.

1. Widening/Implicit Casting (no data loss):

Automatically done by the compiler (smaller → larger type).

int a = 10;
double b = a; // int to double
2. Narrowing/Explicit Casting (possible data loss):

Done manually by the programmer.

double a = 10.5;
int b = (int) a; // double to int

🔹 Automatic Type Promotion:

In expressions, smaller types are promoted to larger types automatically.

✅ Example:
public class Demo {
public static void main(String[] args) {
byte b = 10;
int i = b + 20; // byte promoted to int
System.out.println(i);
}
}

✅ Q19. Write a Java program to sort the given names into ascending order using array.

import java.util.Arrays;

public class SortNames {


public static void main(String[] args) {
String[] names = {"Zara", "Amit", "John", "Rita"};

Arrays.sort(names); // Built-in sorting

System.out.println("Sorted Names:");
for (String name : names) {
System.out.println(name);
}
}
}

✅ Q20. How is a multidimensional array represented in Java? Write code to create a 2×2 array.

🔹 Multidimensional Array:

Java supports arrays of arrays (like a matrix).

✅ Example:
public class Matrix {
public static void main(String[] args) {
int[][] arr = new int[2][2]; // 2x2 array

arr[0][0] = 1;
arr[0][1] = 2;
arr[1][0] = 3;
arr[1][1] = 4;

for (int i = 0; i < 2; i++) {


for (int j = 0; j < 2; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}

✅ Q21. Illustrate Generic class with an example.

🔹 Generics:

They allow you to write type-safe code by working with different data types using a single class.

✅ Example:
class Box<T> {
T value;

void setValue(T value) {


this.value = value;
}

T getValue() {
return value;
}
}

public class GenericExample {


public static void main(String[] args) {
Box<String> strBox = new Box<>();
strBox.setValue("Hello");
System.out.println(strBox.getValue());

Box<Integer> intBox = new Box<>();


intBox.setValue(100);
System.out.println(intBox.getValue());
}
}

✅ Q22. Explain why the main function is declared as public static void main(String[] args).

🔹 Explanation:

 **public** – So JVM can access it from outside the class.


 **static** – JVM doesn't need to create an object to call it.
 **void** – It doesn't return any value.
 **main** – This is the entry point of any Java program.
 **String[] args** – It accepts command-line arguments.

✅ Example:
public class Test {
public static void main(String[] args) {
System.out.println("Hello Java!");
}
}

✅ Q23. Explain different access modifiers available in Java.

🔹 1. public

 Accessible from anywhere.

public int a;

🔹 2. private

 Accessible only within the same class.

private int a;

🔹 3. protected

 Accessible within the same package and in subclasses (even in different packages).
protected int a;

🔹 4. default (no modifier)

 Accessible within the same package only.

int a; // default access


Modifier Same Class Same Package Subclass Outside Package

public ✅ ✅ ✅ ✅

protected ✅ ✅ ✅ ❌ (unless subclass)

default ✅ ✅ ❌ ❌

private ✅ ❌ ❌ ❌

✅ Q24. How is dynamic binding implemented in Java?

🔹 Dynamic Binding (Late Binding):

 Occurs at runtime.
 Used when a method is overridden in a subclass.
 JVM decides which method to call based on actual object type, not reference type.

✅ Example:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Bark");
}
}

public class Test {


public static void main(String[] args) {
Animal obj = new Dog(); // Upcasting
obj.sound(); // Bark → determined at runtime
}
}

You might also like