0% found this document useful (0 votes)
4 views13 pages

Diploma Practical File Java

The document contains multiple Java programs demonstrating various concepts such as classes, inheritance, abstract classes, exception handling, packages, interfaces, and threading. Each program includes code snippets for creating shapes, bank accounts, string manipulations, and handling exceptions, along with their respective outputs. The document serves as a comprehensive guide for understanding object-oriented programming in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views13 pages

Diploma Practical File Java

The document contains multiple Java programs demonstrating various concepts such as classes, inheritance, abstract classes, exception handling, packages, interfaces, and threading. Each program includes code snippets for creating shapes, bank accounts, string manipulations, and handling exceptions, along with their respective outputs. The document serves as a comprehensive guide for understanding object-oriented programming in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

1.

WAP to create a simple class to find out the area and perimeter of rectangle and box
using super and this keyword.
// Superclass for Rectangle
class Rectangle {
int length, breadth;

// Constructor using 'this' keyword


Rectangle(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}

// Method to calculate area of rectangle


int area() {
return length * breadth;
}

// Method to calculate perimeter of rectangle


int perimeter() {
return 2 * (length + breadth);
}
}

// Subclass for Box


class Box extends Rectangle {
int height;

// Constructor using 'super' to call Rectangle constructor


Box(int length, int breadth, int height) {
super(length, breadth); // calling superclass constructor
this.height = height; // referring to current class variable
}

// Method to calculate surface area of box


int surfaceArea() {
return 2 * (length * breadth + breadth * height + height * length);
}

// Method to calculate volume of box


int volume() {
return length * breadth * height;
}
}

// Main class to run the program


public class Main {
public static void main(String[] args) {
// Creating object of Rectangle
Rectangle rect = new Rectangle(10, 5);
System.out.println("Rectangle Area: " + rect.area());
System.out.println("Rectangle Perimeter: " + rect.perimeter());

// Creating object of Box


Box box = new Box(10, 5, 4);
System.out.println("\nBox Surface Area: " + box.surfaceArea());
System.out.println("Box Volume: " + box.volume());
}
}

2. WAP to design a class account using the inheritance and static that show all function of
bank (withdrawal, deposit).
// Base class Account
class Account {
static int accountCount = 0; // static variable to count number of accounts
String name;
int accNumber;
double balance;

// Constructor
Account(String name, int accNumber, double balance) {
this.name = name;
this.accNumber = accNumber;
this.balance = balance;
accountCount++; // increment account count when new account is created
}

// Method to deposit money


void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount);
System.out.println("New Balance: " + balance);
}

// Method to withdraw money


void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
System.out.println("Remaining Balance: " + balance);
} else {
System.out.println("Insufficient balance!");
}
}

// Method to display account info


void display() {
System.out.println("Account Holder: " + name);
System.out.println("Account Number: " + accNumber);
System.out.println("Current Balance: " + balance);
}

// Static method to show total number of accounts


static void showTotalAccounts() {
System.out.println("Total Accounts Created: " + accountCount);
}
}

// Derived class SavingAccount


class SavingAccount extends Account {
double interestRate;

// Constructor
SavingAccount(String name, int accNumber, double balance, double interestRate) {
super(name, accNumber, balance); // calling base class constructor
this.interestRate = interestRate;
}

// Method to add interest


void addInterest() {
double interest = balance * interestRate / 100;
balance += interest;
System.out.println("Interest Added: " + interest);
System.out.println("Balance after Interest: " + balance);
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Creating first account
SavingAccount acc1 = new SavingAccount("Alice", 1001, 5000, 3.5);
acc1.display();
acc1.deposit(1500);
acc1.withdraw(2000);
acc1.addInterest();
System.out.println();

// Creating second account


SavingAccount acc2 = new SavingAccount("Bob", 1002, 3000, 4.0);
acc2.display();
acc2.deposit(1000);
acc2.withdraw(500);
acc2.addInterest();

System.out.println();

// Display total accounts


Account.showTotalAccounts();
}
}
Output
Account Holder: Alice
Account Number: 1001
Current Balance: 5000.0
Deposited: 1500.0
New Balance: 6500.0
Withdrawn: 2000.0
Remaining Balance: 4500.0
Interest Added: 157.5
Balance after Interest: 4657.5

