0% found this document useful (0 votes)
2 views37 pages

Java Assignment 22ad014

The document outlines various Java class implementations, including BankAccount, Student, Rectangle, Book, Vehicle, and Person, each with specific attributes and methods. It demonstrates object creation, method usage, and output for each class, showcasing functionalities like deposit/withdraw for bank accounts, grade calculation for students, area/perimeter calculations for rectangles, and book comparisons. Additionally, it includes a library catalog and shape representation, highlighting the versatility of Java in object-oriented programming.

Uploaded by

baditya985
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)
2 views37 pages

Java Assignment 22ad014

The document outlines various Java class implementations, including BankAccount, Student, Rectangle, Book, Vehicle, and Person, each with specific attributes and methods. It demonstrates object creation, method usage, and output for each class, showcasing functionalities like deposit/withdraw for bank accounts, grade calculation for students, area/perimeter calculations for rectangles, and book comparisons. Additionally, it includes a library catalog and shape representation, highlighting the versatility of Java in object-oriented programming.

Uploaded by

baditya985
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/ 37

ASSIGNMENT-JAVA BALA ADTYA J

22AD014

CLASS
1. Define a Java class named BankAccount that represents a simple bank account.
The class should have
instance variables for account number, account holder's name, and account
balance. Include methods to
deposit and withdraw funds, and a method to display the account details.

public class BankAccount {


// Instance variables
private int accountNumber;
private String accountHolderName;
private double accountBalance;

// Constructor
public BankAccount(int accountNumber, String accountHolderName, double
initialBalance) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.accountBalance = initialBalance;
}

// Method to deposit funds


public void deposit(double amount) {
if (amount > 0) {
accountBalance += amount;
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
System.out.println(amount + " deposited. New balance: " +
accountBalance);
} else {
System.out.println("Invalid amount for deposit.");
}
}

// Method to withdraw funds


public void withdraw(double amount) {
if (amount > 0 && amount <= accountBalance) {
accountBalance -= amount;
System.out.println(amount + " withdrawn. New balance: " +
accountBalance);
} else {
System.out.println("Insufficient funds or invalid amount for withdrawal.");
}
}

// Method to display account details


public void displayAccountDetails() {
System.out.println("Account Number: " + accountNumber);
System.out.println("Account Holder: " + accountHolderName);
System.out.println("Account Balance: " + accountBalance);
}
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
public static void main(String[] args) {
// Creating an instance of BankAccount
BankAccount account = new BankAccount(123456, "John Doe", 1000.0);

// Depositing and withdrawing funds


account.deposit(500.0);
account.withdraw(200.0);

// Displaying account details


account.displayAccountDetails();
}
}
Output:
500.0 deposited. New balance: 1500.0
200.0 withdrawn. New balance: 1300.0
Account Number: 123456
Account Holder: John Doe
Account Balance: 1300.0

2. Create a Java class called Student to represent a student's information. Include


attributes such as name,
age, grade, and a constructor to initialize these values. Implement a method that
calculates and returns
the student's grade based on a predefined grading scale.
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

public class Student {


// Instance variables
private String name;
private int age;
private double grade;

// Constructor
public Student(String name, int age, double grade) {
this.name = name;
this.age = age;
this.grade = grade;
}

// Method to calculate and return the student's grade


public String calculateGrade() {
if (grade >= 90) {
return "A";
} else if (grade >= 80) {
return "B";
} else if (grade >= 70) {
return "C";
} else if (grade >= 60) {
return "D";
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
} else {
return "F";
}
}

public static void main(String[] args) {


// Creating an instance of Student
Student student = new Student("Alice", 18, 85.5);

// Calculating and displaying the student's grade


String studentGrade = student.calculateGrade();
System.out.println(student.getName() + "'s grade: " + studentGrade);
}

// Getter for name


public String getName() {
return name;
}
}

Output:
Name: Alice
Age: 18
Grade: 87.5
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
Calculated Grade: B

