0% found this document useful (0 votes)
31 views

Java 21 J22 J23

Uploaded by

sawantamruta39
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Java 21 J22 J23

Uploaded by

sawantamruta39
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Slip – 21

Q1) Q1) Define a class MyDate(Day, Month, year) with methods to accept and display a
MyDateobject. Accept date as dd,mm,yyyy. Throw user defined exception "InvalidDateException" if
the date is invalid.

Ans_

// Custom exception class for invalid date

class InvalidDateException extends Exception {

public InvalidDateException(String message) {

super(message);

// MyDate class with day, month, and year attributes

class MyDate {

private int day, month, year;

// Constructor to initialize MyDate

public MyDate(int day, int month, int year) throws InvalidDateException {

if (!isValidDate(day, month, year)) {

throw new InvalidDateException("Invalid Date: " + day + "/" + month + "/" + year);

this.day = day;

this.month = month;

this.year = year;

// Method to check if the date is valid

private boolean isValidDate(int day, int month, int year) {

if (month < 1 || month > 12) return false;

if (day < 1 || day > daysInMonth(month, year)) return false;

return true;

}
// Method to get the number of days in a month, considering leap years

private int daysInMonth(int month, int year) {

int[] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

if (month == 2 && isLeapYear(year)) return 29;

return days[month - 1];

// Method to check if the year is a leap year

private boolean isLeapYear(int year) {

return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

// Method to display the date

public void displayDate() {

System.out.println("Date: " + day + "/" + month + "/" + year);

// Main class to test MyDate

public class Main {

public static void main(String[] args) {

try {

MyDate date = new MyDate(29, 2, 2023); // Invalid date (not a leap year)

date.displayDate();

} catch (InvalidDateException e) {

System.out.println(e.getMessage());

}
Q2)

Q2) Create an employee class(id,name,deptname,salary). Define a default and parameterized


constructor. Use ‘this’ keyword to initialize instance variables. Keep a count of 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.

Ans

class Employee {

private int id;

private String name;

private String deptName;

private double salary;

private static int count = 0; // Static variable to keep track of object count

// Default constructor

public Employee() {

this(0, "Unknown", "Unknown", 0.0);

// Parameterized constructor

public Employee(int id, String name, String deptName, double salary) {

this.id = id;

this.name = name;

this.deptName = deptName;

this.salary = salary;

count++; // Increment the object count each time an object is created

displayCount(); // Display object count after creation

// Static method to display the current object count

public static void displayCount() {

System.out.println("Total objects created: " + count);

}
// Method to display the contents of the object

public void displayEmployee() {

System.out.println("ID: " + id + ", Name: " + name + ", Dept: " + deptName + ", Salary: " + salary);

// Main class to test Employee

public class Main {

public static void main(String[] args) {

Employee e1 = new Employee(101, "Alice", "HR", 50000);

e1.displayEmployee();

Employee e2 = new Employee(102, "Bob", "IT", 60000);

e2.displayEmployee();

Employee e3 = new Employee(103, "Charlie", "Finance", 55000);

e3.displayEmployee();

}
Slip -22

Q1) Q1) Write a program to create an abstract class named Shape that contains two integers and an
empty method named printArea(). Provide three classes named Rectangle, Triangle and Circle such
that each one of the classes extends the class Shape. Each one of the classes contain only the
method printArea() that prints the area of the given shape. (use method overriding).

Ans

// Abstract class Shape

abstract class Shape {

int dim1, dim2;

abstract void printArea(); // Abstract method for printing area

// Rectangle class extends Shape

class Rectangle extends Shape {

Rectangle(int length, int breadth) {

this.dim1 = length;

this.dim2 = breadth;

@Override

void printArea() {

System.out.println("Rectangle Area: " + (dim1 * dim2));

// Triangle class extends Shape

class Triangle extends Shape {

Triangle(int base, int height) {

this.dim1 = base;

this.dim2 = height;

@Override

void printArea() {
System.out.println("Triangle Area: " + (0.5 * dim1 * dim2));

// Circle class extends Shape

class Circle extends Shape {

private int radius;

Circle(int radius) {

this.radius = radius;

@Override

void printArea() {

System.out.println("Circle Area: " + (Math.PI * radius * radius));

// Main class to test the Shape hierarchy

public class Main {

public static void main(String[] args) {

Shape rect = new Rectangle(10, 5);

rect.printArea();

Shape tri = new Triangle(10, 5);

tri.printArea();

Shape cir = new Circle(7);

cir.printArea();

}
Q2) Write a program that handles all mouse events and shows the event name at the center of the
Window, red in color when a mouse event is fired. (Use adapter classes)

Ans
Slip -23

Q1) Q1) 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 an object in main.Use command line arguments to pass a
value to the Object

Ans

// Define the MyNumber class

class MyNumber {

// Private data member to hold the integer value

private int number;

// Default constructor initializes number to 0

public MyNumber() {

this.number = 0; // Use 'this' to refer to the current object's member

// Parameterized constructor to initialize number with a given value

public MyNumber(int number) {

this.number = number; // Use 'this' to differentiate between parameter and member

// Method to check if the number is negative

public boolean isNegative() {

return number < 0;

// Method to check if the number is positive

public boolean isPositive() {

return number > 0;

}
// Method to check if the number is zero

public boolean isZero() {

return number == 0;

// Method to check if the number is odd

public boolean isOdd() {

return number % 2 != 0; // Odd if remainder when divided by 2 is not 0

// Method to check if the number is even

public boolean isEven() {

return number % 2 == 0; // Even if remainder when divided by 2 is 0

// Main method to create an object and demonstrate functionality

public static void main(String[] args) {

// Check if command line argument is provided

if (args.length == 0) {

System.out.println("Please pass a number as a command line argument.");

return; // Exit if no argument

// Parse the command line argument to an integer

int inputNumber;

try {

inputNumber = Integer.parseInt(args[0]); // Convert string to integer

} catch (NumberFormatException e) {

System.out.println("Invalid input. Please enter a valid integer.");

return; // Exit if the input is not a valid integer


}

// Create an object of MyNumber using the parameterized constructor

MyNumber myNum = new MyNumber(inputNumber);

// Display the properties of the number

System.out.println("Number: " + inputNumber);

System.out.println("Is Negative? " + myNum.isNegative());

System.out.println("Is Positive? " + myNum.isPositive());

System.out.println("Is Zero? " + myNum.isZero());

System.out.println("Is Odd? " + myNum.isOdd());

System.out.println("Is Even? " + myNum.isEven());

Q2) Write a simple currency converter, as shown in the figure. User can enter the amount of
"Singapore Dollars", "US Dollars", or "Euros", in floating-point number. The converted values shall be
displayed to 2 decimal places. Assume that 1 USD = 1.41 SGD, 1 USD = 0.92 Euro, 1 SGD = 0.65 Euro

Ans ->

import java.util.Scanner;

public class CurrencyConverter {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Displaying conversion options

System.out.println("Currency Converter");

System.out.println("1. Singapore Dollars (SGD)");

System.out.println("2. US Dollars (USD)");

System.out.println("3. Euros (EUR)");

System.out.print("Choose the currency to convert from (1-3): ");


int choice = scanner.nextInt();

System.out.print("Enter the amount: ");

float amount = scanner.nextFloat();

switch (choice) {

case 1: // SGD to USD and EUR

float usdFromSgd = amount / 1.41f; // Convert SGD to USD

float euroFromSgd = amount * 0.65f; // Convert SGD to Euro

System.out.printf("%.2f SGD = %.2f USD\n", amount, usdFromSgd);

System.out.printf("%.2f SGD = %.2f EUR\n", amount, euroFromSgd);

break;

case 2: // USD to SGD and EUR

float sgdFromUsd = amount * 1.41f; // Convert USD to SGD

float euroFromUsd = amount * 0.92f; // Convert USD to Euro

System.out.printf("%.2f USD = %.2f SGD\n", amount, sgdFromUsd);

System.out.printf("%.2f USD = %.2f EUR\n", amount, euroFromUsd);

break;

case 3: // EUR to SGD and USD

float sgdFromEuro = amount / 0.65f; // Convert Euro to SGD

float usdFromEuro = amount / 0.92f; // Convert Euro to USD

System.out.printf("%.2f EUR = %.2f SGD\n", amount, sgdFromEuro);

System.out.printf("%.2f EUR = %.2f USD\n", amount, usdFromEuro);

break;

default:

System.out.println("Invalid choice. Please select a valid option.");

scanner.close(); // Close the scanner


}

Out put:-

Currency Converter

1. Singapore Dollars (SGD)

2. US Dollars (USD)

3. Euros (EUR)

Choose the currency to convert from (1-3): 3

Enter the amount: 100

100.00 EUR = 153.85 SGD

100.00 EUR = 108.70 USD

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy