JAVA

  

S.no

Date

 

Signature

1

15/1/2024

WAP to print your name in Java.

 

2

15/1/2024

WAP to add 2 numbers. Take Input (Via Command Prompt & Via Scanner Class).

 

3

15/1/2024

WAP to do addition, subtraction, multiplication and division by taking (Values for variables & Values via Scanner Class).

 

4

29/1/2024

WAP to calculate factorial of a number taken via Scanner Class.

 

5

29/1/2024

WAP to take 5 numbers as an input from the user and then calculate (Average of the number & Maximum and minimum among the numbers).

 

6

29/1/2024

WAP to take 2 numbers and a symbol (+, -, *, /, %) from user. Using Switch case statement, calculate the desired arithmetic operation.

 

7

5/2/2024

WAP that prompts the user to input a user and then output the number with the digits reversed.

 

8

5/2/2024

WAP to find the largest element in the array using sort function.

 

9

5/2/2024

WAP to multiply two arrays.

 

10

5/2/2024

WAP to create a String class that performs String methods (Equal, reverse the string, change case).

 

11

5/2/2024

WAP to check wether the substring input by user belongs to a pre-defined String object.

 

 

12

 

12/2/2024

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

 

 

13

 

12/2/2024

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.

 

14

12/2/2024

WAP to create a class Shape and use different parameterised constructors to create objects of different shapes:

 

 

15

 

19/2/2024

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.

 

16

19/2/2024

WAP to invoke current class method using this keyword. (this.display())

 


17

19/2/2024

WAP to invoke current class constructors. (this(10), this())

 

18

19/2/2024

Define a Student class (roll number, name, percentage). Define a default and parameterized constructor. Keep a count on objects created.

 


S.no

Date

 

Signature

 

19

 

26/2/2024

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.

 

 

20

4/3/2024

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

 

21

11/3/2024

Create a class TestShape as code of class is given below and predict the output.

 

22

18/3/2024

Re-write the abstract superclass Shape into an interface, containing only abstract methods, as follows:

 

23

1/4/2024

WAP to showcase the possible use of this keyword.

 

24

1/4/2024

WAP to showcase the possible use of super keyword.

 

25

1/4/2024

WAP to showcase the possible use of final keyword.

 

26

8/4/2024

Create a package with two java files. Access these classes in another java file by importing the java file.

 

27

8/4/2024

Catch an Arithmetic Exception using try catch block.

 

 

28

 

15/4/2024

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 e n e r a t e                             u s e r - d e fi e d                         e x c e p ti o “AgeNotWithinRangeException”.

 

 

29

 

22/4/2024

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   Invalid Day Exception” or InvalidMonthException” if the day and month are invalid. If the date is valid display message “valid date”

 

30

29/4/2024

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.

 


31

29/4/2024

Write a program in Java that will create two threads namely thread1 and Thread2 using Runnable interface that will print the alphabet from A to F.

 

32

29/4/2024

Implement a class that checks whether a given number is a prime using both the Thread class and Runnable interface.

 







Program 1: WAP to print your name in Java.

Code:

 

class Second

{

public static void main (String a[]){

// String name

String name= "Samdarsh Gaur"; System.out.println("My name is:" +name);

}

}




Program 2: WAP to add 2 numbers. Take Input



 (Via Command Prompt & Via Scanner Class).


Code:



import java.util.Scanner;


public class Arithmetic {