3. Define a Java class named Rectangle that models a rectangle shape. Include
attributes for width and
height, and provide methods to calculate the area and perimeter of the rectangle.
Create multiple
instances of the class and demonstrate the usage of these methods.

public class Rectangle {


// Instance variables
private double width;
private double height;

// Constructor
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}

// Method to calculate the area of the rectangle


public double calculateArea() {
return width * height;
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
}

// Method to calculate the perimeter of the rectangle


public double calculatePerimeter() {
return 2 * (width + height);
}

public static void main(String[] args) {


// Creating instances of Rectangle
Rectangle rectangle1 = new Rectangle(5.0, 10.0);
Rectangle rectangle2 = new Rectangle(3.0, 7.0);

// Calculating and displaying area and perimeter for rectangle1


System.out.println("Rectangle 1:");
System.out.println("Area: " + rectangle1.calculateArea());
System.out.println("Perimeter: " + rectangle1.calculatePerimeter());
System.out.println();

// Calculating and displaying area and perimeter for rectangle2


System.out.println("Rectangle 2:");
System.out.println("Area: " + rectangle2.calculateArea());
System.out.println("Perimeter: " + rectangle2.calculatePerimeter());
}
}
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

Output:
Rectangle 1:
Area: 50.0
Perimeter: 30.0

Rectangle 2:
Area: 21.0
Perimeter: 20.0

4. Implement a Java class called Book to represent a book's details, including title,
author, year of
publication, and ISBN number. Create methods to display these details and
compare two books based
on their publication years.

public class Book {


// Instance variables
private String title;
private String author;
private int yearOfPublication;
private String isbn;

// Constructor
public Book(String title, String author, int yearOfPublication, String isbn) {
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
this.title = title;
this.author = author;
this.yearOfPublication = yearOfPublication;
this.isbn = isbn;
}

// Method to display book details


public void displayDetails() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Year of Publication: " + yearOfPublication);
System.out.println("ISBN: " + isbn);
}

// Method to compare two books based on publication years


public int compareByPublicationYear(Book otherBook) {
return Integer.compare(this.yearOfPublication, otherBook.yearOfPublication);
}

