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

Java Assignments (1&2) : Assignment 1

The document contains code solutions in Java for 6 programming assignments. Assignment 1 contains code to find the maximum element in an array and to calculate the sum of a series. Assignment 2 contains code to sort an array using quicksort and to search for an element in an array. It also contains code for a menu driven stack implementation using a switch statement. The code solutions are accompanied by sample input/output examples.

Uploaded by

Nil Das
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)
270 views

Java Assignments (1&2) : Assignment 1

The document contains code solutions in Java for 6 programming assignments. Assignment 1 contains code to find the maximum element in an array and to calculate the sum of a series. Assignment 2 contains code to sort an array using quicksort and to search for an element in an array. It also contains code for a menu driven stack implementation using a switch statement. The code solutions are accompanied by sample input/output examples.

Uploaded by

Nil Das
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/ 46

 

 
 

JAVA ASSIGNMENTS (1&2) 


 
 
 
 
 
 
 
 
 
 
ASSIGNMENT 1 
Problem Statement 1:  
Write a java program to find the maximum in an array of integers.  

Code : 
import java.util.Scanner;
class FindMax{
public static void main(String[] args) {
FindMax max = new FindMax();
max.ExtractMax(max.input());
}

 

 

int[] input(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements : ");
int[] arr = new int[input.nextInt()];
System.out.println("Enter the elements : ");
for(int i = 0; i<arr.length; i++)
arr[i] = input.nextInt();
input.close();
return arr;
}
void ExtractMax(int[] arr){
int max = arr[0];
for(int i = 0; i < arr.length; i++){
if(arr[i]>max)
max = arr[i];
}
System.out.println("Max term is : " + max);
}
}

Output : 
PS F:\VSCode\Java\Class> java FindMax 
Enter the number of elements : 

Enter the elements : 
10 20 50 80 100 
Max term is : 100 
 

Problem Statement 2:  


Write a java program to find the sum of the series: 1+(1+2)+(1+2+3)+.......+(1+2+3+.....+n)  

Code : 
import java.util.Scanner;

 

class SumOfSeries{
void sum(int n){
int sum = 0;
for (int i = 1; i <= n; i++){
sum = sum + (i*(i+1))/2;;
}
System.out.println("Sum is : "+sum);
}
int input(){
System.out.println("Enter upto how many terms, the sum will be calculated : ");
Scanner input = new Scanner(System.in);
int term = input.nextInt();
input.close();
return term;
}
public static void main(String[] args) {
SumOfSeries obj= new SumOfSeries();
obj.sum(obj.input());
}
}
 

Output : 
PS F:\VSCode\Java\Class> java SumOfSeries 
Enter upto how many terms, the sum will be calculated : 

Sum is : 35 
 

Problem Statement 3:  


Write a java program to sort an array of integers where your program will accept the integers from : 
a. Command Line Arguments 
b. Keyboard inputs 

Code : 

 

import java.util.Scanner; 
 