    public static void main(String[] args) {

        if (args.length >= 2) {

            // Command-line arguments method

            try {

                String str1 = args[0];

                String str2 = args[1];


                int num1 = Integer.parseInt(str1);

                int num2 = Integer.parseInt(str2);

                int sum = num1 + num2;


                System.out.println("The addition of the numbers provided in the command line is: " + sum);

            } catch (NumberFormatException e) {

                System.out.println("Please ensure that both command-line arguments are integers.");

            }

        } else {

            // Scanner input method

            try (Scanner sc = new Scanner(System.in)) {

                // Taking input from the user

                System.out.print("Enter the first number for calculation: ");

                int a = sc.nextInt();


                System.out.print("Enter the second number for calculation: ");

                int b = sc.nextInt();


                // Calculation and output

                int sum = a + b;

                System.out.println("The addition of (a + b) is: " + sum);

            }

        }

    }



Program 3: WAP to do addition, subtraction, multiplication and division by taking (Values for variables & Values via Scanner Class 



Code:

import java.util.Scanner; public class arithmatic3 {

public static void main(String[] args) {

try (Scanner sc = new Scanner(System.in)){

// Input for the numbers System.out.print("Enter the first number: "); double num1 = sc.nextDouble(); System.out.print("Enter the second number: "); double num2 = sc.nextDouble();

// calculation

double sum = num1 + num2; System.out.println("Sum: " + sum); double difference = num1 - num2;

System.out.println("Difference: " + difference); double product = num1 * num2; System.out.println("Product: " + product);

// Division for Second Value cannot be Zero if (num2 != 0) {

double Division = num1 / num2; System.out.println("Divison: " + Division);

} else {

System.out.println("Cannot divide by zero.");

 


(Values for variables)

 

}

}

}

}

(Values via Scanner Class)


import java.util.Scanner; public class Arithmatic4{

public static void main(String arg[])

{

try (Scanner sc = new Scanner(System.in)) {

//Taking Input from the user

System.out.println("Enter the first number for calculation: "); int a= sc.nextInt();

System.out.println("Enter the second number for calculation: "); int b= sc.nextInt();

// Calculation & output

int c= a+b;

System.out.println("Addition of (a+b) is: "+c); int d= a-b;

System.out.println("Subtraction of (a-b) is: "+d); int e= a*b;

System.out.println("Multiplication of (a*b) is: "+e); int f= a/b;

System.out.println("Divison of (a/b) is: "+f); int g= a%b;

System.out.println("Factorial of (a%b) is: "+g); } } }




Program 4: WAP to calculate factorial of a number taken via Scanner Class.

Code:
import java.util.Scanner; public class Factorial {
public static void main(String[] args) {
try ( Scanner scanner = new Scanner(System.in)){
// Input number
System.out.print("Enter a number to calculate its factorial: "); int number = scanner.nextInt();
// Calculate factorial
long factorial = calculateFactorial(number);
// Output Number
System.out.println("Factorial of " + number + " is: " + factorial);
}
}
// Calculate factorial
private static long calculateFactorial(int n) { if (n == 0 || n == 1) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
}





Program 5: WAP to take 5 numbers as an input from the user and then calculate (Average of the number & Maximum and minimum among the numbers).


import java.util.Scanner; public class Average {
public static void main(String[] a) {
try (Scanner scanner = new Scanner(System.in)){
// Input for 5 numbers int sum = 0;
for (int i = 1; i <= 5; i++)
{ System.out.print("Enter number " + i + ": "); int number = scanner.nextInt();
sum += number;
}
// Calculate average int average = sum / 5;
// Output
System.out.println("Average of the 5 numbers is: " + average);
}
}
}
(Maximum and minimum among the numbers)
import java.util.Scanner; public class Maxmin {
public static void main(String[] a) {
try (Scanner scanner = new Scanner(System.in))
{ int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE;
// Input for 5 numbers for (int i = 1; i <= 5; i++) {
System.out.print("Enter number " + i + ": "); int num = scanner.nextInt();
// Update max and min if (num > max) {
max = num;

}
if (num < min)
{ min = num;
}
}
// Output
System.out.println("Maximum number: " + max); System.out.println("Minimum number: " + min);
}
}
}



Program 6: WAP to take 2 numbers and a symbol (+, -, *, /, %) from user. Using Switch case statement, calculate the desired arithmetic operation.

Code:
import java.util.Scanner; public class Switchcase {
public static void main(String[] a) {
try (Scanner scanner = new Scanner(System.in)){
// Input Number and symbols System.out.print("Enter the first number: "); int num1 = scanner.nextInt(); System.out.print("Enter the second number: "); int num2 = scanner.nextInt();
System.out.print("Enter the arithmetic operation (+, -, *, /, %): "); char operator = scanner.next().charAt(0);
// Arithmetic Operation using switch case statement int result;
switch (operator)
{ case '+':
result = num1 + num2; System.out.println("Result: " + result); break;
case '-':
result = num1 - num2; System.out.println("Result: " + result); break;
case '*':
result = num1 * num2; System.out.println("Result: " + result); break;
case '/':
// Check for division by zero if (num2 != 0) {
result = num1 / num2; System.out.println("Result: " + result);
} else {
System.out.println("Cannot divide by zero.");
}
break; case '%':
// Check for division by zero if (num2 != 0) {
result = num1 % num2; System.out.println("Result: " + result);
} else {

System.out.println("Cannot calculate remainder with zero divisor.");
}
break; default:
System.out.println("Invalid operator. Please enter a valid arithmetic operator.");
}
}
}
}


Program 7: WAP that prompts the user to input a user and then output the number with the digits reversed.


import java.util.Scanner;
public class Reversed_Number { public static void main(String[] args)
{ Scanner s = new Scanner(System.in); System.out.println("Enter a number: "); int user_Input = s.nextInt();
String str1= String.valueOf(user_Input); for(int i=str1.length()-1;i>=0;i--){
System.out.print(str1.charAt(i));
}
}
}


Program 8: WAP to find the largest element in the array using sort function.

Code:

Code:
import java.util.Arrays;