public static void main(String[] args) {


// Creating instances of Book
Book book1 = new Book("To Kill a Mockingbird", "Harper Lee", 1960, "978-0-
06-112008-4");
Book book2 = new Book("1984", "George Orwell", 1949, "978-0-452-28423-
4");
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

// Displaying details for each book


System.out.println("Book 1:");
book1.displayDetails();
System.out.println();

System.out.println("Book 2:");
book2.displayDetails();
System.out.println();

// Comparing books based on publication years


int comparison = book1.compareByPublicationYear(book2);
if (comparison > 0) {
System.out.println("Book 1 was published after Book 2.");
} else if (comparison < 0) {
System.out.println("Book 1 was published before Book 2.");
} else {
System.out.println("Both books were published in the same year.");
}
}
}

Output:
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
Book 1:
Title: To Kill a Mockingbird
Author: Harper Lee
Year of Publication: 1960
ISBN: 978-0-06-112008-4

Book 2:
Title: 1984
Author: George Orwell
Year of Publication: 1949
ISBN: 978-0-452-28423-4

Book 1 was published after Book 2.

5. Create a base class named Vehicle with attributes like make, model, and year.
Derive a subclass Car
from Vehicle with additional attributes specific to cars, such as the number of
doors and fuel efficiency.
Include methods to display the car's details and calculate fuel consumption.
// Base class: Vehicle
class Vehicle {
// Instance variables
protected String make;
protected String model;
protected int year;
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

// Constructor
public Vehicle(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}

// Method to display vehicle details


public void displayDetails() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}

// Subclass: Car (inherits from Vehicle)


class Car extends Vehicle {
// Additional attributes for cars
private int numDoors;
private double fuelEfficiency; // miles per gallon

// Constructor
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
public Car(String make, String model, int year, int numDoors, double
fuelEfficiency) {
super(make, model, year); // Calling base class constructor
this.numDoors = numDoors;
this.fuelEfficiency = fuelEfficiency;
}

// Method to display car details


public void displayCarDetails() {
super.displayDetails(); // Calling base class method
System.out.println("Number of Doors: " + numDoors);
System.out.println("Fuel Efficiency: " + fuelEfficiency + " miles per gallon");
}

// Method to calculate fuel consumption


public double calculateFuelConsumption(double distance) {
return distance / fuelEfficiency;
}
}

public class Main {


public static void main(String[] args) {
// Creating an instance of Car
Car car = new Car("Toyota", "Camry", 2022, 4, 30.5);
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

// Displaying car details


System.out.println("Car Details:");
car.displayCarDetails();
System.out.println();

// Calculating fuel consumption for a distance of 200 miles


double distance = 200.0;
double fuelConsumption = car.calculateFuelConsumption(distance);
System.out.println("Fuel Consumption for " + distance + " miles: " +
fuelConsumption + " gallons");
}
}

Output:

Car Details:
Make: Toyota
Model: Camry
Year: 2022
Number of Doors: 4
Fuel Efficiency: 30.5 miles per gallon

Fuel Consumption for 200.0 miles: 6.557377049180328 gallons


ASSIGNMENT-JAVA BALA ADTYA J
22AD014

Object creation
1. Write a Java program to define a Person class with attributes for name, age, and
occupation. Create
objects for different people and display their information.

public class Person {


// Instance variables
private String name;
private int age;
private String occupation;

// Constructor
public Person(String name, int age, String occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
}

// Method to display person's information


public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Occupation: " + occupation);
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
System.out.println();
}

public static void main(String[] args) {


// Creating objects for different people
Person person1 = new Person("John Doe", 30, "Engineer");
Person person2 = new Person("Jane Smith", 25, "Teacher");
Person person3 = new Person("Michael Johnson", 40, "Doctor");

// Displaying information for each person


System.out.println("Person 1:");
person1.displayInfo();

System.out.println("Person 2:");
person2.displayInfo();

System.out.println("Person 3:");
person3.displayInfo();
}
}

Output:
Person 1:
Name: John Doe
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
Age: 30
Occupation: Engineer

Person 2:
Name: Alice Smith
Age: 25
Occupation: Teacher

Person 3:
Name: Michael Johnson
Age: 45
Occupation: Doctor

3. Create a Java program for a library catalog. Define a Book class with attributes
for title, author, and
genre. Create objects for various books and display their details.

public class Book {


// Instance variables
private String title;
private String author;
private String genre;

// Constructor
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
public Book(String title, String author, String genre) {
this.title = title;
this.author = author;
this.genre = genre;
}

// Method to display book details


public void displayDetails() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Genre: " + genre);
}

public static void main(String[] args) {


// Creating objects for various books
Book book1 = new Book("To Kill a Mockingbird", "Harper Lee", "Fiction");
Book book2 = new Book("1984", "George Orwell", "Dystopian");
Book book3 = new Book("Pride and Prejudice", "Jane Austen", "Romance");

// Displaying details for each book


System.out.println("Book 1:");
book1.displayDetails();
System.out.println();
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
System.out.println("Book 2:");
book2.displayDetails();
System.out.println();

System.out.println("Book 3:");
book3.displayDetails();
}
}

Output:
Book 1:
Title: To Kill a Mockingbird
Author: Harper Lee
Genre: Fiction

Book 2:
Title: 1984
Author: George Orwell
Genre: Dystopian

Book 3:
Title: Pride and Prejudice
Author: Jane Austen
Genre: Romance
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

4. Implement a Java program to represent basic shapes. Define a Shape class with
attributes for type (e.g.,
circle, triangle) and properties related to that shape (e.g., radius, side lengths).
Create objects for
different shapes and calculate/display relevant properties.

