Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
23 views34 pages

MOD 3 and 4

The document outlines Java OOP concepts through a series of 2-mark and 5-mark questions and answers. Key topics include method overloading and overriding, the significance of interfaces and abstract classes, string manipulation, and the use of keywords like 'this', 'super', and 'final'. It also discusses polymorphism, constructor overloading, and the differences between abstract classes and interfaces.

Uploaded by

srbeatz04
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)
23 views34 pages

MOD 3 and 4

The document outlines Java OOP concepts through a series of 2-mark and 5-mark questions and answers. Key topics include method overloading and overriding, the significance of interfaces and abstract classes, string manipulation, and the use of keywords like 'this', 'super', and 'final'. It also discusses polymorphism, constructor overloading, and the differences between abstract classes and interfaces.

Uploaded by

srbeatz04
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/ 34

Java OOP Concepts Summary

2 Marks Questions
REFERENCE: STUDY MATRERIAL
1) What are the different ways to implement method overloading?
2) Compare and contrast overloading and overriding methods.
3) Explain the significance of using Interface.
4) Explain the purpose of abstract classes and how they differ from concrete classes.
5) Discuss the role of abstract methods in abstract classes and how they are implemented in
concrete subclasses.
6) Discuss the role of the @Override annotation in method overriding.
7) Describe the concept of strings in object-oriented programming (OOP) and explain how they are
represented as objects.
8) Explain String Tokenizer with an example.
9) Explain the need for StringEquals function in java with suitable example.
10) Explain the term immutable String in java with suitable example.
11) Can you call one constructor from another if a class has multiple constructors?
12) Explain the syntax of BufferedReader object creation.
13) Can we override a method by using the same method name and arguments but different return
types?
14) Explain the syntax of BufferedReader object creation.
15) Can we override a method by using the same method name and arguments but different return
types?
16) In a class implementing an interface, can we change the value of any variable defined in the
interface?17) Can we make constructors static?
18) Can we use this() and super() both in a same constructor?
19) Distinguish between private and protected access modifier with suitable examples.
20) Explain var-args array.
21) Write down the significance of static keyword.
22) Distinguish the use of extends and implements.
23) What happens if the constructors are defined as private?
24) If two interfaces contain method with same signature and what happen if a class inherits both?
25) Is it possible to override super-class constructor? Why?
26) Explain "Is-A" relationship in inheritance.
27) Explain "HAS-A" relationship in inheritance.
28) What is method overriding and how does it differ from method overloading in Java?
29) When can a method in super class be prevented from being overridden by a method in subclass?
30) Can we declare the static variables and methods in an abstract class?

Here are the 2-mark answers based on your study material reference:

1) What are the different ways to implement method overloading?

By changing the number of parameters.

By changing the type of parameters.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/34
By changing the order of parameters (if they are of different types).

2) Compare and contrast overloading and overriding methods.

Overloading is compile-time polymorphism; same method name with different parameters.

Overriding is runtime polymorphism; same method name, parameters, and return type in
subclass.

3) Explain the significance of using Interface.


Interfaces provide abstraction, support multiple inheritance, and define a contract for implementing
classes to follow.

4) Explain the purpose of abstract classes and how they differ from concrete classes.
Abstract classes can't be instantiated and may contain abstract methods. Concrete classes are fully
implemented and can be instantiated.

5) Discuss the role of abstract methods in abstract classes and how they are implemented in
concrete subclasses.
Abstract methods define a method without implementation. Subclasses must provide the method body
(implementation).

6) Discuss the role of the @Override annotation in method overriding.


It indicates that a method is intended to override a method in a superclass, helping catch errors during
compilation.

7) Describe the concept of strings in object-oriented programming (OOP) and explain how they are
represented as objects.
In Java, strings are instances of the `String` class and are immutable. They are objects with built-in
methods for manipulation.

8) Explain String Tokenizer with an example.


`StringTokenizer` breaks a string into tokens:

java

`StringTokenizer st = new StringTokenizer("Hello World");


while(st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
`

9) Explain the need for StringEquals function in java with suitable example.
`equals()` compares contents of strings, unlike `==` which compares references.

java

`String a = "Hello";
String b = new String("Hello");
System.out.println(a.equals(b)); // true
`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/34
10) Explain the term immutable String in java with suitable example.
Once created, a `String` object cannot be changed.

java

`String s = "Hello";
s.concat("World");
System.out.println(s); // prints "Hello"
`

11) Can you call one constructor from another if a class has multiple constructors?
Yes, using `this()` to call another constructor from the same class.

12) Explain the syntax of BufferedReader object creation.

java

`BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


`

13) Can we override a method by using the same method name and arguments but different
return types?
No, overriding requires the same return type or a subtype (covariant return type).

14) (Duplicate of 12)


Syntax of BufferedReader object creation:

java

`BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


`

15) (Duplicate of 13)


Overriding with same name/arguments but different return type is not allowed.

16) In a class implementing an interface, can we change the value of any variable defined in the
interface?
No. Variables in interfaces are implicitly `public static final` and cannot be changed.

17) Can we make constructors static?


No. Constructors are used to initialize objects and can't be static.

