OOP Practical Answer
OOP Practical Answer
This conversation may reflect the link creator’s personalized data, which isn’t shared and can
meaningfully change how the model responds.
Sure, please provide the questions, and I'll help you with the answers and their corresponding output.
1. a) Write a program in Java to swap the values of two variables without using a third variable.
b) Write a menu-driven calculator program in Java using switch-case construct.
1. a) Java Program to Swap Values of Two Variables Without Using a Third Variable
Here is a simple Java program to swap the values of two variables without using a third variable:
java
System.out.println("Before swap:");
System.out.println("a = " + a);
System.out.println("b = " + b);
// Swap values
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swap:");
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
Output:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/21
less
Before swap:
a = 5
b = 10
After swap:
a = 10
b = 5
Here's a Java program that implements a simple menu-driven calculator using the switch-case
construct:
java
import java.util.Scanner;
while (!exit) {
System.out.println("Menu:");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
System.out.println("Result: " + (num1 + num2));
break;
case 2:
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
System.out.println("Result: " + (num1 - num2));
break;
case 3:
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
System.out.println("Result: " + (num1 * num2));
break;
case 4:
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
if (num2 != 0) {
System.out.println("Result: " + (num1 / num2));
} else {
System.out.println("Error! Division by zero.");
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/21
break;
case 5:
exit = true;
break;
default:
System.out.println("Invalid choice! Please choose a valid option.");
}
System.out.println();
}
scanner.close();
}
}
Example Output:
markdown
Menu:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice: 1
Enter first number: 10
Enter second number: 5
Result: 15.0
Menu:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice: 5
This calculator will keep displaying the menu until the user chooses to exit by selecting option 5.
Method overloading allows a class to have more than one method with the same name, as long as
their parameter lists are different. Here is a simple Java program to illustrate this concept:
java
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/21
// Method with two integer parameters
public void display(int a, int b) {
System.out.println("Method with two integer parameters: " + a + ", " + b);
}
Output:
sql
Dynamic method dispatch (also known as runtime polymorphism) is a mechanism by which a call to
an overridden method is resolved at runtime rather than compile-time. Here’s a Java program to
demonstrate this concept:
java
class A {
// Method to be overridden
void display() {
System.out.println("Display method of class A");
}
}
class B extends A {
// Overriding the display method
void display() {
System.out.println("Display method of class B");
}
}
class C extends A {
// Overriding the display method
void display() {
System.out.println("Display method of class C");
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/21
// Pointing to an object of class C
a = new C();
a.display(); // Calls the display method of class C
}
}
Output:
kotlin
In this program, the `display` method of the appropriate subclass (either `B` or `C`) is called based on
the actual object the reference variable `a` points to, demonstrating dynamic method dispatch.
In multi-level inheritance, a class is derived from another derived class. Here's an example to illustrate
this concept:
java
// Base class
class Animal {
void eat() {
System.out.println("Eating...");
}
}
// Derived class
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 5/21
}
}
Output:
Weeping...
Barking...
Eating...
The `super` keyword in Java is used to call the constructor of the parent class. Here’s an example
demonstrating its use:
java
// Base class
class Person {
String name;
void display() {
System.out.println("Name: " + name);
}
}
// Derived class
class Employee extends Person {
double salary;
void display() {
super.display(); // Calling the display method of the base class
System.out.println("Salary: " + salary);
}
}
Output:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/21
kotlin
In this example, the `super(name)` call in the `Employee` constructor invokes the constructor of the
`Person` class, demonstrating how the `super` keyword can be used to initialize the base class part of
an object.
A prime number is a number that is only divisible by 1 and itself. Here's a Java program to check if a
number is prime:
java
import java.util.Scanner;
if (number <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
scanner.close();
}
}
Output:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/21
less
Enter a number: 17
17 is a prime number.
An abstract class in Java is a class that cannot be instantiated and can have abstract methods
(methods without a body) that must be implemented by subclasses. Here's an example:
java
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
abstract void sound();
// Regular method
void sleep() {
System.out.println("Sleeping...");
}
}
Output:
Barking...
Sleeping...
In this example, the `Animal` class is abstract and contains an abstract method `sound()`. The `Dog`
class extends `Animal` and provides an implementation for the `sound()` method.
5. a) Write a program in Java to find the minimum among three numbers using nested-if
statements. Take the numbers from user.
b) Write a program in Java to illustrate the concept of method over-riding.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/21
5. a) Java Program to Find the Minimum Among Three Numbers Using Nested-if
Statements
This program will take three numbers from the user and determine the smallest using nested-if
statements:
java
import java.util.Scanner;
int min;
Output:
yaml
Method overriding occurs when a subclass provides a specific implementation of a method that is
already defined in its superclass. Here is an example:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 9/21
java
// Base class
class Animal {
// Method to be overridden
void sound() {
System.out.println("Animal makes a sound");
}
}
// Derived class
class Dog extends Animal {
// Overriding the sound method
@Override
void sound() {
System.out.println("Dog barks");
}
}
Output:
css
In this example, the `sound` method is defined in both the `Animal` class and the `Dog` class. The `Dog`
class provides its own implementation of the `sound` method, demonstrating method overriding.
When `sound` is called on an `Animal` reference that points to a `Dog` object, the `Dog`'s
implementation of `sound` is executed.
6. a) Write a Java program to illustrate the concept "A superclass reference may point to a subclass
object"।
b) Write a program in Java to show the concept of constructor overloading.
In Java, a superclass reference can refer to an object of its subclass. This is useful in polymorphism.
Here’s an example:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 10/21
java
// Superclass
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
// Subclass
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
void fetch() {
System.out.println("Dog fetches");
}
}
Output:
Dog barks
In this example, the `myAnimal` reference of type `Animal` points to an object of type `Dog`. When
is called on `myAnimal`, the overridden method in the `Dog` class is executed, demonstrating
`sound`
polymorphism. The line `myAnimal.fetch()` is commented out because the `fetch` method is not
defined in the `Animal` class and would cause a compile-time error.
Constructor overloading is when a class has more than one constructor with different parameter lists.
Here’s an example:
java
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 11/21
ConstructorOverloading(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
void display() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
if (age != 0) {
System.out.println("Age: " + age);
}
}
student1.display();
System.out.println();
student2.display();
}
}
Output:
makefile
ID: 1
Name: Alice
ID: 2
Name: Bob
Age: 20
In this example, the class `ConstructorOverloading` has two constructors with different parameter
lists. The first constructor initializes `id` and `name`, while the second constructor initializes `id`,
`name`, and `age`. This allows creating objects with different initial states.
In Java, multiple catch clauses can be used to handle different types of exceptions. Here’s an example:
java
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 12/21
ArrayIndexOutOfBoundsException
int result = 10 / 0; // ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: Division by zero.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: Array index out of
bounds.");
} catch (Exception e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
}
Output:
sql
In this example, the program demonstrates the use of multiple catch clauses to handle different types
of exceptions. The first catch block catches `ArithmeticException`, the second catches
`ArrayIndexOutOfBoundsException`, and the last one is a generic catch block for any other exceptions.
The `throws` keyword in Java is used to declare that a method can throw one or more exceptions.
Here’s an example:
java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Output:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 13/21
yaml
In this example, the `readFile` method declares that it throws an `IOException`. When calling this
method, the `main` method handles the exception using a try-catch block. This demonstrates how the
`throws` keyword is used to propagate exceptions up the call stack.
In Java, interfaces can inherit from other interfaces using the `extends` keyword. Here’s an example
demonstrating interface inheritance:
java
// Base interface
interface Animal {
void sound();
}
@Override
public void fetch() {
System.out.println("Labrador fetches");
}
}
Output:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 14/21
Labrador barks
Labrador fetches
In this example, the `Dog` interface inherits the `Animal` interface, and the `Labrador` class
implements the `Dog` interface. The `Labrador` class must provide implementations for all methods
defined in both `Animal` and `Dog` interfaces.
Inner classes are classes defined within another class in Java. There are several types of inner classes:
non-static nested classes (inner classes), static nested classes, local classes, and anonymous classes.
Here’s an example of each type:
java
// Outer class
class Outer {
private int outerData = 10;
// Inner class
class Inner {
void display() {
System.out.println("Outer data: " + outerData);
}
}
}
Output:
kotlin
Outer data: 10
java
// Outer class
class Outer {
static class Nested {
void display() {
System.out.println("Static nested class method");
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 15/21
}
}
}
Output:
kotlin
java
// Outer class
class Outer {
void outerMethod() {
// Local class inside a method
class Local {
void display() {
System.out.println("Local class method");
}
}
Output:
kotlin
Anonymous Class
java
// Interface
interface Greeting {
void greet();
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 16/21
}
greeting.greet();
}
}
Output:
mathematica
Inner classes provide encapsulation and logical grouping of classes within other classes, enhancing
code readability and maintainability.
An Armstrong number (also known as narcissistic number) for a given number of digits is a number
that is equal to the sum of its own digits each raised to the power of the number of digits. Here's a
Java program to check if a number is an Armstrong number:
java
import java.util.Scanner;
originalNumber = number;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 17/21
originalNumber = number;
// Calculate result
while (originalNumber != 0) {
remainder = originalNumber % 10;
result += Math.pow(remainder, n);
originalNumber /= 10;
}
if (result == number)
System.out.println(number + " is an Armstrong number.");
else
System.out.println(number + " is not an Armstrong number.");
scanner.close();
}
}
Output:
csharp
In this program:
The `continue` keyword in Java is used to skip the current iteration of a loop and proceed to the next
iteration. Here’s an example demonstrating its use:
java
Output:
2
4
6
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 18/21
8
10
In this example:
The `continue` keyword is useful for skipping certain iterations based on a condition without exiting
the loop entirely.
The `break` statement in Java is used to terminate the loop or switch statement it is used in. Here’s an
example demonstrating its use:
java
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 19/21
Output:
less
Current i value: 1
Current i value: 2
Current i value: 3
Current i value: 4
Breaking the loop at i = 5
i = 1, j = 1
Breaking the nested loop at i = 1, j = 2
In this program:
Example 1 demonstrates using `break` to terminate a `for` loop when `i` equals 5.
Example 2 shows using `break` to break out of a nested loop labeled as `outerloop` when `j`
equals 2.
To print all possible combinations of the digits 1, 2, and 3 without repeating any individual digit, we
can use nested loops. Here’s a Java program to achieve this:
java
Output:
mathematica
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 20/21
3 2 1
Total combinations: 6
In this program:
This approach ensures that all possible combinations of the digits 1, 2, and 3 are printed without any
repetition of individual digits within each combination.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 21/21