oopsthroughjava
oopsthroughjava
Use Eclipse or Net bean platform and acquaint yourself with the various
menus. Create a test project, add a test class, and run it. See how you can use
auto suggestions, auto fill. Try code formatter and code refactoring like
renaming variables, methods, and classes. Try debug step by step with a small
program of about 10 to 15 lines which contains at least one if else conditionand
a for loop.
// Inheritance demo
Bike B = new Bike();
B.method(); // Output: Bike
// Polymorphism demo
Vehicle V1 = new Bike();
Vehicle V2 = new Car();
V1.method(); // Output: Bike
V2.method(); // Output: Car
// Abstraction demo
Shape shape1 = new Rectangle();
Shape shape2 = new Circle();
shape1.draw(); // Output: Drawing Rectangle
shape2.draw(); // Output: Drawing Circle
}
}
OUTPUT
3. Write a Java program to handle checked and unchecked exceptions. Also,
demonstrate the usage of custom exceptions in real time scenario.
// Checked Exception
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
// Unchecked Exception
class InvalidInputException extends RuntimeException {
public InvalidInputException(String message) {
super(message);
}
}
// Custom Exception for Real-Time Scenario
class AuthenticationException extends Exception {
public AuthenticationException(String message) {
super(message);
}
}
class BankAccount {
private double balance;
public BankAccount(double balance) {
this.balance = balance;
}
// Method to withdraw money
public void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance in the
account");
}
balance -= amount;
System.out.println("Withdrawal successful. Remaining balance: " +
balance);
}
}
try {
// Handling custom exception in a real-time scenario
login("admin", "admin@123"); // Throws AuthenticationException
} catch (AuthenticationException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output
4. Write a Java program on Random Access File class to perform different read
and write operations.
import java.io.File;
import java.io.RandomAccessFile;
public class RandomAccessFileDemo {
public static void main(String[] args) {
try {
// Creating a RandomAccessFile object with read-write mode
RandomAccessFile file = new RandomAccessFile("data.txt", "rw");
// Writing data to the file
file.writeUTF("Hello, World!");
// Moving the file pointer to the beginning of the file
file.seek(0);
// Reading data from the file
String data = file.readUTF();
System.out.println("Data read from file: " + data);
// Appending data to the file
file.seek(file.length());
file.writeUTF("\nThis is a new line.");
// Moving the file pointer to the beginning of the file
file.seek(0);
// Reading data from the file after appending
data = file.readUTF();
System.out.println("Data read from file after appending: " + data);