Program 9: WAP to multiply two arrays.
Code:
public class MultiplyingTwoArrays
{ public static void main(String[] args) {
int [] arr1 = {10,20,30,40,50};
System.out.println("Values of Array 1"); for(int num: arr1){
System.out.print(num + " ");
}
int [] arr2 = {50,40,30,20,10};
System.out.println("\nValues of Array 2"); for(int num: arr2){
System.out.print(num + " ");
}
System.out.println("\nAFTER MULTIPLYING ARRAY 1 WITH ARRAY 2");
for(int i=0;i<arr1.length;i++){
System.out.print(arr1[i]*arr2[i] + " ");
}
}
}
Program 10: WAP to create a String class that performs String methods (Equal, reverse the string, change case).
Code:
import java.util.*;
public class StringFunctions {
public static void main(String[] args) {
String s1 = "HELLO";
String s2 = "HELLO";
String s3 = "welcome";
String s4 = "HELLO THIS SIDE Priyanshu Tiwari";
if(s1.compareTo(s2)!=0){
System.out.println("String s1 and s2 is NOT EQUAL");
}
else {
System.out.println("String s1 and s2 is EQUAL");
}
System.out.println("ORIGINAL STRING = " +s3);
StringBuilder sb = new StringBuilder(s3);
s3=sb.reverse().toString();
System.out.println("REVERSED STRING = " +s3);
System.out.println("Lower Case To Upper Case = " + s3.toUpperCase());
System.out.println("Upper Case To Lower Case = " + s4.toLowerCase());
}
}
Program 11: WAP to check whether the substring input by user belongs to a pre-defined String object.
Code:
import java.util.*;
public class StringFinder {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a String: ");
String str1 = s.nextLine();
System.out.println("Enter substring: ");
String substring = s.nextLine();
System.out.println(str1.contains(substring)?"contains "+substring:"Does not contains "+substring);
}
}
Output:
Program 12: WAP to create a class circle and define its methods for calculating area and circumference of circle. Use parametrized constructors to initialize 2 objects of circle class and print the area and circumference of the 2 objects.
Code:
public class Circle { double radius;
public Circle(double radius){
this.radius =radius;
}
double area(){
return 3.14*radius*radius;
}
double circumference(){ return 2*3.14*radius;
}
public static void main(String[] args) {
Circle circle1 = new Circle(5.0);
Circle circle2 = new Circle(7.5);
System.out.println("Circle 1 - Radius: " + circle1.radius);
System.out.println("Area: " + circle1.area());
System.out.println("Circumference: " + circle1.circumference());
System.out.println();
System.out.println("Circle 2 - Radius: " + circle2.radius);
System.out.println("Area: " + circle2.area());
System.out.println("Circumference: " + circle2.circumference());
}
}
Program 13: WAP to create a class Rectangle and define its methods for calculating area and perimeter of rectangle. Use parametrized constructors to initialize 2 objects of rectangle class and print the area and circumference of the 2 objects.
Code:
public class Rectangle { int length;
int breadth;
Rectangle(int length, int breadth){ this.length =length; this.breadth=breadth;
}
int Calc_area(){
return length*breadth;
}
int Calc_perimeter(){
return 2*(length+breadth);
}
public static void main(String[] args) {
Rectangle rectangle1 =new Rectangle(50 ,20);
Rectangle rectangle2 =new Rectangle(70 ,30);
System.out.println("Length of Rectangle1 = " + rectangle1.length);
System.out.println("Breadth of Rectangle1 = " + rectangle1.breadth);
System.out.println("Area of Rectangle1 = "+rectangle1.Calc_area());
System.out.println("Perimeter of Rectangle1 = "+rectangle1.Calc_perimeter());
System.out.println();
System.out.println("Length of Rectangle2 = " + rectangle2.length);
System.out.println("Breadth of Rectangle2 = " + rectangle2.breadth);
System.out.println("Area of Rectangle2 = "+rectangle2.Calc_area());
System.out.println("Perimeter of Rectangle2 = "+rectangle2.Calc_perimeter());
}
}
Program 14: WAP to create a class Shape and use different parameterised constructors to create objects of different shapes:
a) Shape (10,20). Rectangle
b) Shape (20.5). Circle
c) Shape (10). Square
Use method overloading to calculate and print the area of the 3 objects of the Shape class.
Code:
public class Shapes { double radius;
int length; int breadth;
int square_var;
Shapes(double radius){
this.radius =radius;
}
Shapes(int square_var){
this.square_var =square_var;
}
Shapes(int length, int breadth){
this.length =length;
this.breadth=breadth;
}
int Calc_area(int length,int breadth){ return length*breadth;
}
double Calc_area(double radius){
return 3.14*radius*radius;
}
int Calc_area(int square_var){
return square_var*square_var;
}
public static void main(String[] args) {
Shapes shape1 = new Shapes(60,40);
Shapes shape2 = new Shapes(10.0);
Shapes shape3 = new Shapes(5);
System.out.println("Length of Rectangle = "+shape1.length);
System.out.println("breadth of Rectangle = "+shape1.breadth);
System.out.println("Area of Rectangle = "+shape1.Calc_area(60,40));
System.out.println();
System.out.println("Radius of Circle = " +shape2.radius);
System.out.println("Area of Circle = "+shape2.Calc_area(10.0));
System.out.println();
System.out.println("Length and Breadth of Square = "+shape3.square_var);
System.out.println("Area of Square = "+shape3.Calc_area(5));
}
}
Program 15: Define a class MyNumber having one private int data member. Write a default constructor to initialize it to 0 and another constructor to initialize it to a value (Use this). Write methods isNegative, isPositive, isZero, isOdd, isEven. Create objects in main method.
Code:
public class MyNumber { private int data;
public MyNumber() { this.data = 0;
}
public MyNumber(int data) { this.data = data;
}
public boolean isNegative() { return data < 0;
}
public boolean isPositive() { return data > 0;
}
public boolean isZero() { return data == 0;
}
public boolean isOdd() { return data % 2 != 0;
}
public boolean isEven() { return data % 2 == 0;
}
public static void main(String[] args) {
MyNumber num1 = new MyNumber();
MyNumber num2 = new MyNumber(15);
System.out.println("Number 1:");
System.out.println(" isNegative: " + num1.isNegative());
System.out.println(" isPositive: " + num1.isPositive());
System.out.println(" isZero: " + num1.isZero());
System.out.println(" isOdd: " + num1.isOdd());
System.out.println(" isEven: " + num1.isEven());
System.out.println("\nNumber 2:");
System.out.println(" isNegative: " + num2.isNegative());
System.out.println(" isPositive: " + num2.isPositive());
System.out.println(" isZero: " + num2.isZero());
System.out.println(" isOdd: " + num2.isOdd());
System.out.println(" isEven: " + num2.isEven());
}
}
Program 16: WAP to invoke current class method using this keyword. (this.display())
Code:
public class MyClass { public void display() {
System.out.println("This is from the display method");
this.display2();
}
public void display2() {
System.out.println("This is from the display2 method");
}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
Program 17: WAP to invoke current class constructors. (this(10), this())
Code:
public class MyClass1 { private int value; public MyClass1() {
this(10);
}
public MyClass1(int value) { this.value = value;
System.out.println("Value initialized to: " + value);
}
public static void main(String[] args) { MyClass1 obj1 = new MyClass1();
MyClass1 obj2 = new MyClass1(20);
}
}
Program 18: Define a Student class (roll number, name, percentage). Define a default and parameterized constructor. Keep a count on objects created.
Create objects using parameterized constructor and display the object count after each object is created. (Use static member and method). Also display the contents of each object.
Code:
public class Student {
private int rollNumber;
private String name;
private double percentage;
private static int objectCount = 0;
public Student() {
this.rollNumber = 0;
this.name = "NA";
this.percentage = 0.0;
objectCount++;
}
public Student(int rollNumber, String name, double percentage) {
this.rollNumber = rollNumber;
this.name = name;
this.percentage = percentage; objectCount++;
}
public void display() {
System.out.println("Roll Number: " + rollNumber);
System.out.println("Name: " + name);
System.out.println("Percentage: " + percentage);
}
public static int getObjectCount() {
return objectCount;
}
public static void main(String[] args) {
Student student1 = new Student(1, "Priyanshu Tiwari", 85.5);
Student student2 = new Student(2, "Alok Tiwari", 92.0);
System.out.println("Object count after creating student1: " + Student.getObjectCount());
student1.display();
System.out.println("\nObject count after creating student2: " + Student.getObjectCount());
student2.display();
}
}
Program 19: Write a test program (says TestCylinder) to test the Cylinder class created. Create three objects of Cylinder class namely c1, c2 and c3 as below and display height, radius, area, and volume of all the objects.
Code:
Circle
public class Circle {
private double radius = 1.0;
private String color = "red";
public Circle() {
}
public Circle(double radius) {
this.radius = radius;
}
public Circle(double radius, String color) {
this.radius = radius;
this.color = color;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getRadius() {
return radius;
}
public String getColor() {
return color;
}
Cylinder
public class Cylinder extends Circle {
private double height;
public Cylinder(double radius, double height) {
super(radius);
this.height = height;
}
public Cylinder(double radius, double height, String color) {
super(radius, color);
this.height = height;
}
public double getVolume() {
return getArea() * height;
}
public double getHeight() {
return height;
} }
Test Cylinder
public class TestCylinder {
public static void main(String[] args) {
Cylinder c1 = new Cylinder(5.0, 10.0);
Cylinder c2 = new Cylinder(4.0, 12.0, "green");
Cylinder c3 = new Cylinder(6.0, 8.0, "blue");
// Display properties of Cylinder c1
System.out.println("Cylinder c1:");
System.out.println("Height: " + c1.getHeight());
System.out.println("Radius: " + c1.getRadius());
System.out.println("Color: " + c1.getColor());
System.out.println("Area: " + c1.getArea());
System.out.println("Volume: " + c1.getVolume());
// Display properties of Cylinder c2
System.out.println("\nCylinder c2:");
System.out.println("Height: " + c2.getHeight());
System.out.println("Radius: " + c2.getRadius());
System.out.println("Color: " + c2.getColor());
System.out.println("Area: " + c2.getArea());
System.out.println("Volume: " + c2.getVolume());
// Display properties of Cylinder c3
System.out.println("\nCylinder c3:");
System.out.println("Height: " + c3.getHeight());
System.out.println("Radius: " + c3.getRadius());
System.out.println("Color: " + c3.getColor());
System.out.println("Area: " + c3.getArea());
System.out.println("Volume: " + c3.getVolume());
}
}
Program 20: Create 2 object for class Student and Staff each. Use different functions and constructors to provide values to these objects and finally print the objects via toString().
Code:
Person
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String toString() {
return "Name: " + name;
} }
Student
class Student extends Person {
private int studentId;
public Student(String name, int studentId) {
super(name);
this.studentId = studentId;
}
public int getStudentId() {
return studentId;
}
public String toString() {
return super.toString() + ", Student ID: " + studentId;
} }
Staff
class Staff extends Person {
private String staffId;
public Staff(String name, String staffId) {
super(name);
this.staffId = staffId;
}
public String getStaffId() {
return staffId;
}
public String toString() {
return super.toString() + ", Staff ID: " + staffId;
} }
Main
public class Main {
public static void main(String[] args) {
// Create Student objects using constructors
Student student1 = new Student("Priyanshu Tiwari", 1008);
Student student2 = new Student("Alok Tiwari", 10008);
// Create Staff objects using constructors
Staff staff1 = new Staff("Riya Sapra", "S101");
Staff staff2 = new Staff("Sunil Sikka", "S102");
// Print the objects
System.out.println("Student 1: " + student1);
System.out.println("Student 2: " + student2);
System.out.println("Staff 1: " + staff1);
System.out.println("Staff 2: " + staff2);
}
}
Program 21: Create a class TestShape as code of class is given below and predict the output.
public class TestShape {
public static void main(String[] args) {
Rectangle s1 = new Rectangle("red", 4, 5);
System.out.println(s1);
System.out.println("Area is " + s1.getArea());
Triangle s2 = new Triangle("blue", 4, 5);
System.out.println(s2);
System.out.println("Area is " + s2.getArea());
}
}
List out the errors in above mentioned code if any. Correct them to run the program successfully.
Code:
Rectangle
public class Rectangle {
private String color;
private int width;
private int height;
public Rectangle(String color, int width, int height) {
this.color = color;
this.width = width;
this.height = height;
}
public double getArea() {
return width * height;
}
public String toString() {
return "Rectangle - Color: " + color + ", Width: " + width + ", Height: " + height;
}
}
Triangle
public class Triangle {
private String color;
private int base;
private int height;
public Triangle(String color, int base, int height) {
this.color = color;
this.base = base;
this.height = height;
}
public double getArea() {
return 0.5 * base * height;
}
public String toString() {
return "Triangle - Color: " + color + ", Base: " + base + ", Height: " + height;
}
}
TestShape
public class TestShape {
public static void main(String[] args) {
Rectangle s1 = new Rectangle("red", 4, 5);
System.out.println(s1);
System.out.println("Area is " + s1.getArea());
Triangle s2 = new Triangle("blue", 4, 5);
System.out.println(s2);
System.out.println("Area is " + s2.getArea());
}
}
Program 22: Re-write the abstract superclass Shape into an interface, containing only abstract methods, as follows:
Create a class TestShape as code of class is given below and predict the output.
public class TestShape {
public static void main(String[] args) {
Rectangle s1 = new Rectangle("red", 4, 5);
System.out.println(s1);
System.out.println("Area is " + s1.getArea());
Triangle s2 = new Triangle("blue", 4, 5);
System.out.println(s2);
System.out.println("Area is " + s2.getArea());
}
List out the errors in above mentioned code if any. Correct them to run the program successfully.
Code:
Interface
interface Shape {
double getArea();
}
Rectangle
public class Rectangle {
private String color;
private int width;
private int height;
public Rectangle(String color, int width, int height) {
this.color = color;
this.width = width;
this.height = height;
}
public double getArea() {
return width * height;
}
public String toString() {
return "Rectangle - Color: " + color + ", Width: " + width + ", Height: " + height;
}
}
Triangle
public class Triangle {
private String color;
private int base;
private int height;
public Triangle(String color, int base, int height) {
this.color = color;
this.base = base;
this.height = height;
}
public double getArea() {
return 0.5 * base * height;
}
public String toString() {
return "Triangle - Color: " + color + ", Base: " + base + ", Height: " + height;
}
}
TestShape
public class TestShape {
public static void main(String[] args) {
Rectangle s1 = new Rectangle("red", 4, 5);
System.out.println(s1);
System.out.println("Area is " + s1.getArea());
Triangle s2 = new Triangle("blue", 4, 5);
System.out.println(s2);
System.out.println("Area is " + s2.getArea());
}
}
Program 23: WAP to showcase the possible use of this keyword.
Code:
public class ThisExample { private int value = 10;
public void demonstrateVariableConflict() { int value = 20;
System.out.println("Local value: " + value);
System.out.println("Member variable (using this): " + this.value);
}
public ThisExample() { this(5);
}
public ThisExample(int value) { this.value = value;
System.out.println("Value initialized to: " + value);
}
public void printValue() {
System.out.println("Current object value: " + this.value);
}
public void modifyValue(int addToValue) { this.value += addToValue;
System.out.println("Value after modification: " + this.value);
}
public static void main(String[] args) { ThisExample obj = new ThisExample();
obj.demonstrateVariableConflict();
obj.printValue(); obj.modifyValue(15);
}
}
Program 24: WAP to showcase the possible use of super keywords.
Code:
Animal
public class Animal {
String name;
// Constructor
public Animal(String name) {
this.name = name;
}
// Method with public access modifier
public void eat() {
System.out.println(name + " is eating.");
}
}
Dog
public class Dog extends Animal {
String breed;
// Constructor
public Dog(String name, String breed) {
super(name); // Call superclass constructor
this.breed = breed;
}
// Method overriding with public access modifier
@Override
public void eat() {
super.eat(); // Call superclass method
System.out.println(name + " is eating dog food.");
}
// Additional method with public access modifier
public void bark() {
System.out.println(name + " is barking.");
}
}
Main
public class Main {
public static void main(String[] args) {
// Create a Dog object
Dog myDog = new Dog("Buddy", "Labrador");
// Call superclass method using super
myDog.eat();
// Call subclass method
myDog.bark();
}
}
Program 25: WAP to showcase the possible use of final keyword.
Code:
Circle
// Final variable
public class Circle {
final double PI = 3.14159;
double radius;
public Circle(double radius) {
this.radius = radius;
}
// Method with public access modifier
public double getArea() {
return PI * radius * radius;
}
}
Parent
// Final method
public class Parent {
public void display() {
System.out.println("Parent class method");
}
public final void finalDisplay() {
System.out.println("Final method in Parent class (Priyanshu Tiwari)");
}
}
Child
// Attempting to override final method will result in a compilation error
public class Child extends Parent {
// void finalDisplay() { }
}
Final Class
// Final class
final class FinalClass {
// Cannot be extended
}
Program 26: Create a package with two java files. Access these classes in another java file by importing the java file.
Code:
Directory Structure
D:\Semester 2/
│
└── Java/
├── mypackage/
│ ├── MyClass1.java
│ └── MyClass2.java
└── Main.java
MyClass1
package mypackage;
public class MyClass1 {
public void method1() {
System.out.println("Method 1 from MyClass1");
}
}
MyClass2
package mypackage;
public class MyClass2 {
public void method2() {
System.out.println("Method 2 from MyClass2");
}
}
Main
import mypackage.MyClass1;
import mypackage.MyClass2;
public class Main {
public static void main(String[] args) {
MyClass1 obj1 = new MyClass1();
obj1.method1();
MyClass2 obj2 = new MyClass2();
obj2.method2();
}
}
Program 27: Catch an Arithmetic Exception using try catch block.
Code:
public class Main {
public static void main(String[] args) {
try {
int result = divide(20, 5); // Attempt to divide by zero
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static int divide(int dividend, int divisor) {
return dividend / divisor;
}
}
Program 28: Create a class Student with attributes roll no, name, age, and course. Initilize values through parameterized constructor. If age of the student is not in between 15 and 21 then generate user-defined exception “AgeNotWithinRangeException”.
Code:
Student
import java.util.*;
public class Student {
private int rollNo;
private String name;
private int age;
private String course;
// Parameterized constructor with age validation
public Student(int rollNo, String name, int age, String course) throws AgeNotWithinRangeException {
this.rollNo = rollNo;
this.name = name;
if (age < 15 || age > 21) {
throw new AgeNotWithinRangeException("Age must be between 15 and 21.");
}
this.age = age;
this.course = course;
}
// Getters and setters
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) throws AgeNotWithinRangeException {
if (age < 15 || age > 21) {
throw new AgeNotWithinRangeException("Age must be between 15 and 21.");
}
this.age = age;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
@Override
public String toString() {
return "Student{" +
"rollNo=" + rollNo +
", name='" + name + '\'' +
", age=" + age +
", course='" + course + '\'' +
'}';
}
}
Age Not Within Range Exception
// Custom exception class
public class AgeNotWithinRangeException extends Exception {
public AgeNotWithinRangeException(String message) {
super(message);
}
}
Main
public class Main {
public static void main(String[] args) {
try {
// Create a student object with valid age
Student student1 = new Student(108, "Priyanshu", 18, "Computer Science");
System.out.println("Student 1: " + student1);
// Attempt to create a student object with invalid age
Student student2 = new Student(102, "Alok", 22, "Mathematics");
System.out.println("Student 2: " + student2);
} catch (AgeNotWithinRangeException e) {
// Catch and handle AgeNotWithinRangeException
System.out.println("Exception: " + e.getMessage());
}
} }
Output:
Program 29: Define a class MyDate with members day, month, year. Define default and parameterized constructors. Accept values from the command line and create a date object. Throw user defined – “InvalidDayException” or InvalidMonthException” if the day and month are invalid. If the date is valid display message “valid date”
Code:
// Custom exception for invalid day
class InvalidDayException extends Exception {
public InvalidDayException(String message) {
super(message);
}
}
// Custom exception for invalid month
class InvalidMonthException extends Exception {
public InvalidMonthException(String message) {
super(message);
}
}
public class MyDate {
private int day;
private int month;
private int year;
// Default constructor
public MyDate() {
this.day = 1;
this.month = 1;
this.year = 2000;
}
// Parameterized constructor
public MyDate(int day, int month, int year) throws InvalidDayException, InvalidMonthException {
if (!isValidMonth(month)) {
throw new InvalidMonthException("Invalid month: " + month);
}
this.month = month;
if (!isValidDay(day, month, year)) {
throw new InvalidDayException("Invalid day: " + day);
}
this.day = day;
this.year = year;
}
// Method to validate month
private boolean isValidMonth(int month) {
return month >= 1 && month <= 12;
}
// Method to validate day
private boolean isValidDay(int day, int month, int year) {
if (day < 1 || day > 31) {
return false;
}
if (month == 4 || month == 6 || month == 9 || month == 11) {
return day <= 30;
}
if (month == 2) {
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
return day <= 29;
} else {
return day <= 28;
}
}
return true;
}
// Method to display date
public void displayDate() {
System.out.println("Valid date: " + day + "/" + month + "/" + year);
}
public static void main(String[] args) {
try {
// Parse command line arguments
int day = Integer.parseInt(args[0]);
int month = Integer.parseInt(args[1]);
int year = Integer.parseInt(args[2]);
// Create MyDate object
MyDate date = new MyDate(day, month, year);
date.displayDate();
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please provide numeric values for day, month, and year.");
} catch (InvalidDayException | InvalidMonthException e) {
System.out.println("Error: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: java MyDate <day> <month> <year>");
}
}
}
Program 30: Write a program in Java that will create two threads namely thread1 and Thread2 using Thread Class that will print the numbers from 1 to 5.
Code:
Thread1
class Thread1 extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread1: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
} } } }
Thread2
class Thread2 extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread2: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
} } }
Main
public class Main {
public static void main(String[] args) {
// Create threads
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();
// Start threads
thread1.start();
thread2.start();
}
}
Comments
Post a Comment