Account Holder: Bob


Account Number: 1002
Current Balance: 3000.0
Deposited: 1000.0
New Balance: 4000.0
Withdrawn: 500.0
Remaining Balance: 3500.0
Interest Added: 140.0
Balance after Interest: 3640.0

Total Accounts Created: 2

3. WAP to design a class using abstract methods and classes.


// Abstract class
abstract class Shape {
// Abstract method (no body)
abstract void area();
// Concrete method
void display() {
System.out.println("This is a shape.");
}
}

// Subclass for Circle


class Circle extends Shape {
double radius;

Circle(double radius) {
this.radius = radius;
}

// Implementing abstract method


void area() {
double a = Math.PI * radius * radius;
System.out.println("Area of Circle: " + a);
}
}

// Subclass for Rectangle


class Rectangle extends Shape {
double length, breadth;

Rectangle(double length, double breadth) {


this.length = length;
this.breadth = breadth;
}

// Implementing abstract method


void area() {
double a = length * breadth;
System.out.println("Area of Rectangle: " + a);
}
}

// Main class to run the program


public class Main {
public static void main(String[] args) {
// Shape s = new Shape(); // Not allowed: abstract class cannot be instantiated

Shape circle = new Circle(5.0); // upcasting


circle.display();
circle.area();
System.out.println();

Shape rectangle = new Rectangle(4.0, 6.0); // upcasting


rectangle.display();
rectangle.area();
}
}
OUTPUT-
This is a shape.
Area of Circle: 78.53981633974483

This is a shape.
Area of Rectangle: 24.0

4. WAP to design a string class that perform string method (equal, reverse the string, change
case).
class MyString {
String str;

// Constructor
MyString(String str) {
this.str = str;
}

// Method to check equality with another MyString


boolean isEqual(MyString other) {
return this.str.equals(other.str);
}

// Method to reverse the string


String reverse() {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}

// Method to change the case of characters


String changeCase() {
StringBuilder result = new StringBuilder();

for (int i = 0; i < str.length(); i++) {


char ch = str.charAt(i);

if (Character.isUpperCase(ch)) {
result.append(Character.toLowerCase(ch));
} else if (Character.isLowerCase(ch)) {
result.append(Character.toUpperCase(ch));
} else {
result.append(ch); // keep symbols and spaces unchanged
}
}

return result.toString();
}

// Method to display the original string


void display() {
System.out.println("Original String: " + str);
}
}

// Main class to test MyString


public class Main {
public static void main(String[] args) {
MyString s1 = new MyString("HelloWorld");
MyString s2 = new MyString("helloworld");

s1.display();
System.out.println("Reversed: " + s1.reverse());
System.out.println("Case Changed: " + s1.changeCase());
System.out.println();

s2.display();
System.out.println("Reversed: " + s2.reverse());
System.out.println("Case Changed: " + s2.changeCase());
System.out.println();

System.out.println("Are s1 and s2 equal? " + s1.isEqual(s2));


}
}

Output
Original String: HelloWorld
Reversed: dlroWolleH
Case Changed: hELLOwORLD

Original String: helloworld


Reversed: dlrowolleh
Case Changed: HELLOWORLD
Are s1 and s2 equal? False

5. WAP to handle the exception using try and multiple catch block.
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int a = 10, b = 0;

// ArithmeticException: Division by zero


int result = a / b;
System.out.println("Result: " + result);

// NullPointerException
String str = null;
System.out.println("Length of string: " + str.length());

// ArrayIndexOutOfBoundsException
int[] arr = {1, 2, 3};
System.out.println("Element: " + arr[5]);

} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
} catch (Exception e) {
System.out.println("Caught General Exception: " + e.getMessage());
} finally {
System.out.println("This block always executes (finally block).");
}
}
}

Output
Caught ArithmeticException: / by zero
This block always executes (finally block).

6. WAP that implement the Nested try statements.