18) Can we use this() and super() both in a same constructor?


No. Only one of them can be the first statement in a constructor.

19) Distinguish between private and protected access modifier with suitable examples.

`private`: accessible within the same class.


`protected`: accessible in same package and subclasses.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/34
20) Explain var-args array.
Var-args allow passing variable number of arguments:

java

`void show(int... nums) { }


`

21) Write down the significance of static keyword.


`static` makes a variable or method belong to the class rather than instances.

22) Distinguish the use of extends and implements.

`extends`: used for class-to-class and interface-to-interface inheritance.

`implements`: used when a class inherits an interface.

23) What happens if the constructors are defined as private?


They prevent object creation from outside the class, used in Singleton patterns.

24) If two interfaces contain method with same signature and what happen if a class inherits
both?
The class provides a single implementation, no conflict occurs if method signature is same.

25) Is it possible to override super-class constructor? Why?


No. Constructors are not inherited, so they can't be overridden.

26) Explain "Is-A" relationship in inheritance.


Indicates inheritance: e.g., Dog is-a Animal.

27) Explain "HAS-A" relationship in inheritance.


Represents composition: e.g., Car has-a Engine.

28) What is method overriding and how does it differ from method overloading in Java?

Overriding: same signature, different class (subclass).


Overloading: same method name, different parameters in same class.

29) When can a method in super class be prevented from being overridden by a method in
subclass?
By declaring it as `final`, `private`, or `static`.

30) Can we declare the static variables and methods in an abstract class?
Yes. Abstract classes can have static members.

Let me know if you want this in a printable format or explained with diagrams/examples.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/34
5 Marks Questions
REFERENCE: STUDY MATRERIAL
1) Demonstrate constructor overloading with a suitable example.
2) Demonstrate the application of the super keyword in conjunction with a method in Java.
3) Design a Java program that illustrates the concept of static variables by showcasing their unique
property of allocating memory only once throughout the execution of the program.
4) Evaluate the role of abstract classes in Java inheritance. Analyse the advantages and limitations of
using abstract classes compared to interfaces in object-oriented design.
5) Discuss the concept of interface inheritance in Java. Explain how interfaces can extend other
interfaces and inherit methods and constants from parent interfaces. Provide examples to illustrate
interface inheritance and discuss its advantages.
6) Implement a java code to check if the String contains 'e' in umbrella.
7) Develop a java code to examine whether interfaces can be extended in Java.
8) Explain yield() and join() with proper code snippet.
9) Demonstrate different types of polymorphism with a suitable example.
10) How does the abstract class differ from the interface? Discuss with program.
11) Write down the differences between this, super, and final keywords.
12) Develop a Java Program to create an abstract class named Shape that contains two integers and
an empty method named printArea(). Provide three classes named Rectangle, Triangle and Circle
such that each one of the classes extends the class Shape. Each one of the classes contains only the
method printArea () that prints the area of the given shape.
13) What happens if any value is not assigned to a final and static variable during declaration?
Explain and provide a solution with a program.
14) Write down the advantages and disadvantages of Object Cloning.
15) Is it possible to use the keyword super within a static method? Give justification for your answer.

Here are the 5-mark answers based on your study material reference:

1) Demonstrate constructor overloading with a suitable example.


Constructor overloading means defining multiple constructors with different parameter lists.

java

`class Student {
String name;
int age;

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

Student(String n) {
name = n;
age = 0;
}

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

void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

public class Main {

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/34
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Alice");
Student s3 = new Student("Bob", 22);
s1.display();
s2.display();
s3.display();
}
}
`

2) Demonstrate the application of the super keyword in conjunction with a method in Java.

java

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

class Dog extends Animal {


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

public class Test {


public static void main(String[] args) {
Dog d = new Dog();
d.sound();
}
}
`

3) Static variable memory allocation demonstration

java

`class Counter {
static int count = 0;

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

public class StaticDemo {


public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
}
}
`

`static` variable `count` is shared across all objects and memory is allocated only once.

4) Evaluate the role of abstract classes in Java inheritance


Advantages:

Code reusability.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/34
Allows partial abstraction.

Can define constructors and static methods.

Limitations:

Java does not support multiple inheritance with classes.

Cannot enforce full abstraction like interfaces.

Example:

java

`abstract class Animal {


abstract void sound();
void eat() {
System.out.println("This animal eats food.");
}
}

class Cat extends Animal {


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

5) Interface inheritance in Java


Interfaces can extend other interfaces using `extends`.

java

`interface A {
void methodA();
}

interface B extends A {
void methodB();
}

class MyClass implements B {


public void methodA() {
System.out.println("Method A");
}

public void methodB() {


System.out.println("Method B");
}
}
`

Advantages:

Supports multiple inheritance.

Promotes abstraction.

Used for defining contracts across unrelated classes.

6) Java code to check if 'umbrella' contains 'e'

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/34
java

`public class CheckCharacter {


public static void main(String[] args) {
String s = "umbrella";
if (s.contains("e")) {
System.out.println("'e' is present.");
} else {
System.out.println("'e' is not present.");
}
}
}
`

7) Examine whether interfaces can be extended in Java

