0% found this document useful (0 votes)
33 views11 pages

OOPD Soved QP

Uploaded by

adimj257
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)
33 views11 pages

OOPD Soved QP

Uploaded by

adimj257
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/ 11

Course Title : Object Oriented Programming and Design

1. Explain modifier types and its access with examples.


>>Available in Notes.

• 2. a. Explain the process of building and running a Java application program.


>>Create a Java File: Write your Java code in a text editor or an Integrated
Development Environment (IDE) like IntelliJ IDEA, Eclipse, or NetBeans. Save the
file with a .java extension.
• Example:

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
. Compile the Code
• Use the Java Compiler: Open a terminal or command prompt and navigate to the
directory containing your .java file. Run the javac command to compile your code:
Copy code
javac HelloWorld.java
• Output: This command generates a .class file (e.g., HelloWorld.class) containing
bytecode that the Java Virtual Machine (JVM) can execute.
. Run the Application
• Use the Java Interpreter: To run your compiled Java application, use the java
command followed by the name of the class (without the .class extension):
Copy code
java HelloWorld
• Output: The JVM executes the bytecode, and you should see the output on the console
(e.g., Hello, World!).
5. Package the Application (Optional)
• Create a JAR File: If you want to package your application for distribution, you can
create a Java Archive (JAR) file. This is done using the jar command:
arduino
Copy code
jar cvf HelloWorld.jar HelloWorld.class
• Run the JAR File: You can run the JAR file using:
Copy code
java -jar HelloWorld.jar
. Debugging and Testing
• Debugging: Use debugging tools provided by your IDE to troubleshoot and fix any
issues in your code.
• Testing: Write and execute test cases to ensure your application behaves as expected.
-------------------------------------------------------------------------------------------------------
b. Write a method which accepts unsorted integer array as parameter and returns
largest element in the array.
>> public class ArrayUtils {
public static int findLargest(int[] arr) {
// Check if the array is empty
if (arr == null || arr.length == 0) {
throw new IllegalArgumentException("Array cannot be null or empty");
}

// Initialize the largest element to the first element


int largest = arr[0];

// Iterate through the array


for (int i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
largest = arr[i]; // Update largest if current element is greater
}
}

return largest; // Return the largest element found


}
public static void main(String[] args) {
int[] numbers = {3, 5, 7, 2, 8, -1, 4};
int largest = findLargest(numbers);
System.out.println("The largest element is: " + largest);
}
}
---------------------------------------------------------------------------------------------------------------

3. a) What is the output of following snippets? Explain. [4M]


i) class LogicalOP
{
public static void main (String args[])
{
boolean a = true;
boolean b = false;
System.out.println("a||b = " +(a||b));
System.out.println("a&&b = "+(a&&b));
System.out.println("a! = "+(!a));
}
}
ii) class Operator
{
public static void main(String args[])
{
int x=1;
int y=3;
int u;
int z;
u=++y;
z=x++;
System.out.println(x);
System.out.println(y);
System.out.println(u);
System.out.println(z);
}}

>> Explanation:
1. Logical OR (||):
o a || b evaluates to true because at least one operand (a) is true.
o Output: a||b = true
2. Logical AND (&&):
o a && b evaluates to false because both operands must be true for the result to
be true, and b is false.
o Output: a&&b = false
3. Logical NOT (!):
o !a evaluates to false because a is true, and the NOT operator negates it.
o Output: a! = false
Overall Output:
css
Copy code
a||b = true
a&&b = false
a! = false
-------------------------------------------------------------------------------------------------------

b) State difference between method overloading and method overriding in Java.


>> Method Overloading
1. Definition: Method overloading occurs when multiple methods in the same class have
the same name but different parameters (different type, number, or both).
2. Purpose: It allows a class to perform similar operations with different types or
numbers of input parameters, enhancing code readability and usability.
3. Compile-Time Polymorphism: Method overloading is an example of compile-time
polymorphism, as the method to be executed is determined at compile time based on
the method signature.
4. Return Type: The return type of overloaded methods can be the same or different, but
it must differ in parameters.
5. Example:
java
Copy code
class MathUtils {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Method Overriding
1. Definition: Method overriding occurs when a subclass provides a specific
implementation of a method that is already defined in its superclass with the same
name and parameters.
2. Purpose: It allows a subclass to provide a specific behavior for a method that is
already defined in its parent class, facilitating runtime polymorphism.
3. Run-Time Polymorphism: Method overriding is an example of runtime
polymorphism, as the method to be executed is determined at runtime based on the
object’s actual type.
4. Return Type: The return type must be the same or a subtype (covariant return type) of
the return type in the superclass method.
----------------------------------------------------------------------------------------------------------------

4. write a program for bank account to perform following operations.


-Check balance
-withdraw amount
-deposit amount
Use exception/s properly in the program. Use bankac as main class. Write output of the
program.

>>class InsufficientFundsException extends Exception {


public InsufficientFundsException(String message) {
super(message);
}
}

class BankAccount {
private double balance;

public BankAccount(double initialBalance) {


if (initialBalance < 0) {
throw new IllegalArgumentException("Initial balance cannot be negative.");
}
this.balance = initialBalance;
}

public double getBalance() {


return balance;
}
public void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Deposit amount must be positive.");
}
balance += amount;
System.out.println("Deposited: " + amount);
}

