JavaPrac 1-3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

1. OOPs concepts in Java – 1 a.

Write a program to create a class and implement a default,


overloaded and copy Constructor
public class Person {
private String name;
private int age;
// Default Constructor
public Person() {
this.name = "Unknown";
this.age = 0;
}
// Overloaded Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Copy Constructor
public Person(Person otherPerson) {
this.name = otherPerson.name;
this.age = otherPerson.age;
}
// Getter methods
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
// Using Default Constructor
Person person1 = new Person();
System.out.println("Default Constructor:");
person1.displayInfo();
System.out.println();
// Using Overloaded Constructor
Person person2 = new Person("John Doe", 25);
System.out.println("Overloaded Constructor:");
person2.displayInfo();
System.out.println();
// Using Copy Constructor
Person person3 = new Person(person2);
System.out.println("Copy Constructor:");
person3.displayInfo();
}
}
#output : Default Constructor: Overloaded Constructor: Copy Constructor:
Name: Unknown Name: John Doe Name: John Doe
Age: 0 Age: 25 Age: 25
b. Write a program to create a class and implement the concepts of Method Overloading
#Output:
public class MethodOverloadingExample {
// Method with two integer parameters
public int add(int a, int b) {
return a + b;
}
// Method with three integer parameters
public int add(int a, int b, int c) {
return a + b + c;
}
// Method with two double parameters
public double add(double a, double b) {
return a + b;
}
// Method with a String parameter
public String concatenate(String str1, String str2) {
return str1 + str2;
}
public static void main(String[] args) {
MethodOverloadingExample example = new MethodOverloadingExample();
// Call methods with different parameter combinations
int sum1 = example.add(5, 10);
int sum2 = example.add(5, 10, 15);
double sum3 = example.add(3.5, 7.5);
String result = example.concatenate("Hello, ", "World!");
// Display the results
System.out.println("Sum 1: " + sum1);
System.out.println("Sum 2: " + sum2);
System.out.println("Sum 3: " + sum3);
System.out.println("Concatenated String: " + result);
}}
#Output:
Sum 1: 15
Sum 2: 30
Sum 3: 11.0
Concatenated String: Hello, World!
C.Write a program to create a class and implement the concepts of Static methods
#Program:
public class MathOperations {
// Static method to calculate the sum of two numbers
public static int add(int a, int b) {
return a + b;
}
// Static method to calculate the difference of two numbers
public static int subtract(int a, int b) {
return a - b;
}
// Static method to calculate the product of two numbers
public static int multiply(int a, int b) {
return a * b;
}
public static void main(String[] args) {
// Calling static methods without creating an instance
int sumResult = MathOperations.add(5, 3);
int differenceResult = MathOperations.subtract(8, 4);
int productResult = MathOperations.multiply(2, 6);
// Displaying results
System.out.println("Sum: " + sumResult);
System.out.println("Difference: " + differenceResult);
System.out.println("Product: " + productResult);
} }
#Output :
Sum: 8
Difference: 4
Product: 12
Prac 2.a Write a program to implement the concepts of Inheritance and Method overriding
#Program:
// Base class
class Animal {
String name;

// Constructor
public Animal(String name) {
this.name = name;
}
// Method to display information about the animal
public void displayInfo() {
System.out.println("I am an animal. My name is " + name);
}
}
// Derived class (subclass) inheriting from Animal
class Dog extends Animal {
String breed;
// Constructor
public Dog(String name, String breed) {
// Call the constructor of the base class (Animal)
super(name);
this.breed = breed;
}
// Override the displayInfo method from the base class
@Override
public void displayInfo() {
System.out.println("I am a dog. My name is " + name + " and my breed is " + breed);
}
// New method specific to the Dog class
public void bark() {
System.out.println("Woof! Woof!");
} }
public class InheritanceExample {
public static void main(String[] args) {
// Create an instance of the base class (Animal)
Animal animal = new Animal("Generic Animal");
animal.displayInfo();
System.out.println();
// Create an instance of the derived class (Dog)
Dog dog = new Dog("Buddy", "Golden Retriever");
dog.displayInfo();
dog.bark();
} }
#Program:
I am an animal. My name is Generic Animal
I am a dog. My name is Buddy and my breed is Golden Retriever
Woof! Woof!
2.b Write a program to implement the concepts of Abstract classes and methods
#Program :
abstract class Animal {
// Abstract method (no implementation body)
abstract void makeSound();
// Regular method (with implementation body)
void eat() {
System.out.println("Animal is eating.");
} }
// Concrete subclass (extends Animal and implements makeSound())
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Woof!");
} }
// Concrete subclass (extends Animal and implements makeSound())
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow!");
} }
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
dog.makeSound(); // Output: Woof!
dog.eat(); // Output: Animal is eating.
cat.makeSound(); // Output: Meow!
cat.eat(); // Output: Animal is eating.
} }
#Program :
Woof!
Animal is eating.
Meow!
Animal is eating.
2.c Write a program to implement the concept of interfaces.
#Program :
interface Shape {
// Interface methods (no implementation)
double getArea();
void draw();
}
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius);
} }
class Rectangle implements Shape {
private double width, height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
@Override
public void draw() {
System.out.println("Drawing a rectangle with width " + width + " and height " + height);
} }
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);
printShapeInfo(circle);
printShapeInfo(rectangle);
}
static void printShapeInfo(Shape shape) {
System.out.println("Shape area: " + shape.getArea());
shape.draw();
} }
#Output :
Shape area : 78.53981633974483
Drawing a circle with radius 5.0
Shape area : 24.0
Drawing a ectangle with width 4.0 and height 6.0
Prac 3.a Write a program to raise built-in exceptions and raise them as per the requirements
public class CustomExceptionExample {
// Method that throws a built-in exception based on a condition
public static void validateAge(int age) throws IllegalArgumentException {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older");
}
// Perform other operations if the age is valid
System.out.println("Age is valid: " + age);
}
// Method that throws a built-in exception based on a condition
public static void validateDivide(int numerator, int denominator) throws ArithmeticException
{
if (denominator == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
int result = numerator / denominator;
System.out.println("Result of division: " + result);
}
public static void main(String[] args) {
try {
// Example 1: Validating age
validateAge(25);
// Example 2: Performing division
validateDivide(10, 2);
// Example 3: Attempting to divide by zero (should raise an exception)
validateDivide(5, 0); // This line will not be executed due to the exception
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException caught: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " + e.getMessage());
} } }
#Output :
Age is valid: 25
Result of division: 5
ArithmeticException caught: Cannot divide by zero
3.b Write a program to define user defined exceptions and raise them as per the
requirements
#Program :
// Custom exception class
class CustomValidationException extends Exception {
// Constructor that takes a custom message
public CustomValidationException(String message) {
super(message);
} }
public class CustomExceptionExample {
// Method that throws a custom exception based on a condition
public static void validateAge(int age) throws CustomValidationException {
if (age < 0) {
throw new CustomValidationException("Age cannot be negative");
}
if (age < 18) {
throw new CustomValidationException("Age must be 18 or older");
}
// Perform other operations if the age is valid
System.out.println("Age is valid: " + age);
}
public static void main(String[] args) {
try {
// Example 1: Validating age
validateAge(25);
// Example 2: Attempting to validate with negative age (should raise a custom exception)
validateAge(-5); // This line will not be executed due to the exception
} catch (CustomValidationException e) {
System.out.println("CustomValidationException caught: " + e.getMessage());
} } }
#Output :
Age is valid: 25
CustomValidationException caught: Age cannot be negative.

You might also like