java

`interface A {
void methodA();
}

interface B extends A {
void methodB();
}

class Demo implements B {


public void methodA() {
System.out.println("A's method");
}

public void methodB() {


System.out.println("B's method");
}

public static void main(String[] args) {


Demo obj = new Demo();
obj.methodA();
obj.methodB();
}
}
`

8) Explain yield() and join()

java

`class MyThread extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Child Thread");
Thread.yield(); // Hint to pause and allow other threads
}
}
}

public class JoinYieldDemo {


public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
t.start();
t.join(); // Waits for thread t to finish
for (int i = 1; i <= 5; i++) {
System.out.println("Main Thread");
}
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/34
}
`

9) Demonstrate different types of polymorphism

Compile-time polymorphism (Method Overloading)

Run-time polymorphism (Method Overriding)

java

`class PolymorphismExample {
void show(int a) {
System.out.println("int: " + a);
}

void show(double a) {
System.out.println("double: " + a);
}
}

class A {
void display() {
System.out.println("Class A");
}
}

class B extends A {
void display() {
System.out.println("Class B");
}
}
`

10) Abstract class vs Interface with program


Differences:

Abstract class can have constructors; interface cannot.

Interface methods are implicitly abstract and public.

java

`abstract class Animal {


abstract void sound();
}

interface Flyable {
void fly();
}

class Bird extends Animal implements Flyable {


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

public void fly() {


System.out.println("Bird flies");
}
}
`

11) Difference between this, super, and final

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/34
`this`: Refers to current object.

`super`: Refers to parent class.


`final`: Prevents method or class from being modified or overridden.

java

`class Parent {
final void show() {}
}

class Child extends Parent {


void display() {
System.out.println(this);
super.show();
}
}
`

12) Abstract Shape program

java

`abstract class Shape {


int a, b;
abstract void printArea();
}

class Rectangle extends Shape {


Rectangle(int x, int y) { a = x; b = y; }
void printArea() {
System.out.println("Rectangle: " + (a * b));
}
}

class Triangle extends Shape {


Triangle(int x, int y) { a = x; b = y; }
void printArea() {
System.out.println("Triangle: " + (0.5 * a * b));
}
}

class Circle extends Shape {


Circle(int r) { a = r; }
void printArea() {
System.out.println("Circle: " + (3.14 * a * a));
}
}
`

13) What happens if final static variable is not initialized?


Compilation error. It must be initialized during declaration or in a static block.

java

`class Example {
static final int VALUE;
static {
VALUE = 100;
}
}
`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/34
14) Advantages and Disadvantages of Object Cloning

Advantages:

Avoids reinitializing an object.


Performs deep or shallow copy as needed.

Disadvantages:

Requires implementing `Cloneable`.

Can lead to shallow copy issues if not handled.

15) Can we use the keyword super within a static method?

No. `super` refers to instance of the parent class, and static methods are class-level, so no instance
context is available.

Let me know if you want a PDF export or formatted version of these for printing!

10 Marks Questions
REFERENCE: STUDY MATRERIAL
1) Discuss the difference between start() and run() methods by demonstrating through a
Multithreaded Java program. Justify your observations.
2) Design an abstract class shape having two methods calculate_area() and display(). Create
rectangle, triangle, and ellipse classes by inheriting the shape class and overriding the above
methods to suitably implement rectangle, triangle, and ellipse classes.
3) Evaluate the design of a banking application in Java that uses abstract classes and interfaces to
model various account types. Analyse the role of abstract classes in providing common behaviour
among account types and interfaces in defining a contract for account operations.
4) Generate a class where a Company manufactures Vehicles, which could be a Helicopter, a Car, or
a Train depending on the customer’s demand. Each Vehicle instance has a method called move,
which prints on the console the nature of movement of the vehicle. For example, the Helicopter Flies
in Air, the Car Drives on Road and the Train Runs on Track. Write a program that accepts input from
the user on the kind of vehicle the user wants to order, and the system should print out nature of
movement. Implement all Java coding best practices to implement this program.
5) Develop a java code to create Thread by implementing the Runnable interface. Write a java
program to implement the yield( ) method in thread programming.
6) Design a Java program to display the car no., model, colour and price of a car using class and
object concept.(use Scanner class).
7) What is array of objects? Describe the use of Access Modifiers in Java? Draw a table showing the
scope of accessibility? Justify: I. Why we declare main () method as public and static member. II. Why
we generally declare constructor as public member. III. Why there is no destructor in java.
8) Differentiate between abstract class and Interface. The abstract Vegetable class has three
subclasses named Potato, Brinjal and Tomato. Write an application that demonstrates how to
establish this class hierarchy. Declare one instance variable of type String that indicates the colour
of a vegetable. Create and display instances of these objects. Override the toString() method of
Object to return a string with the name of the vegetable and its colour.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/34
Here are the 10-mark answers based on your study material reference:

1) Difference between `start()` and `run()` methods in a multithreaded Java


program

`start()` creates a new thread and calls `run()` in that thread.


`run()` does not start a new thread; it executes in the current thread.

Example:

java