public class QuickSort {  
 
int partition(int arr[], int low, int high) {  
int pivot = arr[high];   
int i = (low-1); 
for (int j=low; j<high; j++) {  
   
if (arr[j] <= pivot) {  
i++;  
int temp = arr[i];  
arr[i] = arr[j];  
arr[j] = temp;  
}  
}   
int temp = arr[i+1];  
arr[i+1] = arr[high];  
arr[high] = temp;  
  
return i+1;  
}  
void sort(int arr[], int low, int high) {  
if (low < high) {  
int pi = partition(arr, low, high);  
sort(arr, low, pi-1);  
sort(arr, pi+1, high);  
}  
}  
static void printArray(int arr[]) {  
int n = arr.length;  
for (int i=0; i<n; ++i)  

 

System.out.print(arr[i]+" ");  
System.out.println();  
}  
 
public static int[] inputArr() { 
Scanner sc = new Scanner(System.in); 
System.out.print("Enter length: "); 
int len = sc.nextInt(); 
int[] arr = new int[len]; 
 
for (int i = 0; i < len; i++) { 
arr[i] = sc.nextInt();   

return arr; 

public static int[] cliArr(String args[]) { 
int arr[] = new int[args.length]; 
int i = 0; 
for (String number : args) { 
arr[i++] = Integer.parseInt(number); 

return arr; 

public static void main(String args[]) { 
int arr[]; 
if (args.length > 0) { 
arr = cliArr(args); 
} else { 
arr = inputArr(); 

System.out.println("Unsorted array"); 
printArray(arr); 

 

int n = arr.length;  
  
QuickSort ob = new QuickSort();  
ob.sort(arr, 0, n-1);  
  
System.out.println("Sorted array");  
printArray(arr);  

}  
 

Output : 
PS F:\VSCode\Java\Assignment 2> java QuickSort 
Enter length: 5 
10 52 36 48 51 
Unsorted array 
10 52 36 48 51 
Sorted array 
10 36 48 51 52 
 

 
Problem Statement 4: 
Write a java program to search ​for a given element from an array of numbers.  

Code : 
import java.util.Scanner;
class SearchElement{
private Scanner input= new Scanner(System.in);
int[] input(){
System.out.println("Enter the number of elements : ");
int[] arr = new int[input.nextInt()];
System.out.println("Enter the elements : ");
for(int i = 0; i<arr.length; i++)

 

arr[i] = input.nextInt();
return arr;
}
void Find(int[] arr){
System.out.println("Enter which element do you want to find : ");
int target = input.nextInt();
for(int i = 0; i < arr.length; i++){
if(arr[i] == target){
System.out.println("Element is found at " + (i+1) + "th location.");
return;
}
}
System.out.println("Element not found.");
}
public static void main(String[] args) {
SearchElement obj = new SearchElement();
obj.Find(obj.input());
}
}
 

 
Output : 
PS F:\VSCode\Java\Class> java SearchElement 
Enter the number of elements : 

Enter the elements : 
10 20 30 40 50 
Enter which element do you want to find : 
40 
Element is found at 4th location. 
 

Problem Statement 5:  



 

Write a java program that accepts the radius​ of a circle and displays the options as follows : 
1. Find diameter ​of a circle (2 * radius) 
2. Find area ​of circle (Pi * radius * radius) 
3. Find circumference ​of circle (2 * Pi * radius)  
4. Exit Use switch statement ​to implement each option and display the corresponding output.  

Code : 
import java.util.Scanner;
class Circle{
void diameter(int r){
System.out.println("Diameter is : " + 2*r);
}
void area (int r){
System.out.println("Area is : "+ (3.14*r*r));
}
void circumference (int r){
System.out.println("Circumference is :" + (2*3.14*r));
}
public static void main(String[] args) {
System.out.println("Enter the radius of the circle: ");
Scanner input = new Scanner(System.in);
int r = input.nextInt();
System.out.println("Enter the option : ");
System.out.println("1. Diameter");
System.out.println("2. Area");
System.out.println("3. Circumference");
int choice = input.nextInt();
Circle obj = new Circle();
switch(choice){
case 1 : obj.diameter(r);
break;
case 2 : obj.area(r);
break;
case 3 : obj.circumference(r);

 

break;
default : System.out.println("Enter valid input.");
}
input.close();
}
}
 

Output : 
PS F:\VSCode\Java\Class> java Circle 
Enter the radius of the circle: 
50 
Enter the option : 
1. Diameter 
2. Area 
3. Circumference 

Diameter is : 100 
 

 
 
Problem Statement 6:  
Write a java program to implement Stack​ (Menu driven using switch statement)  

Code : 
import java.util.Scanner;
class Stack{
int size;
int [] arr;
int top;
public Stack(int size){
this.size = size;
arr = new int [size];

 

top = -1;
}
public void push(int value){
if (top == size - 1){
System.out.println("Stack is full");
return;
}
arr[++top] = value;
System.out.println(value +" is pushed successsfully.");
}
public void pop(){
if(top == -1){
System.out.println("Stack is empty");
return;
}
System.out.println(arr[top] + " is popped successfully.");
top = top -1;
}
public static void main(String[] args) {
System.out.println("Enter the size of the stack");
Scanner input = new Scanner(System.in);
int size = input.nextInt();
Stack stack = new Stack(size);

while (true){
System.out.println("1. Push\n2. Pop \n3. Show stack");
int choice = input.nextInt();
switch(choice){
case 1 : System.out.println("Enter the value to be pushed: ");
int value = input.nextInt();
stack.push(value);
break;
case 2 : stack.pop();
break;
10 
 

case 3 :System.out.println("Stack elements are: ");


for(int i = 0; i <= stack.top; i++)
System.out.println(stack.arr[(i)]);
break;
default: System.out.println("WRONG INPUT : TERMINATED");
return;
}
}
}
}import java.util.Scanner;
class Stack{
int size;
int [] arr;
int top;
public Stack(int size){
this.size = size;
arr = new int [size];
top = -1;
}
public void push(int value){
if (top == size - 1){
System.out.println("Stack is full");
return;
}
arr[++top] = value;
System.out.println(value +" is pushed successsfully.");
}
public void pop(){
if(top == -1){
System.out.println("Stack is empty");
return;
}
System.out.println(arr[top] + " is popped successfully.");
top = top -1;
11 
 

}
public static void main(String[] args) {
System.out.println("Enter the size of the stack");
Scanner input = new Scanner(System.in);
int size = input.nextInt();
Stack stack = new Stack(size);

while (true){
System.out.println("1. Push\n2. Pop \n3. Show stack");
int choice = input.nextInt();
switch(choice){
case 1 : System.out.println("Enter the value to be pushed: ");
int value = input.nextInt();
stack.push(value);
break;
case 2 : stack.pop();
break;
case 3 :System.out.println("Stack elements are: ");
for(int i = 0; i <= stack.top; i++)
System.out.println(stack.arr[(i)]);
break;
default: System.out.println("WRONG INPUT : TERMINATED");
return;
}
}
}
}
 

Output : 
PS F:\VSCode\Java\Class> java Stack 
Enter the size of the stack 

1. Push 
12 
 

2. Pop 
3. Show stack 

Enter the value to be pushed: 
10 
10 is pushed successfully. 
1. Push 
2. Pop 
3. Show stack 

Enter the value to be pushed: 
20 
20 is pushed successfully. 
1. Push 
2. Pop 
3. Show stack 

Enter the value to be pushed: 
30 
30 is pushed successfully. 
1. Push 
2. Pop 
3. Show stack 

Stack elements are: 
10 
20 
30 
 

Problem Statement 7:  


Write a java program to implement a Queue ​(Menu driven using switch statement)  
13 
 

Code : 
import java.util.Scanner;
class Queue{
int size;
int [] arr;
int top;
public Queue(int size){
this.size = size;
arr = new int [size];
top = -1;
}
public void push(int value){
if (top == size - 1){
System.out.println("Queue is full");
return;
}
arr[++top] = value;
System.out.println(value +" is pushed successsfully.");
}
public void pop(){
if(top == -1){
System.out.println("Queue is empty");
return;
}
System.out.println(arr[0] + " is popped successfully.");
for(int i = 1; i <=top; i++){
arr[i-1] = arr [i];
}
top = top - 1;
}
public static void main(String[] args) {
System.out.println("Enter the size of the Queue");
Scanner input = new Scanner(System.in);
int size = input.nextInt();
14 
 

Queue queue = new Queue(size);

while (true){
System.out.println("1. Push\n2. Pop \n3. Show Queue");
int choice = input.nextInt();
switch(choice){
case 1 : System.out.println("Enter the value to be pushed: ");
int value = input.nextInt();
queue.push(value);
break;
case 2 : queue.pop();
break;
case 3 :System.out.println("Queue elements are: ");
for(int i = 0; i <= queue.top; i++)
System.out.println(queue.arr[(i)]);
break;
default: System.out.println("WRONG INPUT : TERMINATED");
return;
}
}
}
}
 

Output : 
PS F:\VSCode\Java\Class> java Queue 
Enter the size of the Queue 

1. Push 
2. Pop 
3. Show Queue 

Enter the value to be pushed: 
10 
15 
 

10 is pushed successfully. 
1. Push 
2. Pop 
3. Show Queue 

Enter the value to be pushed: 
20 
20 is pushed successfully. 
1. Push 
2. Pop 
3. Show Queue 

Enter the value to be pushed: 
30 
30 is pushed successfully. 
1. Push 
2. Pop 
3. Show Queue 

10 is popped successfully. 
1. Push 
2. Pop 
3. Show Queue 

Queue elements are: 
20 
30 
 

Problem Statement 8:  


Java program that inputs a person’s name in the form of First Middle Last,​ and then prints it in form Last First M., 
​where “M” is a person's middle initial.  
16 
 

Code : 
import java.util.Scanner;
class Name{
public static void main(String[] args) {
System.out.println("Enter your name in 'First Middle Last' format :");
Scanner input = new Scanner(System.in);
String name = input.nextLine();
input.close();
String [] stringArr = name.split("\\ ");
System.out.println(stringArr[2] +" "+ stringArr[0] +" "+ stringArr[1].charAt(0));
}
}
 

Output : 
PS F:\VSCode\Java\Class> java Name 
Enter your name in 'First Middle Last' format : 
Prasanta Kumar Mondal 
Mondal Prasanta K 
 

 
Problem Statement 9:  
Define a class called fruit with the following attributes : 
a. Name of the fruit 
b. Single fruit or bunch fruit 
c. Price  
Define a suitable constructor​ and displayFruit() ​method that displays the values of all the attributes.  
Write a program that creates 2 objects of fruit class and display their attributes. 

Code : 
import java.util.Scanner;
class fruit{
String fruitname;
17 
 

float price;
boolean single = true;
boolean bunch = false;
public fruit(String fruitname, float price, boolean single){
this.fruitname = fruitname;
this.price = price;
this.single = single;
//System.out.println("Constructor called");
}
void displayFruit(){
System.out.println("Fruit name is: " + fruitname);
System.out.println("Price is : " + price);
if(single == true)
System.out.println("Fruit is single.");
else
System.out.println("Fruit is bunched.");
}
public static void main(String[] args) {
fruit obj1 = new fruit("Apple", 200, true);
obj1.displayFruit();
fruit obj2 = new fruit("Banana", 36, false);
obj2.displayFruit();
}
}
 

Output : 
PS F:\VSCode\Java\Class> java fruit 
Constructor called 
Fruit name is: Apple 
Price is : 200.0 
Fruit is single. 
Constructor called 
Fruit name is: Banana 
18 
 

Price is : 36.0 
Fruit is bunched. 
 

Problem Statement 10:  


Define a class called Employee with the following attributes: 
a. Employee Id - integer 
b. Gender - the value of gender must be M ​or F ​not Male or Female  
c. Employee Name - String  
Define a suitable method displayEmployeeDetails() method that displays the details of an employee.  
Now write another class containing main() ​method which will accept the details of employees from the keyboard 
and then display the details.  

Code : 
import java.util.Scanner;
class Emp{
String name;
int id;
char gender;
public Emp(String name, int id, char gender){
this.name = name;
this.id = id;
this.gender = gender;
}
void displayEmployeeDetails(){
System.out.println("Employee name : " + name);
System.out.println("Employee id : "+ id);
if(gender == 'M')
System.out.println("Gender : M");
else
System.out.println("Gender : F");
}
}
class Employee_input{
public static void main(String[] args) {
19 
 

Emp [] arr = new Emp[10];


Scanner input = new Scanner(System.in);
System.out.println("Enter 10 Employee name, Employee id and Employee gender respectively and hit
enter every time : ");
for(int i = 0; i< 10; i++){
String name = input.next();
int id = input.nextInt();
char gender = input.next().charAt(0);
arr[i]=new Emp(name, id, gender);
System.out.println("Enter again Name, ID, Gender : ");
}
for(int i = 0; i < 10; i++){
arr[i].displayEmployeeDetails();
}
input.close();
}
}
 

Output : 
PS F:\VSCode\Java\Assignment 1> java Employeeinput 
Enter 10 Employee name, Employee id and Employee gender respectively and hit enter every time : 
nil 


Enter again Name, ID, Gender : 
shouvik 


Enter again Name, ID, Gender : 
suporna 


Enter again Name, ID, Gender : 
20 
 

joydeep 


Enter again Name, ID, Gender : 
satadal 


Enter again Name, ID, Gender : 
srestha 


Enter again Name, ID, Gender : 
subha 


Enter again Name, ID, Gender : 
prabir 


Enter again Name, ID, Gender : 
susmita 


Enter again Name, ID, Gender : 
dilruba 
10 

Enter again Name, ID, Gender : 
Employee name : nil 
Employee id : 1 
Gender : M 
Employee name : shouvik 
21 
 

Employee id : 2 
Gender : M 
Employee name : suporna 
Employee id : 3 
Gender : F 
Employee name : joydeep 
Employee id : 4 
Gender : M 
Employee name : satadal 
Employee id : 5 
Gender : M 
Employee name : srestha 
Employee id : 6 
Gender : F 
Employee name : subha 
Employee id : 7 
Gender : M 
Employee name : prabir 
Employee id : 8 
Gender : M 
Employee name : susmita 
Employee id : 9 
Gender : F 
Employee name : dilruba 
Employee id : 10 
Gender : F 

 
Problem Statement 11:  
Create class student Student ​(Roll number, name, number of subjects, marks of each subject). No of subjects 
varies for each student. Write a parameterized constructor which initializes roll number, name and number of 
subjects and create the array of marks dynamically. Display details of all students with percentage and class 
obtained.  
22 
 

Code : 
import java.io.*;
class Student {
int rollno;
String name;
int number_of_subjects;
int mark[];

Student(int roll, String stud_name, int noofsub) throws IOException {


rollno = roll;
name = stud_name;
number_of_subjects = noofsub;
getMarks(noofsub);
}

public void getMarks(int nosub ) throws IOException{


mark=new int[nosub];
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
for (int i=0; i<nosub;i++)
{
System.out.println("Enter "+(i+1)+" Subject Marks.:=> ");
mark[i]=Integer.parseInt(br.readLine());
System.out.println("");
}

public void calculateMarks()


{
double percentage=0;
int tmarks=0;
for (int i=0;i<mark.length;i++)
{
tmarks+=mark[i];
23 
 

}
percentage=tmarks/number_of_subjects;
System.out.println("Roll Number :=> " + rollno);
System.out.println("Name Of Student is :=> "+name);
System.out.println("Number Of Subject :=> "+number_of_subjects);
System.out.println("Percentage Is :=> "+percentage);
}
}

class StudentDemo {
public static void main(String args[])throws IOException
{
int rno,no,nostud;
String name;
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
System.out.println("Enter How many Students:=> ");
nostud=Integer.parseInt(br.readLine());
Student s[]=new Student[nostud];

for(int i=0;i<nostud;i++)
{
System.out.println("Enter Roll Number:=> ");
rno=Integer.parseInt(br.readLine());
System.out.println("Enter Name:=> ");
name=br.readLine();
System.out.println("Enter No of Subject:=> ");
no=Integer.parseInt(br.readLine());
s[i]=new Student(rno,name,no);
}
for(int i=0;i<nostud;i++)
{
s[i].calculateMarks();
}
24 
 

}

Output : 
PS F:\VSCode\Java\Class> java StudentDemo 
Enter How many Students:=> 

Enter Roll Number:=> 
11 
Enter Name:=> 
Nil 
Enter No of Subject:=> 

Enter 1 Subject Marks.:=> 
50 
Enter 2 Subject Marks.:=> 
80 
Enter Roll Number:=> 
12 
Enter Name:=> 
Shouvik 
Enter No of Subject:=> 

Enter 1 Subject Marks.:=> 
30 
Enter 2 Subject Marks.:=> 
100 
Roll Number :=> 11 
Name Of Student is :=> Nil 
Number Of Subject :=> 2 
Percentage Is :=> 65.0 
Roll Number :=> 12 
25 
 

Name Of Student is :=> Shouvik 


Number Of Subject :=> 2 
Percentage Is :=> 65.0 
 

Problem Statement 12:  


Create a class Rectangle​. The class has two attributes, length ​and width​, each of which defaults to 0. It has 
methods that calculate the perimeter​ and area of the rectangle. It has setter ​and getter ​methods for both length 
​and width. ​The setter method should verify that length ​and width ​are floating-point numbers larger than 0.0 and 
less than 20.0.  

Code : 
import java.util.Scanner;
class Rectangle2{
private static float length = 0;
private static float width = 0;
public float perimeter(){
return 2*(length + width);
}
public float area(){
return length*width;
}
public float getlength(){
return Rectangle2.length;
}
public float getwidth(){
return Rectangle2.width;
}
public void setter(float x , float y){
if(x < 20.0 && x > 0.0 && y < 20.0 && y > 0.0){
Rectangle2.length = x;
Rectangle2.width = y;
}
}
public static void main(String[] args) {
Rectangle2 r = new Rectangle2();
26 
 

System.out.println("Enter the length and width between value 0.0 and 20.0 :");
Scanner input = new Scanner(System.in);
float len = input.nextFloat();
float wid = input.nextFloat();
input.close();
r.setter(len, wid);
float peri = r.perimeter();
float area = r.area();
if(peri !=0 && area != 0)
System.out.println("Perimeter and area are "+peri+" and "+area+" respectively.");
else
System.out.println("You values crossed the limit.");
System.out.println("Length and width are taken as : "+r.getlength()+" and "+r.getwidth()+" to calculate
result.");
}
}

Output : 
PS F:\VSCode\Java\Class> java Rectangle2 
Enter the length and width between value 0.0 and 20.0 : 
12 9 
Perimeter and area are 42.0 and 108.0 respectively. 
Length and width are taken as : 12.0 and 9.0 to calculate result. 
 

ASSIGNMENT 2 
 
Problem Statement 1:  
Define a class MotorVehicle​ as described below:
a. Data members
i. modelName
ii. modelNumber
iii. modelPrice
b. Methods:
27 
 

i. display() method to display the name, model number ​and price.​


Define another class Car​ that inherits the class MotorVehicle ​and has the following
details:
a. Data members:
i. discountRate
b. Methods:
i. display() method to display the car name, car model number, car price​ and
discount rate.
ii. calculateDiscount() method to compute the discount.
Create the classes MotorVehicle ​and Car ​with suitable constructors and test it.

Code : 
class MotorVehicle{
String modelName;
int modelNumber;
float modelPrice;
MotorVehicle(String name, int number, float price){
this.modelName = name;
this.modelNumber = number;
this.modelPrice = price;
}
void display(){
System.out.println("Model name is : "+modelName);
System.out.println("Model number is : "+modelNumber);
System.out.println("Model price is :"+modelPrice);
}
}
class Car extends MotorVehicle{
float discountRate;
Car(String name, int number, float price, float discount){
super (name, number, price);
this.discountRate = discount;
}
28 
 

void display(){
super.display();
System.out.println("Discount rate is : "+discountRate);
}
double calculateDiscount(){
double discountAmount = modelPrice * discountRate * 0.01;
return discountAmount;
}
}
class CarDemo{
public static void main(String[] args) {
MotorVehicle m1 = new MotorVehicle("Bajaj", 9907, 65000);
m1.display();
Car c1 = new Car("Vitara_Breza", 2258, 45000, 15);
double discount = c1.calculateDiscount();
c1.display();
System.out.println("Total discount available is :"+discount);
}
}
 

 
Output : 
PS F:\VSCode\Java\Class> java CarDemo 
Model name is : Bajaj 
Model number is : 9907 
Model price is :65000.0 
Model name is : Vitara_Breza 
Model number is : 2258 
Model price is :45000.0 
Discount rate is : 15.0 
Total discount available is :6750.0 
 
29 
 

Problem Statement 2:  


Define a class named as College​ as shown below :
a. Data members:
a. collegeName
b. address
b. Methods:
a. showCollegeDetails() to show the details about the college.
Define another class named Department ​that inherits the class College​ and has the following:
a. Data members:
a. departmentName
b. hodName
b. Methods:
a. showDepartmentDetails() to show the details of the department ​within the college.
Define another class named FacultyMember ​that inherits the class Department ​and has the
following details:
a. Data members:
a. facultyMemberName
b. facultyMemberQualification
c. yearsOfExperience
b. Methods:
a. showFacultyMemberDetails() to show the details of the faculty member ​within a
particular department ​in the college.
Create the classes College, Department ​and FacultyMember ​with suitable constructors and
test them.
 

Code : 
class College{
String collegeName;
String address;
College(String name, String address){
this.collegeName = name;
this.address = address;
}
30 
 

void showCollegeDetails(){
System.out.println("College name is : "+collegeName);
System.out.println("College address is : "+address);
}
}
class Department extends College{
String departmentName;
String hodName;
Department(String name, String address, String deptName, String hodName){
super(name, address);
this.departmentName = deptName;
this.hodName = hodName;
}
void showDepartmemtDetails(){
super.showCollegeDetails();
System.out.println("Department name : "+departmentName);
System.out.println("HOD name : "+hodName);
}
}
class facultyMember extends Department{
String facultyMemberName;
String facultyMemberQualification;
int yearsOfExperience;
facultyMember(String name, String address, String deptName, String hodName, String memberName, String
memberQualification, int experience){
super(name, address, deptName, hodName);
this.facultyMemberName = memberName;
this.facultyMemberQualification = memberQualification;
this.yearsOfExperience = experience;
}
void showFacultyMemberDetails(){
super.showDepartmemtDetails();
System.out.println("Faculty member name : "+facultyMemberName);
System.out.println("Qualification : "+facultyMemberQualification);
31 
 

System.out.println("Experience : "+yearsOfExperience+" years");


}
}
class CollegeDemo{
public static void main(String[] args) {
facultyMember f1 = new facultyMember("GCETTS", "Serampore", "CSE", "PM Sir", "Neel", "B.Tech",
4);
f1.showFacultyMemberDetails();
}
}
 

Output : 
PS F:\VSCode\Java\Class> java CollegeDemo 
College name is : GCETTS 
College address is : Serampore 
Department name : CSE 
HOD name : PM Sir 
Faculty member name : Neel 
Qualification : B.Tech 
Experience : 4 years 
 

Problem Statement 3:  


Create a class named Employee ​with the following details:
a. Data members:
a. Name
b. dateOfBirth
c. gender
d. address
b. Methods:
a. display() to show the employee details.
Create another class FullTimeEmployee ​that inherits Employee ​class and has the following:
a. Data members:
a. Salary
32 
 

b. designation
b. Methods:
a. display() to show the salary ​and designation ​along with other employee details.
Create another class PartTimeEmployee​ that inherits Employee ​class and has the following:
a. Data members:
a. workingHours
b. ratePerHour
b. Methods:
a. calculatePay() to calculate the amount payable.
b. display() to show the amount payable ​along with other employee details.
Create objects of these classes and call their methods. ​Use appropriate constructors.
 

Code : 
class Employee{
private String name;
private String dateOfBirth;
private String gender;
private String address;
public Employee(String name, String dob, String gender, String address){
this.name = name;
this.dateOfBirth = dob;
this.address = address;
if(gender == "male")
System.out.println("Gender : Male");
else if(gender == "female")
System.out.println("Gender : Female");
}
void display(){
System.out.println("Employee name : "+name);
System.out.println("Date of birth : "+dateOfBirth);
System.out.println("Address : "+address);
}
}
class FullTimeEmployee extends Employee{
33 
 

private double salary;


private String designation;
public FullTimeEmployee(String name, String dob, String gender, String address, double sal, String desg){
super(name, dob, gender, address);
this.salary = sal;
this.designation = desg;
}
void display(){
super.display();
System.out.println("Salary : "+salary);
System.out.println("Designation : "+designation);
}
}
class PartTimeEmployee extends Employee{
private float workingHours;
private double ratePerHour;
public PartTimeEmployee(String name, String dob, String gender, String address, float hours, double rate){
super(name, dob, gender, address);
this.workingHours = hours;
this.ratePerHour = rate;
}
private double calculatePay(){
return workingHours*ratePerHour;
}
void display(){
super.display();
System.out.println("Working hours is : "+workingHours);
System.out.println("Rate per hour : "+ratePerHour);
System.out.println("Amount payable : "+ calculatePay());
}
}
class EmployeeDemo{
public static void main(String[] args) {
34 
 

FullTimeEmployee f = new FullTimeEmployee("Amit", "27-8-1996", "male", "Keshpur", 15000,


"Assistant");
f.display();
PartTimeEmployee p = new PartTimeEmployee("Susmita", "12-5-1990", "female", "Serampore", 11,
500);
p.display();
}
}

Output : 
PS F:\VSCode\Java\Assignment 2> java EmployeeDemo
Gender : Male
Employee name : Amit
Date of birth : 27-8-1996
Address : Keshpur
Salary : 15000.0
Designation : Assistant
Gender : Female
Employee name : Susmita
Date of birth : 12-5-1990
Address : Serampore
Working hours is : 11.0
Rate per hour : 500.0
Amount payable : 5500.0
 
 

Problem Statement 4:  


Define an Employee ​class with suitable attributes ​having getSalary() ​method, which returns salary withdrawn ​by 
particular employee. Write class Manager ​which extends class Employee , override the getSalary() ​method, which 
will return salary of manager ​by adding travelling allowance ​(i.e. TA), house rent allowance​ (i.e. HRA) etc. 

 
Code : 
35 
 

import java.util.Scanner;
class employee{
protected double getSalary(){
System.out.println("Enter the salary of employee : ");
Scanner input = new Scanner(System.in);
double sal = input.nextDouble();
//input.close();
return sal;
}
}
class manager extends employee{
public double getSalary(){
Scanner input = new Scanner(System.in);
System.out.println("Enter salary of the manager :");
double sal = input.nextDouble();
System.out.println("Enter travelling allowance :");
double ta = input.nextDouble();
System.out.println("Enter house rent :");
double hr = input.nextDouble();
input.close();
return sal+ta+hr;
}
}
class EmpDemo{
public static void main(String[] args) {
employee emp = new employee();
double salemp = emp.getSalary();
System.out.println("Salary of the employee is : "+salemp);
employee mngr = new manager();
double salmngr = mngr.getSalary();
System.out.println("Salary of the manager is :"+salmngr);
}

 
36 
 

Output : 
PS F:\VSCode\Java\Class> java EmpDemo 
Enter the salary of employee : 
15000 
Salary of the employee is : 15000.0 
Enter salary of the manager : 
25000 
Enter travelling allowance : 
1000 
Enter house rent : 
5000 
Salary of the manager is :31000.0 
 

Problem Statement 5:  


Create a class named Figure. ​Make cube, cylinder ​and sphere ​as object of the class Figure and calculate their 
surface area ​by the concept of method overloading.  

Code : 
import java.util.Scanner;
class Figure {
public double surfaceArea(double a){
return 6*a*a;
}
public double surfaceArea(double a,double pi){
return 4*3.14*a*a;
}
public double surfaceArea(double r,double h,double pi){
return (2*3.14*r*h+2*3.14*r*r);
}
}

class FigureDemo {
public static void main(String[] args) {
37 
 

Scanner sc=new Scanner(System.in);


System.out.println("Enter side of cube : ");
double side=sc.nextDouble();
Figure cube=new Figure();
System.out.println("Surface area of cube is :"+cube.surfaceArea(side));
System.out.println("Enter radius of Sphere : ");
side=sc.nextDouble();
Figure sphere=new Figure();
System.out.println("Surface area of Sphere is :"+sphere.surfaceArea(side, Math.PI));
System.out.println("Enter radius and height of Cylinder : ");
double radius=sc.nextDouble();
side=sc.nextDouble();
Figure cylinder=new Figure();
System.out.println("Surface area of Cylinder is :"+cylinder.surfaceArea(radius,side,Math.PI));
}
}
 

Output : 
PS F:\VSCode\Java\Assignment 2> java FigureDemo 
Enter side of cube : 
10 
Surface area of cube is :600.0 
Enter radius of Sphere : 

Surface area of Sphere is :314.0 
Enter radius and height of Cylinder : 
10 20 
Surface area of Cylinder is :1884.0 
 

Problem Statement 6:  


Create a class Telephone ​containing a list of customers ​(name, telephone number ​and city​)
and write member functions (using function overloading) for the followings:
38 
 

a. Search telephone number with given name.


b. Search name with given telepone number.
c. Search all customers in given city.
In this program Customer ​is a class with the following attributes:
a. Name
b. telephoneNumber
c. city

Code : 
class Customer { 
public String name; 
public int telephoneNumber; 
public String city; 
 
Customer(String name, int telephoneNumber, String city) { 
this.name = name; 
this.telephoneNumber = telephoneNumber; 
this.city = city; 

void display() { 
System.out.println("Customer Name: " + name); 
System.out.println("Telephone Number: " + telephoneNumber); 
System.out.println("City: " + city); 


class Telephone { 
private Customer arr[]; 
private int index; 
 
Telephone(int Count) { 
this.arr = new Customer[Count]; 
39 
 

index = 0; 

public void searchByName(String name) { 
for (Customer cst : arr) { 
if (cst.name == name) { 
cst.display(); 



public void searchByNumber(int number) { 
for (Customer cst : arr) { 
if (cst.telephoneNumber == number) { 
cst.display(); 



public void searchByCity(String city) { 
for (Customer cst : arr) { 
if (cst.city == city) { 
cst.display(); 



public void addCustomer(String name, int telephoneNumber, String city) { 
this.arr[index++] = new Customer(name, telephoneNumber, city); 

public static void main(String[] args) { 
Telephone telephone = new Telephone(5); 
telephone.addCustomer("Neel", 1001, "Kolkata"); 
telephone.addCustomer("Jodu", 1002, "Serampore"); 
telephone.addCustomer("Satadal", 1003, "Hooghly"); 
telephone.addCustomer("Susmita", 1004, "Lane"); 
40 
 

telephone.addCustomer("Baaz", 1005, "Hyderabad"); 


 
telephone.searchByName("Jodu"); 
telephone.searchByNumber(1004); 
telephone.searchByCity("Kolkata"); 


 

Output : 
PS F:\VSCode\Java\Assignment 2> java Telephone 
Customer Name: Jodu 
Telephone Number: 1002 
City: Serampore 
Customer Name: Susmita 
Telephone Number: 1004 
City: Lane 
Customer Name: Neel 
Telephone Number: 1001 
City: Kolkata 
 

Problem Statement 7:  


Create a class called Amphibian.​ From this, inherit a class called Frog.​ Put appropriate methods ​in the base class. 
In main() ​, create a Frog ​and upcast ​it to Amphibian,​ and demonstrate that all the methods still work. Now 
modify the Frog ​class so that it overrides the method definitions from the base class ​(provides new definitions 
using the same method signatures). Note what happens in main().  

Code : 
class Amphibian {
public void eat() {
System.out.println("Amphibian eat");
}
public void sleep() {
System.out.println("Amphibian sleep");
41 
 

}
}
class Frog extends Amphibian {
public void eat() {
System.out.println("Frog eat");
}
public void sleep() {
System.out.println("Frog sleep");
}
}
class AmphibianDemo {
public static void main(String[] args) {
Frog fg=new Frog();
Amphibian amph=(Amphibian)fg;
amph.eat();
amph.sleep();
}
}
 

 
 
Output : 
PS F:\VSCode\Java\Assignment 2> java AmphibianDemo 
Frog eat 
Frog sleep 
 

Problem Statement 8:  


Create a class with a final ​method. Inherit ​from that class and attempt to override ​that method.  

Code : 
class Bike{ 
final void run(){ 
42 
 

System.out.println("run bike"); 


class Honda extends Bike{ 
void run(){ 
System.out.println("Run Honda"); 


class BikeTest{ 
public static void main(String[] args) { 
Bike b = new Honda(); 
b.run(); 


 

Output : 
PS F:\VSCode\Java\Assignment 2> javac BikeTest.java 
BikeTest.java:7: error: run() in Honda cannot override run() in Bike 
void run(){ 

overridden method is final 
1 error 
 

Problem Statement 9:  


Create a base class ​with two methods. In the first ​method, call the second ​method. Inherit a class and override 
​the second​ method. Create an object of the derived class, upcast ​it to the base type, and call the first ​method. 
See what happens.  

Code : 
class BaseClass { 
public void first(){ 
System.out.println("First method of the base class."); 
43 
 

second(); 

 
public void second(){ 
System.out.println("Second method of the base class."); 


 
public class Inherit extends BaseClass { 
 
public void second(){ 
System.out.println("Overriden second method of the base class in the Inherit class."); 

 
public static void main(String[] args) { 
BaseClass bc = new Inherit(); 
if(bc instanceof Inherit){ 
Inherit in = (Inherit)bc; 
in.first(); 

else 
System.out.println("Cannot be done"); 


 

 
Output : 
PS F:\VSCode\Java\Assignment 2> java Inherit 
First method of the base class. 
Overriden second method of the base class in the Inherit class. 
 
44 
 

Problem Statement 10:  


Create a class Instrument ​with a method tune().​ Create another class Guitar ​which extends Instrument ​class and 
override the tune() ​method. Create another class Keyboard ​which also extends Instrument ​class and override the 
tune() ​method. Now create TestInstrument ​class containing main() ​method and in the main() ​method create an 
array ​of Instrument ​objects of size 2. The array will contain Guitar ​and Keyboard ​objects respectively. Now call 
the tune() method on the array objects.​ See what happens.  

Code : 
class Instrument {
public void tune() {
System.out.println("General tune");
}
}
class Guitar extends Instrument {
public void tune() {
System.out.println("Guitar tune");
}
}
class Keyboard extends Instrument {
public void tune() {
System.out.println("Keyboard tune");
}
}
class TestInstrument {
public static void main(String[] args) {
Instrument[] instrument=new Instrument[2];
instrument[0]=new Guitar();
instrument[1]=new Keyboard();
instrument[0].tune();
instrument[1].tune();
}
}
 

Output : 
45 
 

PS F:\VSCode\Java\Assignment 2> java TestInstrument 


Guitar tune 
Keyboard tune 

You might also like