public void withdraw(double amount) throws InsufficientFundsException {


if (amount <= 0) {
throw new IllegalArgumentException("Withdrawal amount must be positive.");
}
if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds for withdrawal.");
}
balance -= amount;
System.out.println("Withdrew: " + amount);
}
}

public class BankAC {


public static void main(String[] args) {
BankAccount account = new BankAccount(1000.0); // Initial balance

try {
System.out.println("Current Balance: " + account.getBalance());

// Deposit money
account.deposit(500.0);
System.out.println("Balance after deposit: " + account.getBalance());
// Withdraw money
account.withdraw(300.0);
System.out.println("Balance after withdrawal: " + account.getBalance());

// Attempt to withdraw more than the balance


account.withdraw(1500.0);
} catch (InsufficientFundsException e) {
System.err.println("Error: " + e.getMessage());
} catch (IllegalArgumentException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
--------------------------------------------------------------------------------------------------------------

.5.There is a file input.txt with the following content −

“This is test for copy file.”


Create same file content to another file names ouput.txt. Use exceptions properly.

>>import java.io.*;

public class FileCopy {


public static void main(String[] args) {
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");

// Using try-with-resources for automatic resource management


try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {

String line;
// Read each line from input file and write to output file
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine(); // Add a new line after each line copied
}

System.out.println("File copied successfully!");


} catch (FileNotFoundException e) {
System.err.println("Error: Input file not found - " + e.getMessage());
} catch (IOException e) {
System.err.println("Error: An I/O error occurred - " + e.getMessage());
}
}
}

Explanation
1. File Handling:
o The program uses File, BufferedReader, and BufferedWriter to manage
reading from and writing to the files.
2. Try-with-Resources:
o This feature automatically closes the BufferedReader and BufferedWriter at
the end of the block, ensuring resources are released properly.
3. Reading and Writing:
o The program reads each line from input.txt using readLine() and writes it to
output.txt. After writing each line, it adds a new line using newLine().
4. Exception Handling:
o FileNotFoundException: This exception is caught if input.txt does not exist in
the specified directory.
o IOException: This catches any input/output errors that may occur while
reading from or writing to the files.

----------------------------------------------------------------------------------------------------------------
6. Write a JAVA program to create your own exception (User Exception) that displays
the error message “ Invalid Input” to find the area of the circle when the radius is given
as either 0 or a negative value
>> // Custom Exception Class
class InvalidInputException extends Exception {
public InvalidInputException(String message) {
super(message);
}
}

public class CircleArea {

// Method to calculate area of the circle


public static double calculateArea(double radius) throws InvalidInputException {
if (radius <= 0) {
throw new InvalidInputException("Invalid Input: Radius must be greater than zero.");
}
return Math.PI * radius * radius; // Area formula: πr²
}

public static void main(String[] args) {


double radius = -5; // Change this value to test different inputs

try {
double area = calculateArea(radius);
System.out.printf("The area of the circle with radius %.2f is: %.2f%n", radius, area);
} catch (InvalidInputException e) {
System.err.println(e.getMessage());
}
}
}
Explanation

1. Custom Exception Class:


o InvalidInputException extends the Exception class. It takes an error message
as a parameter and passes it to the superclass.
2. Area Calculation Method:
o The calculateArea method takes a double parameter for the radius.
o If the radius is less than or equal to 0, it throws an InvalidInputException with
a specific error message.
o If the input is valid, it calculates the area using the formula πr2\pi r^2πr2.
3. Main Method:
o The main method sets a test radius (you can change this value to test different
inputs).
o It calls the calculateArea method within a try-catch block to handle the custom
exception.
o If an exception is thrown, it catches it and prints the error message.
7. Write a JAVA program to create two classes for displaying first 15 fibonacci
numbers and first 15 prime numbers between 200 to 500 and produce their outputs
concurrently in 3 slots ( Printing some prime numbers for each 5 fibonacci numbers)
using multithreading
>>
Class to generate and display Fibonacci numbers
class Fibonacci extends Thread {
public void run() {
int num1 = 0, num2 = 1;
System.out.println("Fibonacci Numbers:");
for (int i = 1; i <= 15; i++) {
System.out.print(num1 + " ");
int nextNum = num1 + num2;
num1 = num2;
num2 = nextNum;
// Sleep for a while to simulate concurrent execution
try {
Thread.sleep(100); // Adjust time for better output visibility
} catch (InterruptedException e) {
System.err.println(e.getMessage());
}
// Print prime numbers intermittently
if (i % 5 == 0) {
System.out.println(); // New line after every 5 Fibonacci numbers
printPrimes(); // Call to print primes
}
}
System.out.println();
}

// Method to print prime numbers between 200 and 500


public void printPrimes() {
System.out.print("Prime Numbers: ");
int count = 0;
for (int num = 200; num <= 500 && count < 15; num++) {
if (isPrime(num)) {
System.out.print(num + " ");
count++;
// Simulate delay
try {
Thread.sleep(100); // Adjust time for better output visibility
} catch (InterruptedException e) {
System.err.println(e.getMessage());
}
}
}
System.out.println(); // New line after printing prime numbers
}

// Method to check if a number is prime


private boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
}

// Class to run the main program


public class Main {
public static void main(String[] args) {
Fibonacci fibonacciThread = new Fibonacci();
fibonacciThread.start(); // Start Fibonacci thread
}
}

XXXXXXX

You might also like