`class MyThread extends Thread {


public void run() {
System.out.println("Run method executed by: " + Thread.currentThread().getName());
}

public static void main(String[] args) {


MyThread t1 = new MyThread();

t1.start(); // Creates new thread


t1.run(); // Runs in main thread

System.out.println("Main method executed by: " + Thread.currentThread().getName());


}
}
`

Justification:

`start()` invokes a new thread; `run()` does not.


Output confirms which thread is executing each method.

2) Abstract class Shape with Rectangle, Triangle, and Ellipse

java

`abstract class Shape {


abstract void calculate_area();
abstract void display();
}

class Rectangle extends Shape {


int length = 5, breadth = 3;
double area;

void calculate_area() {
area = length * breadth;
}

void display() {
System.out.println("Rectangle Area: " + area);
}
}

class Triangle extends Shape {


int base = 4, height = 6;
double area;

void calculate_area() {
area = 0.5 * base * height;

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/34
}

void display() {
System.out.println("Triangle Area: " + area);
}
}

class Ellipse extends Shape {


int a = 7, b = 3;
double area;

void calculate_area() {
area = 3.14 * a * b;
}

void display() {
System.out.println("Ellipse Area: " + area);
}
}

public class TestShape {


public static void main(String[] args) {
Shape s1 = new Rectangle();
s1.calculate_area();
s1.display();

Shape s2 = new Triangle();


s2.calculate_area();
s2.display();

Shape s3 = new Ellipse();


s3.calculate_area();
s3.display();
}
}
`

3) Banking application using abstract class and interface

java

`interface Transaction {
void deposit(double amount);
void withdraw(double amount);
}

abstract class Account implements Transaction {


protected double balance = 0;
protected String accountNumber;

public Account(String accNo) {


accountNumber = accNo;
}

public void displayBalance() {


System.out.println("Account: " + accountNumber + ", Balance: " + balance);
}
}

class SavingsAccount extends Account {


public SavingsAccount(String accNo) {
super(accNo);
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) {


if (balance >= amount)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/34
balance -= amount;
else
System.out.println("Insufficient Balance");
}
}

public class BankApp {


public static void main(String[] args) {
Account acc = new SavingsAccount("SA123");
acc.deposit(1000);
acc.withdraw(500);
acc.displayBalance();
}
}
`

Analysis:

Abstract class provides shared code (e.g., balance).


Interface enforces required actions (deposit, withdraw).

Promotes reusability and modularity.

4) Company manufactures Vehicles — move method

java

`import java.util.Scanner;

abstract class Vehicle {


abstract void move();
}

class Helicopter extends Vehicle {


void move() {
System.out.println("Helicopter Flies in Air");
}
}

class Car extends Vehicle {


void move() {
System.out.println("Car Drives on Road");
}
}

class Train extends Vehicle {


void move() {
System.out.println("Train Runs on Track");
}
}

public class VehicleFactory {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the type of vehicle (Helicopter, Car, Train): ");
String type = sc.nextLine().trim().toLowerCase();
Vehicle v;

switch (type) {
case "helicopter": v = new Helicopter(); break;
case "car": v = new Car(); break;
case "train": v = new Train(); break;
default:
System.out.println("Invalid type");
return;
}
v.move();
sc.close();

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/34
}
}
`

5) Create thread using Runnable & yield() method

java

`class MyRunnable implements Runnable {


public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(Thread.currentThread().getName() + " is running");
Thread.yield(); // Hint to pause execution
}
}
}

public class RunnableDemo {


public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(), "Thread-1");
Thread t2 = new Thread(new MyRunnable(), "Thread-2");
t1.start();
t2.start();
}
}
`

6) Car class using Scanner

java

`import java.util.Scanner;

class Car {
String carNo, model, color;
double price;

void inputDetails() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Car No: ");
carNo = sc.nextLine();
System.out.print("Enter Model: ");
model = sc.nextLine();
System.out.print("Enter Colour: ");
color = sc.nextLine();
System.out.print("Enter Price: ");
price = sc.nextDouble();
}

void display() {
System.out.println("Car No: " + carNo + ", Model: " + model + ", Colour: " + color + ", Pric
}
}

public class CarDetails {


public static void main(String[] args) {
Car c = new Car();
c.inputDetails();
c.display();
}
}
`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/34
7) Array of Objects & Access Modifiers

Array of objects:

java

`class Student {
String name;
Student(String n) { name = n; }
}

Student[] arr = new Student[3];


arr[0] = new Student("John");
`

Access Modifiers Table:

Modifier Class Package Subclass World


public ✔ ✔ ✔ ✔
protected ✔ ✔ ✔ ✖
default ✔ ✔ ✖ ✖
private ✔ ✖ ✖ ✖
Justify:

`main()` is public and static so JVM can call it without an object.


Constructors are public to allow object creation.

Java uses Garbage Collector, hence no destructor needed.

8) Abstract class vs Interface with Vegetable hierarchy

java