public class NestedTryExample {


public static void main(String[] args) {
try {
// Outer try block
int[] arr = new int[3];
arr[2] = 30;
System.out.println("Outer try block executed");

try {
// Inner try block
int num = 10 / 0; // This will throw ArithmeticException
System.out.println("Inner try result: " + num);
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException in inner try: " + e.getMessage());
}

try {
// Another inner try block
String str = null;
System.out.println(str.length()); // This will throw NullPointerException
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException in second inner try: " +
e.getMessage());
}

// This will throw ArrayIndexOutOfBoundsException


int val = arr[5];
System.out.println("Value: " + val);

} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException in outer try: " +
e.getMessage());
}

System.out.println("Program continues...");
}
}
Output
Outer try block executed
Caught ArithmeticException in inner try: / by zero
Caught NullPointerException in second inner try: Cannot invoke "String.length()" because
"str" is null
Caught ArrayIndexOutOfBoundsException in outer try: Index 5 out of bounds for length 3
Program continues...
7. WAP to create a package that access the member of external class as well as same package.

Steps Covered:

 Creating two packages: mypackage and externalpackage.


 Accessing:
o A class from the same package
o A class from an external package

Directory Structure:

Project/

├── externalpackage/

│ └── ExternalClass.java

├── mypackage/

│ ├── MyClass.java

│ └── MainClass.java

Step-by-Step Code:

externalpackage/ExternalClass.java

package externalpackage;

public class ExternalClass {


public void showExternal() {
System.out.println("Accessed method from External Package.");
}
}

mypackage/MyClass.java
package mypackage;
public class MyClass {
public void showInternal() {
System.out.println("Accessed method from Same Package.");
}
}
mypackage/MainClass.java
package mypackage;

// Import external package


import externalpackage.ExternalClass;

public class MainClass {


public static void main(String[] args) {
// Access class in same package
MyClass obj1 = new MyClass();
obj1.showInternal();

// Access class in external package


ExternalClass obj2 = new ExternalClass();
obj2.showExternal();
}
}

Compilation and Run Instructions (Command Line):


Go to the root folder (Project) and compile:
javac externalpackage/ExternalClass.java
javac mypackage/MyClass.java
javac -cp . mypackage/MainClass.java

Run the program:


java -cp . mypackage.MainClass

Output
Accessed method from Same Package.
Accessed method from External Package.

8. WAP that show the partial implementation of interface.

Interface: Vehicle.java

interface Vehicle {
void start();
void stop();
void fuelType();
}

Abstract Class: Car.java


abstract class Car implements Vehicle {
public void start() {
System.out.println("Car is starting...");
}

// stop() and fuelType() are not implemented here


}

Concrete Class: Sedan.java


class Sedan extends Car {
public void stop() {
System.out.println("Car is stopping...");
}

public void fuelType() {


System.out.println("Fuel type: Petrol");
}
}

Main Class: Main.java


public class Main {
public static void main(String[] args) {
Vehicle myCar = new Sedan(); // using interface reference
myCar.start();
myCar.stop();
myCar.fuelType();
}
}

Output
Car is starting...
Car is stopping...
Fuel type: Petrol

9. WAP to create a thread that implement the Runnable interface.

// Implementing Runnable interface


class MyRunnable implements Runnable {
public void run() {
// Code to be executed in the new thread
for (int i = 1; i <= 5; i++) {
System.out.println("Runnable Thread: " + i);
try {
Thread.sleep(500); // pause for 500ms
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " + e.getMessage());
}
}
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Creating Runnable object
MyRunnable runnable = new MyRunnable();

// Passing it to Thread constructor


Thread thread = new Thread(runnable);

// Starting the thread


thread.start();

// Main thread execution


for (int i = 1; i <= 5; i++) {
System.out.println("Main Thread: " + i);
try {
Thread.sleep(500); // pause for 500ms
} catch (InterruptedException e) {
System.out.println("Main thread interrupted: " + e.getMessage());
}
}
}
}

OUTPUT-
Runnable Thread: 1
Main Thread: 1
Runnable Thread: 2
Main Thread: 2
Runnable Thread: 3
Main Thread: 3
Runnable Thread: 4
Main Thread: 4
Runnable Thread: 5
Main Thread: 5

You might also like