public class UsingSortFunction {
public static void main(String[] args) { int [] arr = {20,54,982,-1,29,19,-10};
System.out.println("THE ORIGINAL ARRAY IS: "); for(int num: arr){
System.out.print(num +" ");
}
System.out.println("\nTHE SORTED ARRAY IS: "); Arrays.sort(arr);
for(int num: arr){ System.out.print(num + " ");
}
}
}




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();
    }
}



 Program 31: Write a program in Java that will create two threads namely thread1 and Thread2 using Runnable interface that will print the alphabet from A to F.





Code: 
Thread1
class Thread1 extends Thread {
    public void run() {
for (char c = 'A' ; c <= 'F'; c++) {
            System.out.println("Thread1: " + c);     
try {
                Thread.sleep(1000); // Sleep for 1 second
            } catch (InterruptedException e) {
                e.printStackTrace();
            }        }    }     }
Thread2
class Thread2 extends Thread {
    public void run() {
        for (char c = 'A' ; c <= 'F'; c++) {
            System.out.println("Thread1: " + c);
            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();
    }
}






Program 32



 

AIM:WAP to create a form with awt controls.

CODE:


import java.awt.*; import java.awt.event.*;

 

class frame1 extends Frame

{


frame1()

{


 

setLayout(null);

Label head=new Label("New Student Registeration Form"); head.setBounds(500,50,250,30);

this.add(head);


Label fName = new Label("Student First Name : "); fName.setBounds(50,150,150,30); this.add(fName);

TextField tf1=new TextField(30); tf1.setBounds(250,150,200,30); add(tf1);

Label lName = new Label("Student Last Name : "); lName.setBounds(50,200,150,30); this.add(lName);

TextField tf2=new TextField(30); tf2.setBounds(250,200,200,30); add(tf2);

Label Add = new Label("Email Address : "); Add.setBounds(50,250,150,30); this.add(Add);

TextField tf3=new TextField(30); tf3.setBounds(250,250,200,30); add(tf3);

Label cAdd = new Label("Confirm Email Address : "); cAdd.setBounds(50,300,150,30);

this.add(cAdd);

TextField tf4=new TextField(30); tf4.setBounds(250,300,200,30); add(tf4);

Label Pass = new Label("Password : "); Pass.setBounds(50,350,150,30); this.add(Pass);

TextField tf5=new TextField(30); tf5.setBounds(250,350,200,30); add(tf5);

Label cPass = new Label("Confirm Password : "); cPass.setBounds(50,400,150,30); this.add(cPass);

TextField tf6=new TextField(30); tf6.setBounds(250,400,200,30); add(tf6);

Label DOB = new Label("Date of Birth : "); DOB.setBounds(50,450,150,30);

this.add(DOB);

Choice c1 = new Choice();

c1.setBounds(250, 450, 75, 75); c1.add("Year");


c1.add("Item 4");

c1.add("Item 5"); add(c1);

 

Choice c2 = new Choice(); c2.setBounds(350, 450, 75, 75); c2.add("Month");

c2.add("Item 2");

c2.add("Item 3");

c2.add("Item 4");

c2.add("Item 5"); add(c2);

Choice c3 = new Choice(); c3.setBounds(450, 450, 75, 75); c3.add("Date");

c3.add("Item 2");

c3.add("Item 3");

c3.add("Item 4");

c3.add("Item 5"); add(c3);

Checkbox r1=new Checkbox("Male"); Checkbox r2=new Checkbox("Female"); r1.setBounds(250,500,100,30); r2.setBounds(350,500,100,30);

add(r1);

add(r2);

Label dept = new Label("Department : "); dept.setBounds(50,550,150,30); this.add(dept);

Checkbox r3=new Checkbox("Civil"); r3.setBounds(250,550,100,30); add(r3);

Checkbox r4=new Checkbox("Computer Science and Engineering"); r4.setBounds(250,580,100,30);

add(r4);

Checkbox r5=new Checkbox("Electrical"); r5.setBounds(250,610,100,30);

add(r5);

Checkbox r6=new Checkbox("Electronics and communication"); r6.setBounds(250,640,100,30);

add(r6);

Button bt=new Button("Submit"); bt.setBounds(250,700,70,30); add(bt);

Button bt1=new Button("Cancle"); bt1.setBounds(330,700,70,30); add(bt1);

Label date = new Label("Your date is Below "); date.setBounds(750,500,150,30); this.add(date);

TextField tf7=new TextField(30); tf7.setBounds(750,550,300,200); add(tf7);

this.addWindowListener(new WindowAdapter()

{

public void windowClosing(WindowEvent we)

{


 

 


System.exit(0);

}


 

}

}

public class MainFun

{

public static void main(String args[])

{

frame1 f1=new frame1(); f1.setVisible(true); f1.setSize(500,500);

}

}






 


Comments

Popular posts from this blog

BCA- Computer Fundamental Old Question Paper

BCA 1ST SEMESTER NOTES