`abstract class Vegetable {


String color;
Vegetable(String color) {
this.color = color;
}

public abstract String getName();

public String toString() {


return getName() + " is " + color;
}
}

class Potato extends Vegetable {


Potato(String color) { super(color); }
public String getName() { return "Potato"; }
}

class Brinjal extends Vegetable {


Brinjal(String color) { super(color); }
public String getName() { return "Brinjal"; }
}

class Tomato extends Vegetable {


Tomato(String color) { super(color); }
public String getName() { return "Tomato"; }
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/34
public class VegDemo {
public static void main(String[] args) {
Vegetable v1 = new Potato("Brown");
Vegetable v2 = new Brinjal("Purple");
Vegetable v3 = new Tomato("Red");

System.out.println(v1);
System.out.println(v2);
System.out.println(v3);
}
}
`

Let me know if you'd like diagrams, formatted notes, or a PDF for easy study!

2 Marks Questions REFERENCE: STUDY MATRERIAL


1) What are the different types of exceptions?
2) Compare between “extends Thread” and “implements Runnable” options.
3) Describe the concept of thread scheduling in Java.
4) What is the main advantage of using threads in Java applications?
5) What is a thread in Java?
6) Examine the purpose of Static methods and static variables.
7) What is thread based multitsking?
8) What is process based multitasking ?
9) Write down the difference between Concat method and + operator to join strings?
10) In multi-threading how can we ensure that a resource isn‟t used by multiple threads
simultaneously?
11) Distinguish between private and protected access modifier with suitable examples.
12) What is default exception handler?
13) Distinguish between throw and throws.
14) What happens if matching exception type is not found in catch blocks? Explain.
15) Discuss the use of join() in multithread programming.
16) Write a statement that moves a thread to blocked-state.
17) Write a program where one interface inherits another one.
18) Compare Garbage collection and finalize method
19) Write a program where one interface inherits another one.
20) Write a statement that moves a thread to blocked-state.

Here are the 2 Marks Java Questions with concise answers based on your study material reference:

1) What are the different types of exceptions?

Checked Exceptions: Checked at compile time (e.g., `IOException`, `SQLException`)


Unchecked Exceptions: Checked at runtime (e.g., `NullPointerException`, `ArithmeticException`)
Errors: Serious problems (e.g., `OutOfMemoryError`)

2) Compare “extends Thread” and “implements Runnable”:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/34
Criteria extends Thread implements Runnable
Inheritance Can't extend other class Can extend other classes
Flexibility Less flexible More flexible (favors OOP)

Recommended Less recommended More recommended

3) Describe the concept of thread scheduling in Java.

Thread scheduling determines the execution order of threads based on priority and CPU availability,
managed by the JVM thread scheduler (usually preemptive or time-slicing).

4) What is the main advantage of using threads in Java applications?

Threads enable concurrent execution, improving performance and responsiveness, especially in I/O-
bound and CPU-bound tasks.

5) What is a thread in Java?

A thread is a lightweight subprocess that runs concurrently within a program, allowing multitasking.

6) Examine the purpose of Static methods and static variables.

Static variable: Shared among all objects of a class.

Static method: Can be called without creating an object; often used for utility or helper methods.

7) What is thread-based multitasking?

Thread-based multitasking allows a single program to perform multiple tasks concurrently using
threads.

8) What is process-based multitasking?

Each program runs as a separate process, with its own memory and resources; the OS manages
multiple such processes simultaneously.

9) Difference between `concat()` method and `+` operator:

`+` Operator: Internally uses `StringBuilder`; more concise.

`concat()`: A method of the `String` class; only joins two strings.

10) How to ensure a resource isn’t used by multiple threads simultaneously?

Use synchronized blocks/methods to prevent race conditions.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/34
java

`synchronized(obj) {
// critical section
}
`

11) Private vs Protected with Example:

Private: Accessible only within the same class.


Protected: Accessible in the same package and subclasses.

java

`class A {
private int x = 5;
protected int y = 10;
}
`

12) What is default exception handler?

When an exception is unhandled, Java Runtime Environment (JRE) provides a default handler that
prints the exception name, description, and stack trace.

13) Difference between `throw` and `throws`:

`throw`: Used to explicitly throw an exception.

`throws`: Declares exception(s) a method might throw.

java

`throw new ArithmeticException();


void method() throws IOException {}
`

14) What if no matching catch block is found?

The default exception handler of the JVM is invoked, and the program terminates abruptly with an
error message.

15) Use of `join()` in multithreading:

The `join()` method waits for a thread to finish its execution before continuing.

java

`t1.join(); // Waits for thread t1 to die


`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/34
16) Statement to move a thread to blocked state:

java

`synchronized(obj) {
obj.wait(); // Causes thread to enter blocked/waiting state
}
`

17) Program: One interface inherits another

java

`interface A {
void display();
}

interface B extends A {
void show();
}
`

18) Compare Garbage Collection and `finalize()` method:

Garbage Collection: Automatic memory management.

`finalize()`: Method called before object is removed by GC (deprecated in recent versions).

19) Program: One interface inherits another (repetition)

java

`interface A {
void test();
}

interface B extends A {
void print();
}
`

20) Statement to move a thread to blocked-state (repetition):

java

`synchronized(obj) {
obj.wait(); // Moves thread to blocked/waiting state
}
`