public class Shape {


// Instance variables
private String type;
private double[] properties;

// Constructor
public Shape(String type, double... properties) {
this.type = type;
this.properties = properties;
}

// Method to calculate area for different shapes


public double calculateArea() {
if (type.equalsIgnoreCase("circle")) {
return Math.PI * properties[0] * properties[0]; // properties[0] is radius
} else if (type.equalsIgnoreCase("triangle")) {
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
double s = (properties[0] + properties[1] + properties[2]) / 2; //
semiperimeter
return Math.sqrt(s * (s - properties[0]) * (s - properties[1]) * (s -
properties[2]));
} else {
return -1; // Invalid shape
}
}

// Method to display shape details


public void displayDetails() {
System.out.println("Shape type: " + type);
for (int i = 0; i < properties.length; i++) {
System.out.println("Property " + (i + 1) + ": " + properties[i]);
}
System.out.println("Area: " + calculateArea());
}

public static void main(String[] args) {


// Creating objects for different shapes
Shape circle = new Shape("circle", 5.0); // Radius = 5.0
Shape triangle = new Shape("triangle", 3.0, 4.0, 5.0); // Side lengths = 3.0, 4.0,
5.0

// Displaying details for each shape


ASSIGNMENT-JAVA BALA ADTYA J
22AD014
System.out.println("Circle:");
circle.displayDetails();
System.out.println();

System.out.println("Triangle:");
triangle.displayDetails();
}
}

Output:
Circle:
Shape type: circle
Property 1: 5.0
Area: 78.53981633974483

Triangle:
Shape type: triangle
Property 1: 3.0
Property 2: 4.0
Property 3: 5.0
Area: 6.0
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
5. Write a Java program to manage employee records. Define an Employee class
with attributes for name,
role, and salary. Create objects for employees and implement methods to update
salary and display their
information.

public class Employee {


// Instance variables
private String name;
private String role;
private double salary;

// Constructor
public Employee(String name, String role, double salary) {
this.name = name;
this.role = role;
this.salary = salary;
}

// Method to update the salary


public void updateSalary(double newSalary) {
salary = newSalary;
}
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
// Method to display employee information
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Role: " + role);
System.out.println("Salary: " + salary);
}

public static void main(String[] args) {


// Creating employee objects
Employee employee1 = new Employee("John Doe", "Manager",
50000.0);
Employee employee2 = new Employee("Alice Smith", "Developer",
60000.0);

// Displaying information for each employee


System.out.println("Employee 1:");
employee1.displayInfo();
System.out.println();

System.out.println("Employee 2:");
employee2.displayInfo();
System.out.println();
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

// Updating salary for employee 1


employee1.updateSalary(55000.0);

// Displaying updated information for employee 1


System.out.println("Updated Employee 1:");
employee1.displayInfo();
}
}

Output:
Employee 1:
Name: John Doe
Role: Manager
Salary: 50000.0

Employee 2:
Name: Alice Smith
Role: Developer
Salary: 60000.0

Updated Employee 1:
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
Name: John Doe
Role: Manager
Salary: 55000.0

Default Constructor:
1. Create a Java program to define a class BankAccount with instance variables for
account number and
balance. Implement a default constructor that initializes the account number to a
default value and
balance to 0. Display the account details after initialization.

public class BankAccount {


// Instance variables
private int accountNumber;
private double balance;

// Default constructor
public BankAccount() {
accountNumber = 123456; // Default account number
balance = 0.0; // Default balance
}
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
// Method to display account details
public void displayAccountDetails() {
System.out.println("Account Number: " + accountNumber);
System.out.println("Balance: " + balance);
}

public static void main(String[] args) {


// Creating an instance of BankAccount using the default constructor
BankAccount account = new BankAccount();

// Displaying account details after initialization


account.displayAccountDetails();
}
}
OUTPUT:
Account Number: 123456
Balance: 0.0

2. Write a Java program that defines a class Student with instance variables for
name, age, and student ID.
Use a default constructor to initialize the student's information with default
values. Print the student's
details after initialization.
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
public class Student {
// Instance variables
private String name;
private int age;
private int studentID;

// Default constructor
public Student() {
name = "John Doe"; // Default name
age = 18; // Default age
studentID = 123456; // Default student ID
}

// Method to display student details


public void displayStudentDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Student ID: " + studentID);
}

