Java Assignment-1
Kushal Kamlikar 210303105038
Lab Sheet 1(Based on Encapsulation)
1-Design a class Circle having radius(type float) as a instance
variable and make following member methods
a) Zero argument and parameterized constructors
b) Override String toString() method return radius of Circle object
c) Override boolean equals(Object object) method to check that
two circle
object are same or not.
d) Write method that will return area of Circle(no argument)
e) Write method that will take one Circle object as argument and
return its area .
Code –
class Circle {
private float radius;
public Circle() {}
public Circle(float radius) {
this.radius = radius;
}
@Override
public String toString() {
return "Radius: " + radius;
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
Circle other = (Circle) obj;
return this.radius == other.radius;
}
public float getArea() {
return (float) (Math.PI * radius * radius);
}
public float getArea(Circle circle) {
return (float) (Math.PI * circle.radius * circle.radius);
}
public static void main(String[] args) {
Circle c1 = new Circle(15);
System.out.println(c1.toString());
System.out.println("Area: " + c1.getArea());
Circle c2 = new Circle(9);
System.out.println(c2.toString());
System.out.println("Area: " + c1.getArea(c2));
System.out.println("Circles are equal: " + c1.equals(c2));
}
}
Output –
2- Design a class Point with two double x and y as instance
variable such that object of this class will represent a point of
coordinate system and make following member methods.
a) Zero argument and parameterized constructors
b) Write a method that will take one Point as argument and print
its quadrant or lies on X-axis or Y-axis or origin
c) Write a method that will take two Point as a argument and
return center point of these points
d) Write a method that will take two Point as a argument and
return distance between these points
e) Write a method that will take three Point as a argument and
return 1 if they are in straight line otherwise return 0
f) Override String toString() to return values of Point
Code –
class Point {
double x;
double y;
Point() {
x = 0;
y = 0;
}
Point(double x, double y) {
this.x = x;
this.y = y;
}
void findQuadrantOrAxis(Point p) {
if (p.x == 0 && p.y == 0) {
System.out.println("Point lies on the origin.");
} else if (p.x == 0) {
System.out.println("Point lies on the Y-axis.");
} else if (p.y == 0) {
System.out.println("Point lies on the X-axis.");
} else if (p.x > 0 && p.y > 0) {
System.out.println("Point lies in the first quadrant.");
} else if (p.x < 0 && p.y > 0) {
System.out.println("Point lies in the second quadrant.");
} else if (p.x < 0 && p.y < 0) {
System.out.println("Point lies in the third quadrant.");
} else {
System.out.println("Point lies in the fourth quadrant.");
}
}
Point findCenterPoint(Point p1, Point p2) {
double centerX = (p1.x + p2.x) / 2;
double centerY = (p1.y + p2.y) / 2;
return new Point(centerX, centerY);
}
double findDistance(Point p1, Point p2) {
double distance = Math.sqrt(Math.pow((p2.x - p1.x), 2) +
Math.pow((p2.y - p1.y), 2));
return distance;
}
int checkStraightLine(Point p1, Point p2, Point p3) {
double slope1 = (p2.y - p1.y) / (p2.x - p1.x);
double slope2 = (p3.y - p2.y) / (p3.x - p2.x);
if (slope1 == slope2) {
return 1;
} else {
return 0;
}
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
public static void main(String[] args) {
Point p1 = new Point(2, 3);
Point p2 = new Point(-2, 4);
Point p3 = new Point(0, 0);
p1.findQuadrantOrAxis(p1);
System.out.println(p2.findCenterPoint(p1,p2));
System.out.println(p3.findDistance(p1,p3));
System.out.println(p1.checkStraightLine(p1,p2,p3));
}
}
Output –
3. Write class Matrix that have one twoD array of size 3 by 3as
instance variable and have following methods.
A. zero arguments and parameterized constructor
B. Write a method that will take two Matrix as argument and
return a Matrix by adding both Matrix.
C. Write a method that will take two Matrix as argument and
return a Matrix by subtracting both Matrix.
D. Write a method that will take two Matrix as argument and
return a Matrix by multiplying both Matrix.
Code –
import java.util.Arrays;
class Matrix {
int[][] twoD;
Matrix() {
twoD = new int[3][3];
}
Matrix(int[][] arr) {
twoD = arr;
}
public void print() {
for (int[] row : twoD) {
System.out.println(Arrays.toString(row));
}
}
public Matrix add(Matrix m1, Matrix m2) {
int[][] result = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = m1.twoD[i][j] + m2.twoD[i][j];
}
}
return new Matrix(result);
}
public Matrix subtract(Matrix m1, Matrix m2) {
int[][] result = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = m1.twoD[i][j] - m2.twoD[i][j];
}
}
return new Matrix(result);
}
public Matrix multiply(Matrix m1, Matrix m2) {
int[][] result = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = 0;
for (int k = 0; k < 3; k++) {
result[i][j] += m1.twoD[i][k] * m2.twoD[k][j];
}
}
}
return new Matrix(result);
}
public static void main(String[] args) {
int[][] arr1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] arr2 = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
Matrix m1 = new Matrix(arr1);
Matrix m2 = new Matrix(arr2);
System.out.println("Matrix 1: ");
m1.print();
System.out.println("Matrix 2: ");
m2.print();
System.out.println("Matrix 1 + Matrix 2: ");
Matrix m3 = m1.add(m1, m2);
m3.print();
System.out.println("Matrix 1 - Matrix 2: ");
Matrix m4 = m1.subtract(m1, m2);
m4.print();
System.out.println("Matrix 1 * Matrix 2: ");
Matrix m5 = m1.multiply(m1, m2);
m5.print();
}
}
Output –
4. Design a class Product with
productid,productname,productprice as instance variable And
make following members methods
a) Zero argument and parameterized constructors ,print method
b) Override String toString() to return values of Product into a
single string object
c) Write code for counting how many object of Product class
created using static block,initializer block,static variable
d) Write a static method that will return how many object created
Code –
class Product {
private int productId;
private String productName;
private double productPrice;
private static int count;
public Product() {
count++;
}
public Product(int productId, String productName, double
productPrice) {
this();
this.productId = productId;
this.productName = productName;
this.productPrice = productPrice;
}
static {
count = 0;
}
{
count++;
}
public void print() {
System.out.println("Product ID: " + productId);
System.out.println("Product Name: " + productName);
System.out.println("Product Price: " + productPrice);
}
@Override
public String toString() {
return "Product ID: " + productId + ", Product Name: " +
productName + ", Product Price: " + productPrice;
}
public static int getCount() {
return count;
}
public static void main(String[] args) {
Product p1 = new Product(101, "Product 1", 10.5);
Product p2 = new Product(102, "Product 2", 20.5);
Product p3 = new Product(103, "Product 3", 30.5);
System.out.println("Number of Product objects created: " +
Product.getCount());
}
}
Output –
5. Write a class Account that will account number, name of
account holder, balance as member data and have following
member function:
A. Zero argument and parameterized constructors ,print method
B. Write a method that will take one Account object and money as
argument and deposit money in this account.
C. Write a method that will take one Account and money as
argument and
withdraw money from this account. Give proper message if
balance is not
available.
D. Write a method that will take two Account and money as
argument and return an account having max balance.
Code –
class Account {
private int accountNumber;
private String accountHolderName;
private double balance;
public Account() {
}
public Account(int accountNumber, String accountHolderName, double
balance) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = balance;
}
public void print() {
System.out.println("Account Number: " + accountNumber);
System.out.println("Account Holder Name: " + accountHolderName);
System.out.println("Balance: " + balance);
}
public void deposit(double money) {
balance += money;
}
public void withdraw(double money) {
if (balance < money) {
System.out.println("Insufficient balance");
} else {
balance -= money;
}
}
public static Account getMaxBalanceAccount(Account account1, Account
account2) {
if (account1.balance > account2.balance) {
return account1;
} else {
return account2;
}
}
public static void main(String[] args) {
Account account1 = new Account(101, "John Doe", 1000.0);
Account account2 = new Account(102, "Jane Doe", 2000.0);
account1.print();
account2.print();
account1.deposit(500.0);
System.out.println("After depositing 500 in Account 1");
account1.print();
account1.withdraw(1500.0);
System.out.println("After withdrawing 1500 from Account 1");
account1.print();
Account maxBalanceAccount = Account.getMaxBalanceAccount(account1,
account2);
System.out.println("Account with maximum balance: ");
maxBalanceAccount.print();
}
}
Output –
Self Analysis Question:-
1- implementation of static method for retuning object of class
when all constructors are Declared as private
Code –
class Singleton {
private static Singleton instance;
private String data;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
singleton1.setData("Hello World");
System.out.println("Data for singleton1: " + singleton1.getData());
Singleton singleton2 = Singleton.getInstance();
System.out.println("Data for singleton2: " + singleton2.getData());
}
}
Output –
2- implementation of this keyword in case of constructor chaining
Code –
class Employee {
private int id;
private String name;
private double salary;
public Employee() {
this(0, "Unknown");
}
public Employee(int id, String name) {
this(id, name, 0.0);
}
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public static void main(String[] args) {
Employee employee1 = new Employee();
System.out.println("Employee1: " + employee1.getId() + " " +
employee1.getName() + " " + employee1.getSalary());
Employee employee2 = new Employee(101, "John");
System.out.println("Employee2: " + employee2.getId() + " " +
employee2.getName() + " " + employee2.getSalary());
Employee employee3 = new Employee(102, "Jane", 10000.0);
System.out.println("Employee3: " + employee3.getId() + " " +
employee3.getName() + " " + employee3.getSalary());
}
}
Output –
3- difference in between == operator and equals method of
Object class used with instances of class
Code –
class Person {
private int id;
private String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public static void main(String[] args) {
Person person1 = new Person(1, "John");
Person person2 = new Person(1, "John");
Person person3 = person1;
System.out.println("Using == operator:");
System.out.println("person1 and person2: " + (person1 == person2));
System.out.println("person1 and person3: " + (person1 == person3));
System.out.println("Using equals method:");
System.out.println("person1 and person2: " +
person1.equals(person2));
System.out.println("person1 and person3: " +
person1.equals(person3));
}
}
Output –
4- implementation of method overloading.
Code –
class Calculator {
public static void main(String[] args) {
System.out.println("Sum of two integers: " + add(2, 3));
System.out.println("Sum of three integers: " + add(2, 3, 4));
System.out.println("Sum of two doubles: " + add(2.1, 3.2));
}
public static int add(int a, int b) {
return a + b;
}
public static int add(int a, int b, int c) {
return a + b + c;
}
public static double add(double a, double b) {
return a + b;
}
}
Output –
5- call by value and call by reference
Code –
class Main {
public static void main(String[] args) {
int value = 10;
System.out.println("Before calling changeValueByValue method, value
= " + value);
changeValueByValue(value);
System.out.println("After calling changeValueByValue method, value
= " + value);
Data data = new Data(10);
System.out.println("Before calling changeValueByReference method,
data.value = " + data.value);
changeValueByReference(data);
System.out.println("After calling changeValueByReference method,
data.value = " + data.value);
}
public static void changeValueByValue(int value) {
value = 20;
}
public static void changeValueByReference(Data data) {
data.value = 20;
}
}
class Data {
int value;
public Data(int value) {
this.value = value;
}
}
Output –
6- implicit and explicit type casting.
Code –
class TypeCasting {
public static void main(String[] args) {
int x = 10;
long y = x;
System.out.println("Implicit type casting value of y: " + y);
double d = 100.04;
int i = (int) d;
System.out.println("Explicit type casting value of i: " + i);
}
}
Output –
Lab Sheet 2(Based on Inheritance)
1) write java code for following inheritance. Make constructors in
each class
and use super keyword to call constructors of super classes from
derived
class and use String toString() methods to return values of
respective objects Write code that will create object of all derived
class and call methods.
Code –
class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Animal [name=" + name + "]";
}
}
class Mammal extends Animal {
private int weight;
public Mammal(String name, int weight) {
super(name);
this.weight = weight;
}
public int getWeight() {
return weight;
}
@Override
public String toString() {
return "Mammal [name=" + getName() + ", weight=" + weight + "]";
}
}
class Dog extends Mammal {
private String breed;
public Dog(String name, int weight, String breed) {
super(name, weight);
this.breed = breed;
}
public String getBreed() {
return breed;
}
@Override
public String toString() {
return "Dog [name=" + getName() + ", weight=" + getWeight() + ",
breed=" + breed + "]";
}
}
class InheritanceExample {
public static void main(String[] args) {
Animal animal = new Animal("Lion");
System.out.println("Animal: " + animal.toString());
Mammal mammal = new Mammal("Elephant", 500);
System.out.println("Mammal: " + mammal.toString());
Dog dog = new Dog("Golden Retriever", 50, "Retriever");
System.out.println("Dog: " + dog.toString());
}
}
Output –
2:- write code for implementing concept of method overriding.
Code –
class Shape {
double area() {
return 0.0;
}
}
class Rectangle extends Shape {
double length;
double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
double area() {
return length * width;
}
}
class Triangle extends Shape {
double base;
double height;
Triangle(double base, double height) {
this.base = base;
this.height = height;
}
double area() {
return 0.5 * base * height;
}
}
class Overriding {
public static void main(String[] args) {
Shape rectangle = new Rectangle(10, 20);
System.out.println("Area of rectangle: " + rectangle.area());
Shape triangle = new Triangle(10, 20);
System.out.println("Area of triangle: " + triangle.area());
}
}
Output –
3:- use concept abstract class and abstract methods in q2
Code –
abstract class Shape1 {
abstract double area();
}
class Rectangle1 extends Shape {
double length;
double width;
Rectangle1(double length, double width) {
this.length = length;
this.width = width;
}
double area() {
return length * width;
}
}
class Triangle1 extends Shape {
double base;
double height;
Triangle1(double base, double height) {
this.base = base;
this.height = height;
}
double area() {
return 0.5 * base * height;
}
}
class AbstractClass {
public static void main(String[] args) {
Shape rectangle = new Rectangle(10, 20);
System.out.println("Area of rectangle: " + rectangle.area());
Shape triangle = new Triangle(10, 20);
System.out.println("Area of triangle: " + triangle.area());
}
}
Output –
4- write code to implement final key word in all aspects
(i) By using Final as variable:
Code –
import java.util.*;
class FinalVar {
public static void main(String[] args)
{
double r;
final double pi = 3.14;
double area;
Scanner sc=new Scanner(System.in);
System.out.println("Enter radius");
r=sc.nextDouble();
area=pi*r*r;
System.out.println("Area is"+area);
}
}
Output –
(ii) By using Final as method:
Code –
class FinalMethod {
final void Print()
{
System.out.println("Hello");
}
}
class A extends FinalMethod{
void display()
{
System.out.println("This is for method using final");
}
public static void main(String args[]){
A a= new A();
a.display();
}
}
Output –
(iii) By using Final as class:
Code –
final class Circle {
private int radius;
public Circle(int radius) {
this.radius = radius;
}
public int getRadius() {
return radius;
}
public double calculateArea() {
return Math.PI * radius * radius;
}
public static void main(String[] args) {
Circle circle = new Circle(5);
System.out.println("Radius of the circle: " +
circle.getRadius());
System.out.println("Area of the circle: " +
circle.calculateArea());
}
}
Output –
5- write code for use of finalize() methods
Code –
class FinalizeClass {
public static void main(String[] args)
{
FinalizeClass obj = new FinalizeClass();
System.out.println(obj.hashCode());
obj = null;
System.gc();
System.out.println("end of garbage collection");
}
protected void finalize()
{
System.out.println("finalize method called");
}
}
Output –
6- code for showing typecasting in between objects of super class
and derived class
Code –
class SuperClass{
public SuperClass(){
System.out.println("Constructor of the super class");
}
public void superMethod() {
System.out.println("Method of the super class ");
}
}
class Test extends SuperClass {
public Test() {
System.out.println("Constructor of the sub class");
}
public void subMethod() {
System.out.println("Method of the sub class ");
}
public static void main(String[] args) {
SuperClass sup = new Test();
Test obj = (Test) sup;
obj.superMethod();
obj.subMethod();
}
}
Output –
7- reference variable of super class can refer object of its derived
class. write code to implement this statement.
Code –
class Shape2 {
void draw() {
System.out.println("Drawing a Shape");
}
}
class Rectangle2 extends Shape2 {
void draw() {
System.out.println("Drawing a Rectangle");
}
}
class Triangle2 extends Shape2 {
void draw() {
System.out.println("Drawing a Triangle");
}
}
class ReferenceVariable {
public static void main(String[] args) {
Shape2 shape = new Rectangle2();
shape.draw();
shape = new Triangle2();
shape.draw();
}
}
Output –