Let me know if you'd like these in a formatted doc or PDF!

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/34
5 Marks Questions REFERENCE: STUDY MATRERIAL
1) Can we have multiple catch blocks for a single try block? Justify your answer with an example.
2) Implement a java program to remove all the repeated element from the ArrayList.
3) Differentiate between values() and valuesOf() in JAVA
4) Develop a java program to create a package and a subpackage then access the methods from
both.
5) Consider a scenario where two classes with same name are defined in two different packages.
How to access members of both from a same method. Write a program to support that.
6) Write a java program to create two threads, one for writing odd numbers and another for writing
even numbers up to 150 in two different files.
7) How polymorphism property can be achieved by constructors?
10 Marks Questions REFERENCE: STUDY MATRERIAL
1) Create a user-defined exception i.e. "LowBalanceException". Write the code to throw that
"LowBalanceException" if your savings account balance goes below 500 Rs. and arrange to handle
that "LowBalanceException". Also, write the output.
2) Develop a Java program that demonstrates the implementation of the Runnable interface to
create threads effectively.
3) Explain the concept of multithreading in Java. Provide a code example demonstrating the creation
and execution of multiple threads. Discuss the advantages of using multithreading in Java
applications.
4) Explain the role of interfaces in achieving multiple inheritance in Java. Discuss how interfaces
allow a class to implement multiple interfaces, thereby inheriting behaviors from multiple sources.
Provide examples to demonstrate the use of multiple interfaces in Java.
5) Create a parent class Computer with three child classes Laptop,TabletComputers and SmartPhone
justify with suitable code showing all Laptops ,TabletComputers and SmartPhones belongs to
Computer class.
6) Distinguish between the „throw‟ and „throws‟. Give proper codes. What happens precisely when
the code in the try block throws an exception?
7) Write a Java program that creates two threads. First thread displays Good Morning! in every one
second, and the second thread displays Hello! in every two seconds.
8) A)Explain about Thread Life Cycle.
B) Describe how to set the priority to threads. what are the different ranges?
9) Write a Java program that creates three threads. First thread generates a random positive
number (>1) every 2 second. If the number is even, the second thread prints all even numbers
between 1 and the generated number. If the number is odd, the third thread will print all odd
numbers between 1 and the generated number.
10) Discuss the working and meaning of the “static” modifier with example and explain static
variable and static methods with an example program. Java program is to be compiled first and then
to be interpreted for execution. True or false? Justify your answer.
11) Write a java program to show the use of throw, throws, try, catch and finally. Explain each.
12) What are the types of Exceptions in Java. What is the implication of catching all the exceptions
with the type “Exception”? Write a program to create a user defined exception to check correctness
of mobile number and also handle that using try, catch. For correctness of mobile number consider
length is 10 and that of numeric only. Take user input to validate that.
13) Name the superclass of all exception classes in Java. Build a Java program that simulates a
banking transaction. Use exception handling to ensure that the account balance is never negative
after a withdrawal.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/34
Awesome! You've got a solid collection of Java questions here, and it's great to see you're preparing
across all types—2, 5, and 10 marks. Do you want brief answers now for the 5-mark and 10-mark
questions like I did earlier, or would you prefer I create detailed Java programs and explanations for
specific ones? Just let me know which ones you’d like help with first!

semi detailed

Perfect! Here's a semi-detailed explanation for your 5-mark and 10-mark Java questions based on
your study material. I'll cover the first few from each section to keep it manageable—let me know if
you want more after this!

✅ 5 MARKS QUESTIONS
1) Can we have multiple catch blocks for a single try block? Justify your answer with an example.

Yes, Java allows multiple `catch` blocks for a single `try` block to handle different types of exceptions
separately.
Example:

java

`public class MultiCatchExample {


public static void main(String[] args) {
try {
int[] arr = new int[3];
arr[5] = 10; // ArrayIndexOutOfBoundsException
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception caught");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Exception caught");
}
}
}
`

2) Java program to remove all repeated elements from ArrayList

java

`import java.util.*;

public class RemoveDuplicates {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "apple", "orange"
Set<String> uniqueSet = new LinkedHashSet<>(list);
list.clear();
list.addAll(uniqueSet);
System.out.println("List after removing duplicates: " + list);
}
}
`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/34
3) Differentiate between `values()` and `valueOf()` in Java

Method Description
`values()` Returns an array of all enum constants.
`valueOf()` Returns enum constant with the specified name (throws exception if invalid).

Example:

java

`enum Color { RED, GREEN, BLUE }

Color[] colors = Color.values(); // All constants


Color green = Color.valueOf("GREEN"); // Specific constant
`

4) Java program to create package and subpackage

File structure:

markdown

`myPackage/
├── SubPackage/
└── SubClass.java
└── MainClass.java
`

SubClass.java:

java

`package myPackage.SubPackage;

public class SubClass {


public void display() {
System.out.println("Hello from SubPackage");
}
}
`

MainClass.java:

java

`package myPackage;

import myPackage.SubPackage.SubClass;

public class MainClass {


public static void main(String[] args) {
SubClass obj = new SubClass();
obj.display();
}
}
`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 23/34
Compile with:

swift