public static void main(String[] args) {


// Creating an instance of Student using the default constructor
Student student = new Student();
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
// Displaying student details after initialization
student.displayStudentDetails();
}
}

Output: Name: John Doe


Age: 18
Student ID: 123456

3. Design a Java class Calculator with variables for two numbers and a result.
Create a default constructor
that sets the numbers to default values and initializes the result. Implement
methods for addition,
subtraction, multiplication, and division. Display the calculated results.

public class Calculator {


// Instance variables
private double num1;
private double num2;
private double result;

// Default constructor
public Calculator() {
num1 = 0.0; // Default value
num2 = 0.0; // Default value
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
result = 0.0; // Initialized result
}

// Method for addition


public void add() {
result = num1 + num2;
}

// Method for subtraction


public void subtract() {
result = num1 - num2;
}

// Method for multiplication


public void multiply() {
result = num1 * num2;
}

// Method for division


public void divide() {
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Cannot divide by zero.");
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
}
}

// Method to display the result


public void displayResult() {
System.out.println("Result: " + result);
}

public static void main(String[] args) {


// Creating an instance of Calculator
Calculator calculator = new Calculator();

// Performing calculations and displaying results


calculator.add();
System.out.print("Addition: ");
calculator.displayResult();

calculator.subtract();
System.out.print("Subtraction: ");
calculator.displayResult();

calculator.num1 = 10;
calculator.num2 = 5;
calculator.multiply();
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
System.out.print("Multiplication: ");
calculator.displayResult();

calculator.divide();
System.out.print("Division: ");
calculator.displayResult();
}
}

Output:
Addition: Result: 0.0
Subtraction: Result: 0.0
Multiplication: Result: 50.0
Division: Result: 2.0

4. Develop a Java class Person with attributes for name, age, and gender. Include a
default constructor that
sets default valuesfor these attributes. Create instances of the class and print out
the details of the person
objects.
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
public class Person {
// Instance variables
private String name;
private int age;
private String gender;

// Default constructor
public Person() {
name = "Unknown"; // Default name
age = 0; // Default age
gender = "Unknown"; // Default gender
}

// Method to display person details


public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Gender: " + gender);
}

public static void main(String[] args) {


// Creating instances of Person using the default constructor
Person person1 = new Person();
Person person2 = new Person();
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

// Displaying person details for each instance


System.out.println("Person 1:");
person1.displayDetails();
System.out.println();

System.out.println("Person 2:");
person2.displayDetails();
}
}

Output:
Person 1:
Name: Unknown
Age: 0
Gender: Unknown

Person 2:
Name: Unknown
Age: 0
Gender: Unknown
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
5. Build a Java class Vehicle with instance variables for make, model, and year.
Define a default
constructor that initializes the vehicle details to default values. Create objects of
the class and display
the vehicle information.

public class Vehicle {


// Instance variables
private String make;
private String model;
private int year;

// Default constructor
public Vehicle() {
make = "Unknown"; // Default make
model = "Unknown"; // Default model
year = 0; // Default year
}

// Method to display vehicle information


public void displayInfo() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
ASSIGNMENT-JAVA BALA ADTYA J
22AD014

public static void main(String[] args) {


// Creating instances of Vehicle using the default constructor
Vehicle vehicle1 = new Vehicle();
Vehicle vehicle2 = new Vehicle();

// Displaying vehicle information for each instance


System.out.println("Vehicle 1:");
vehicle1.displayInfo();
System.out.println();

System.out.println("Vehicle 2:");
vehicle2.displayInfo();
}
}

Output:
Vehicle 1:
Make: Unknown
Model: Unknown
Year: 0

Vehicle 2:
Make: Unknown
ASSIGNMENT-JAVA BALA ADTYA J
22AD014
Model: Unknown
Year: 0

You might also like