`javac myPackage/SubPackage/SubClass.java
javac myPackage/MainClass.java
`

✅ 10 MARKS QUESTIONS
1) User-defined Exception – LowBalanceException

java

`class LowBalanceException extends Exception {


public LowBalanceException(String msg) {
super(msg);
}
}

class Account {
private double balance = 1000;

public void withdraw(double amount) throws LowBalanceException {


if (balance - amount < 500)
throw new LowBalanceException("Low Balance! Minimum balance of Rs.500 required.");
else {
balance -= amount;
System.out.println("Withdraw successful. Balance: " + balance);
}
}
}

public class Bank {


public static void main(String[] args) {
Account acc = new Account();
try {
acc.withdraw(600);
} catch (LowBalanceException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
`

Output:

makefile

`Exception: Low Balance! Minimum balance of Rs.500 required.


`

2) Runnable Interface Thread Implementation

java

`class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread is running...");

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 24/34
}
}

public class RunnableExample {


public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
}
}
`

3) Concept of Multithreading + Example

Multithreading allows multiple threads to run concurrently, improving CPU utilization and
responsiveness.
Advantages:

Better resource utilization

Improved application responsiveness


Useful in games, UI, servers, etc.

Code Example:

java

`class Task1 extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Task 1 - Count: " + i);
}
}
}

class Task2 extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Task 2 - Count: " + i);
}
}
}

public class MultiThreadDemo {


public static void main(String[] args) {
Task1 t1 = new Task1();
Task2 t2 = new Task2();
t1.start();
t2.start();
}
}
`

Would you like me to continue with the rest of the questions? Or would you prefer a downloadable
version (like PDF or Word)?

continue

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 25/34
Great! Continuing with more 5-mark and 10-mark questions in semi-detailed format from your list.

✅ 5 MARKS QUESTIONS (Continued)


5) Two classes with same name in different packages – How to access both

Suppose we have:

`package1.ClassA`

`package2.ClassA`

Code Structure:
`package1/ClassA.java`

java

`package package1;
public class ClassA {
public void show() {
System.out.println("ClassA from package1");
}
}
`

`package2/ClassA.java`

java

`package package2;
public class ClassA {
public void show() {
System.out.println("ClassA from package2");
}
}
`

Main.java

java

`import package1.ClassA;

public class Main {


public static void main(String[] args) {
ClassA obj1 = new ClassA(); // from package1
obj1.show();

package2.ClassA obj2 = new package2.ClassA(); // fully qualified name


obj2.show();
}
}
`

6) Two threads: Odd & Even to different files

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 26/34
java

`import java.io.*;

class EvenThread extends Thread {


public void run() {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("even.txt"))) {
for (int i = 2; i <= 150; i += 2) {
bw.write(i + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

class OddThread extends Thread {


public void run() {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("odd.txt"))) {
for (int i = 1; i <= 150; i += 2) {
bw.write(i + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

public class ThreadToFile {


public static void main(String[] args) {
new EvenThread().start();
new OddThread().start();
}
}
`

7) How polymorphism can be achieved through constructors

Constructor overloading enables polymorphism:

java

`class Student {
String name;
int age;

Student(String n) {
name = n;
}

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

void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

public class ConstructorPolymorphism {


public static void main(String[] args) {
Student s1 = new Student("Alice");
Student s2 = new Student("Bob", 20);
s1.display();
s2.display();
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 27/34
}
`

✅ 10 MARKS QUESTIONS (Continued)


4) Multiple Inheritance using Interfaces in Java

java

`interface Printable {
void print();
}

interface Showable {
void show();
}

class A implements Printable, Showable {


public void print() {
System.out.println("Print method");
}

public void show() {


System.out.println("Show method");
}
}

public class MultipleInterfaceDemo {


public static void main(String[] args) {
A obj = new A();
obj.print();
obj.show();
}
}
`

Explanation:

Java doesn't support multiple inheritance using classes.


Using interfaces, we can implement multiple behaviors.

5) Class hierarchy: Computer → Laptop, TabletComputers, SmartPhone

java

`class Computer {
void specs() {
System.out.println("Generic Computer Specs");
}
}

class Laptop extends Computer {


void specs() {
System.out.println("Laptop: i7, 16GB RAM");
}
}

class TabletComputers extends Computer {


void specs() {
System.out.println("Tablet: Touchscreen, Portable");
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 28/34
}

class SmartPhone extends Computer {


void specs() {
System.out.println("SmartPhone: Android, 5G");
}
}

public class ComputerDemo {


public static void main(String[] args) {
Computer[] devices = {
new Laptop(),
new TabletComputers(),
new SmartPhone()
};

for (Computer c : devices) {


c.specs();
}
}
}
`

6) Difference between `throw` and `throws` + What happens in try block

Difference:

`throw` `throws`
Used to throw exception Declares exceptions that a method might throw
Followed by instance Followed by exception class name

Only one exception Can declare multiple exceptions

Example:

java

`class ThrowThrowsExample {
static void checkAge(int age) throws ArithmeticException {
if (age < 18)
throw new ArithmeticException("Not eligible to vote");
}

public static void main(String[] args) {


try {
checkAge(16);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("Voting check complete.");
}
}
}
`

Would you like me to continue with the next set (from question 7 onward in the 10-mark list), or would
you like the output as a document/PDF too?

continue

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 29/34
Perfect! Let’s continue with the next set of 10-mark questions in semi-detailed format:

✅ 10 MARKS QUESTIONS (Continued)


7) Two threads: “Good Morning!” every 1 sec, “Hello!” every 2 sec

java

`class MorningThread extends Thread {


public void run() {
try {
while (true) {
System.out.println("Good Morning!");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Morning Thread interrupted");
}
}
}

class HelloThread extends Thread {


public void run() {
try {
while (true) {
System.out.println("Hello!");
Thread.sleep(2000);
}
} catch (InterruptedException e) {
System.out.println("Hello Thread interrupted");
}
}
}

public class Greetings {


public static void main(String[] args) {
new MorningThread().start();
new HelloThread().start();
}
}
`

Explanation:

`sleep(milliseconds)` pauses the thread.


Demonstrates concurrent execution using multithreading.

8A) Thread Life Cycle

Phases:

1. New – Thread created but not started.


2. Runnable – Thread ready to run.
3. Running – Thread is executing.
4. Blocked/Waiting – Waiting for resource or signal.
5. Terminated – Thread execution completed.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 30/34
8B) Thread Priority in Java

java

`Thread t1 = new Thread();


t1.setPriority(Thread.MAX_PRIORITY); // 10
`

Range: 1 (MIN) to 10 (MAX), default is 5.


Use:

To hint JVM about order of execution. Not guaranteed but often respected.

9) Three threads: Random number, Even, Odd

java

`import java.util.Random;

class RandomGenerator extends Thread {


int number;

public void run() {


while (true) {
number = new Random().nextInt(100) + 2; // >1
System.out.println("Generated: " + number);
if (number % 2 == 0) {
new EvenPrinter(number).start();
} else {
new OddPrinter(number).start();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
}
}
}

class EvenPrinter extends Thread {


int limit;

EvenPrinter(int limit) {
this.limit = limit;
}

public void run() {


for (int i = 2; i <= limit; i += 2) {
System.out.print(i + " ");
}
System.out.println();
}
}

class OddPrinter extends Thread {


int limit;

OddPrinter(int limit) {
this.limit = limit;
}

public void run() {


for (int i = 1; i <= limit; i += 2) {
System.out.print(i + " ");
}
System.out.println();
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 31/34
}

public class MultiThreadRandom {


public static void main(String[] args) {
new RandomGenerator().start();
}
}
`

10) `static` keyword: variable & method + compilation-execution

Static Variable/Method Example:

java

`class StaticDemo {
static int count = 0;

static void displayCount() {


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

public static void main(String[] args) {


count++;
StaticDemo.displayCount();
}
}
`

Static variables: Shared among all instances.

Static methods: Can be called without an object.

True or False?

Java is compiled and then interpreted.


✅ True – Java code is compiled to bytecode (`.class` files), which is then interpreted or just-
in-time compiled by the JVM.

11) Use of `throw`, `throws`, `try`, `catch`, `finally`

java

`class ExceptionDemo {
static void divide(int a, int b) throws ArithmeticException {
if (b == 0)
throw new ArithmeticException("Cannot divide by zero");
System.out.println("Result: " + (a / b));
}

public static void main(String[] args) {


try {
divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
} finally {
System.out.println("Finally block executed");
}
}
}
`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 32/34
12) Exception types + Mobile Number Checker

Types:

Checked Exceptions (e.g., `IOException`)


Unchecked Exceptions (e.g., `NullPointerException`)

Errors (e.g., `OutOfMemoryError`)

Implication of catching `Exception`:

Catches all exceptions, but not recommended as it hides specific errors.

User-defined Exception for Mobile Number:

java

`import java.util.Scanner;

class InvalidMobileException extends Exception {


public InvalidMobileException(String msg) {
super(msg);
}
}

public class MobileCheck {


static void validateMobile(String number) throws InvalidMobileException {
if (number.length() != 10 || !number.matches("\\d+")) {
throw new InvalidMobileException("Invalid Mobile Number!");
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter mobile number: ");
String number = sc.nextLine();

try {
validateMobile(number);
System.out.println("Valid mobile number");
} catch (InvalidMobileException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
`

13) Superclass of all exception classes + Banking Exception Program

Superclass: `Throwable`
Banking Simulation Example:

java

`class InsufficientBalanceException extends Exception {


public InsufficientBalanceException(String msg) {
super(msg);
}
}

class BankAccount {

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 33/34
private double balance = 1000;

void withdraw(double amt) throws InsufficientBalanceException {


if (balance - amt < 0) {
throw new InsufficientBalanceException("Insufficient balance.");
}
balance -= amt;
System.out.println("Withdrawal successful. Balance: " + balance);
}
}

public class BankSimulation {


public static void main(String[] args) {
BankAccount acc = new BankAccount();
try {
acc.withdraw(1200);
} catch (InsufficientBalanceException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
`

Would you like a compiled document/PDF version of all these questions and answers next?

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 34/34

You might also like