Java 3 & 4
Java 3 & 4
Java 3 & 4
(3&4)
Signature :
Date :
ASSIGNMENT 3
Problem Statement 1:
Create an abstract class Account as shown below:
a. Data members:
i. accountNumber
ii. accountHolderName
iii. address
iv. balance
b. Methods:
i. withdraw()- abstract
ii. deposite()- abstract
iii. display() to show the balance of the account.
Create a subclass of Account named SavingsAccount that has the following details:
a. Data members:
i. rateOfInterest
b. Methods:
i. calculateAmount() to calculate the total balance after calculating interest.
ii. display() to display rate of interest with new balance and full account holder details.
Create another subclass of Account named CurrentAccount that has the following details:
a. Data members:
i. overdraftLimit
b. Methods:
i. display() to show overdraft limit along with the full account holder details.
Create objects of these two classes and call their methods. Use appropriate constructors.
Code :
abstract class Account {
int accountNumber;
String accountHolderName;
String address;
double balance;
public Account() {
return this.accountHolderName;
this.accountHolderName = var1;
this.accountNumber = var1;
return this.address;
this.address = var1;
return this.balance;
this.balance = var1;
SavingsAccount(double var1) {
this.rateOfInterest = var1;
this.balance -= var1;
else {
System.out.println("Insufficient balance");
return this.balance;
this.balance += var1;
return this.balance;
CurrentAccount(double var1) {
this.overdraftLimit = var1;
System.out.println("Address : "+this.address);
}
public double withdraw(double var1) {
this.balance -= var1;
} else {
System.out.println("Insufficient balance");
return this.balance;
this.balance += var1;
return this.balance;
class Test {
public Test() {
var1.setAccountHolderName("Nil Das");
var1.setAccountNumber(6022);
var1.setAddress("Serampore");
var1.setBalance(80.0D);
var1.display();
var1.deposit(40.0D);
var1.withdraw(90.0D);
var2.setAccountHolderName("Shouvik");
var2.setAccountNumber(6018);
var2.setAddress("Serampore");
var2.setBalance(0.0D);
var2.deposit(40.0D);
var2.withdraw(30.0D);
var2.display();
Output :
PS G:\Java> javac Test.java
PS G:\Java> java Test
Acc Holder Name : Nil Das
Address : Serampore
Acc Number : 6022
Interest rate : 0.04
Final Amount : 83.2
Updated Final Amount : 124.8
Updated Final Amount : 31.2
Acc Holder Name : Shouvik
Address : Serampore
Acc Number : 6018
Over Draft Limit : 40.0
Final Balance : 10.0
Problem Statement 2:
Create an abstract class Person. Define two subclasses Employee and Worker from it. Use proper method
to accept and display the details for the same. The fields of Employee are empNo, empName, address.
Similar fields for Worker are name and workingHours.
Code :
abstract class Person {
public Person() {
this.empNo = var1;
this.empName = var2;
this.address = var3;
return this.empNo;
this.empNo = var1;
return this.address;
this.address = var1;
return this.empName;
void display() {
System.out.println("Employee no : "+this.empNo);
System.out.println("Address : "+this.address);
this.name = var1;
this.workingHours = var2;
return this.name;
this.name = var1;
return this.workingHours;
this.workingHours = var1;
void display() {
}
public class Test {
public Test() {
var1.display();
var1.setEmpName("Shouvik");
var1.setEmpNo(2);
var1.setAddress("Serampore");
var1.display();
var2.display();
Output :
PS G:\Assignment-3\Two> javac Test.java
PS G:\Assignment-3\Two> java Test
Employee name : Satadal
Employee no : 1
Address : Midnapore
Employee name : Shouvik
Employee no : 2
Address : Serampore
Worker name : Nil
Working hours : 10
Problem Statement 3:
Write an interface called Numbers with a method int process(int x, int y). Write a class called Sum, in
which the method process() finds the sum of two numbers and returns an integer value. Write another
class called Average, in which the process() method finds the average of the two numbers and returns an
integer value.
Code :
interface Numbers {
public Sum() {
public Average() {
public Test() {
System.out.println(var1.process(5, 6));
System.out.println(var2.process(5, 6));
}
Output :
PS G:\Assignment 3\Three> javac Test.java
PS G:\Assignment 3\Three> java Test
11
5
Problem Statement 4:
Write an interface Examination with a method pass(int marks) that returns a boolean value. Write another
interface called Classify with a method division(int average) which returns a String. Write a class Result
which implements both Examination and Classify. The pass() method should return true if the marks is
greater than or equal to 50 else false. The method division() should return "First" when the parameter
average is 60 or more, "Second" when the average is 50 or more but less than 60, "No Division" when
average is less than 50.
Code :
interface Examination {
interface Classify {
public Result() {
return "First";
} else {
}
}
Output :
PS G:\Assignment 3\Four> javac Test.java
PS G:\Assignment 3\Four> java Test
Marks: 55
Passed: true
Division: Second
Marks: 45
Passed: false
Division: No Division
Marks: 75
Passed: true
Division: First
Problem Statement 5:
Create an interface Shape. Derive three classes Sphere, Cone and Cylinder from it. Calculate area and
volume of all (using method overriding).
Code :
interface Shape {
double surfaceArea();
double volume();
Sphere(double radius) {
this.radius = radius;
this.height = height;
this.radius = radius;
this.height = height;
this.radius = radius;
System.out.println("Sphere: ");
System.out.println("Cone: ");
System.out.println("Cylinder: ");
}
Output :
PS G:\Assignment 3\Five> javac Test.java
PS G:\Assignment 3\Five> java Test
Sphere:
Area: 314.1592653589793
Volume: 523.5987755982989
Cone:
Area: 260.317073556415
Volume: 188.4955592153876
Cylinder:
Area: 414.6902302738527
Volume: 565.4866776461628
Problem Statement 6:
Design an interface named Stack with the following methods:
a. To push elements into the stack.
b. To pop elements from the stack.
c. To check whether the stack is empty or not.
Implement the stack with the help of array and if the size of the array becomes too small to hold the
elements, create a new one. Test this interface by inheriting it in its subclass StackTest.java.
Code :
import java.util.NoSuchElementException;
import java.util.Scanner;
class Stack<Item> {
private int n = 0;
Stack() {
return this.n == 0;
}
return this.n;
var2[var3] = this.a[var3];
this.a = var2;
if (this.n == this.a.length) {
this.resize(2 * this.a.length);
this.a[this.n++] = var1;
if (this.isEmpty()) {
} else {
this.a[this.n - 1] = null;
--this.n;
this.resize(this.a.length / 2);
return var1;
}
public class StackTest {
public StackTest() {
System.out.println("Enter 0 to exit");
while(!var3) {
System.out.print("Choice: ");
switch(var2.nextInt()) {
case 0:
var3 = true;
break;
case 1:
System.out.print("Text: ");
var1.push(var2.next());
break;
case 2:
System.out.println((String)var1.pop());
break;
default:
System.out.println("Invalid Choice");
var2.close();
}
Output :
G:\Assignment 3\Six>javac -Xlint StackTest.java
G:\Assignment 3\Six>java StackTest
Enter 1 to push to stack
Enter 2 to pop from stack
Enter 0 to exit
Choice: 1
Text: Nil
Choice: 1
Text: Baaj
Choice: 2
Popped Baaj
Choice: 0
Problem Statement 7:
Design an interface named Queue with the following methods:
a. To add elements into the queue.
b. To remove elements from the queue.
c. To check whether the stack is empty or not.
Implement the queue with the help of array and if the size of the array becomes too small to hold the
elements, create a new one. Test this interface by inheriting it in its subclass QueueTest.java.
Code :
import java.util.NoSuchElementException;
import java.util.Scanner;
class Queue<Item> {
private int n = 0;
public Queue() {
}
public boolean isEmpty() {
return this.n == 0;
return this.n;
this.q = var2;
this.first = 0;
this.last = this.n;
if (this.n == this.q.length) {
this.resize(2 * this.q.length);
this.q[this.last++] = var1;
if (this.last == this.q.length) {
this.last = 0;
++this.n;
if (this.isEmpty()) {
} else {
this.q[this.first] = null;
--this.n;
++this.first;
if (this.first == this.q.length) {
this.first = 0;
this.resize(this.q.length / 2);
return var1;
public QueueTester() {
System.out.println("Enter 1 to enqueue");
System.out.println("Enter 2 to dequeue");
System.out.println("Enter 0 to exit");
while(!var3) {
System.out.print("Choice: ");
switch(var2.nextInt()) {
case 0:
var3 = true;
break;
case 1:
System.out.print("Text: ");
var1.enqueue(var2.next());
break;
case 2:
System.out.println((String)var1.dequeue());
break;
default:
System.out.println("Invalid Choice");
var2.close();
Output :
G:\Assignment 3\Seven>java QueueTester
Enter 1 to enqueue
Enter 2 to dequeue
Enter 0 to exit
Choice: 1
Text: 50
Choice: 1
Text: 74
Choice: 1
Text: 98
Choice: 2
Popped 50
Choice: 2
Popped 74
Problem Statement 8:
Design an interface with a method reversal. This method takes a String as its input and returns the
reversed String. Create a class StringReversal that implements the method [do not use predefined
methods].
Code :
interface Reversal {
String reverse(String data);
validData[validData.length - i - 1] = temp;
Output :
G:\Assignment 3\Eight>java StringReversal
sad lin ma I
AVAJ ekil I
Problem Statement 9:
Write a program to create a package named pack and store Addition class in it. Now create another class
TestPackage containing main() method and use an object of Addition class in the main() method. Place
TestPackage class in the default package or in the pack package. In both cases run the program
TestPackage without using an IDE.
Code :
import pack.Addition;
System.out.println(var1.add(5, 6));
Output :
G:\Assignment 3\Nine>java TestPackage
11
Code :
package iterative;
int result=1,i=1;
while(i<=n){
result=result*i;
i++;
return result;
package recursive;
return 1;
else{
return n*factorialRecursive(n-1);
import iterative.FactorialIterative;
import recursive.FactorialRecursive;
System.out.println(fi.factorialIterative(10));
System.out.println(fr.factorialRecursive(10));
Output :
G:Assignment 3\Ten>java TestFactorial
3628800
3628800
ASSIGNMENT 4
Problem Statement 1:
Create a user-defined exception named CheckArgument to check the number of arguments passed
through command line. If the number of arguments is less than five, throw the CheckArgument exception
else print the summation of all the five numbers.
Code :
public class TestDemo {
public static void main(String[] args) {
int sum = 0;
try {
if (args.length < 5) {
throw new CheckArgument();
} else {
int arr[] = new int[args.length];
for (int i = 0; i < args.length; i++)
arr[i] = Integer.parseInt(args[i]);
for (int i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
System.out.println("Sum of the command line arguments : " + sum);
}
} catch (CheckArgument e) {
System.out.println("Number of command line arguments should be atleast
five.");
System.out.println("Try running the program again.");
}
}
}
public class CheckArgument extends Exception {
public CheckArgument() {
}
}
Output :
G:\VSCode\Java\Assignment4\one>java TestDemo
Number of command line arguments should be atleast five.
Try running the program again.
Problem Statement 2:
Consider a student examination database system that prints the mark sheet of students. Input the
following from the keyboard:
a. Student's name
b. Marks in six subjects
These marks should be between 0 and 50. If the marks are not in the specified range, raise a
RangeException (a user-defined exception) else find the total marks and print the percentage of marks of
the students.
Code :
import java.util.*;
Output :
G:\VSCode\Java\Assignment4\two>java TestResult
Enter Student's Name :
Nilmadhab Das
Enter the marks of the student :
40
30
35
45
50
20
Student's Name : Nilmadhab Das
Result ::
Subject 1 : 40
Subject 2 : 30
Subject 3 : 35
Subject 4 : 45
Subject 5 : 50
Subject 6 : 20
Total marks : 220
Percentage : 72.0
Problem Statement 3:
Write a program to generate and catch an ArrayIndexOutOfBoundsException.
Code :
public class ArrayIndexOutOfBound {
public static void main(String[] args) {
int[] arr = new int[2];
try {
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}
}
Output :
G:\VSCode\Java\Assignment4\three>java ArrayIndexOutOfBound
java.lang.ArrayIndexOutOfBoundsException: 2
at ArrayIndexOutOfBound.main(ArrayIndexOutOfBound.java:7)
Problem Statement 4:
Define an object reference and initialize it to null. Try to call a method through this reference. Now wrap
the code in a try-catch clause to catch the exception.
Code :
public class TestException {
public static void main(String[] args) {
try {
refObject obj = null;
obj.refObjectNum(10);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
public class refObject {
int number;
public void refObjectNum(int num) {
this.number = num;
}
}
Output :
G:\VSCode\Java\Assignment4\four>java TestException
java.lang.NullPointerException
at TestException.main(TestException.java:5)
Problem Statement 5:
Consider a class that represents an account in a bank. Let the minimum balance for the account be Rs.
1000. Write a program that throws an exception when a withdrawal results in the balance decreasing to
value less than Rs. 1000.
Code :
import java.util.Scanner;
Output :
G:\VSCode\Java\Assignment4\five>java bankAccount
Enter amount to withdraw :
400
Current balance in your account : 600
Problem Statement 6:
Create your own exception class using extends keyword. Write a constructor for this class that takes a
String argument and store it inside object with a String reference. Write a method that prints out the
stored String. Create a try-catch clause to exercise your new exception.
Code :
public class TestDemo {
public static void main(String[] args) {
String ptr = "SB";
try {
if (ptr.equals("SB")) {
// throw new stringExcept(ptr);
System.out.println("Both strings are equal");
} else {
throw new stringExcept(ptr);
}
} catch (stringExcept e) {
e.printName();
}
}
}
import java.io.*;
stringExcept(String strng) {
this.str = strng;
}
void printName() {
System.out.println("String to be tested is : " + str);
}
Output :
G:\VSCode\Java\Assignment4\six>java TestDemo
Both strings are equal
Problem Statement 7:
Create a class with two methods first() and second(). Each method throws an exception of a new type that
you have defined. In first(), call second(), catch its exception and in the catch clause, throw a different
exception (of a second type that you have defined). In main() method call the first() method.
Code :
public class TestExceptClass {
public void second() {
try {
throw new MyException2();
} catch (MyException2 e2) {
System.out.println("My Exception-2 caught");
}
}
Output :
G:\VSCode\Java\Assignment4\seven>java TestExceptClass
Error: Could not find or load main class TestExceptClass
Problem Statement 8:
Create three new types of exceptions. Write a class with method that throws all the three. In main(), call
the method but only use a single catch clause that will catch all the three types of exceptions.
Code :
import java.util.Scanner;
G:\VSCode\Java\Assignment4\eight>java TestDemo
Choose a Number from below :
(1)
(2)
(3)
2
MyException2 arrised.
G:\VSCode\Java\Assignment4\eight>java TestDemo
Choose a Number from below :
(1)
(2)
(3)
1
MyException1 arrised.
Problem Statement 9:
Write class Student with attributes roll no, name, age and course. Initialize values through parameterized
constructor. If age of student is not in between 15 and 21 then generate user defined exception "Age Not
within Range". If name contains numbers or special symbols, raise exception "Name not Valid".
Code :
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Student {
int rollNo;
String name;
int age;
String course;
this.rollNo = rollNo;
this.course = course;
Output :
G:\VSCode\Java\Assignment4\nine>java TestDemo
Age should be between 15 to 21
Code :
import java.util.Scanner;
Output :
G:\VSCode\Java\Assignment4\ten>java Test
Enter marks : 25
Marks entered is : 25
Code :
public class testClass {
char input;
Output :
G:\VSCode\Java\Assignment4\eleven>java testClass
Error: Main method not found in class testClass, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Code :
(a)
import java.util.Scanner;
public class findStringLength {
public static void main(String[] args) {
String input;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String : ");
input = sc.nextLine();
System.out.println("Length : " + input.length());
}
}
(b)
import java.util.Scanner;
}
(c)
import java.util.Scanner;
Output :
(a)
G:\VSCode\Java\Assignment4\twelve\a>java findStringLength
Enter a String :
Nilmadhab
Length : 9
(b)
G:\VSCode\Java\Assignment4\twelve\b>java noWhiteSpace
Enter a String :
Nilmadhab das
Length of the String without White Space : 12
(c)
G:\VSCode\Java\Assignment4\twelve\c>java doubleToString
Enter a Double value :
2222222222222.3656444
After converting the Double to String : 2.2222222222223657E12
And Length of this String : 21
(d)
G:\VSCode\Java\Assignment4\twelve\d>java demo
Enter a String :
nil9rt@
Contains both Numbers and Characters
(e)
G:\VSCode\Java\Assignment4\twelve\e>java checkStrings
Enter first String :
Nil
Enter second String :
Das
Second String is not the reverse of the First String
(f)
G:\VSCode\Java\Assignment4\twelve\f>java checkStrings
Enter first String :
nil
Enter second String :
lin
Strings are not Equal
(g)
G:\VSCode\Java\Assignment4\twelve\g>java removeChar
Enter a String :
nilmadhab
After removing 6th and 8th char the string is :
nilmaha
(h)
G:\VSCode\Java\Assignment4\twelve\h>java lowerUpper
Enter String mixing LowerCase & UpperCase letters :
NILmadhabDas
Whole String in Lower Case :
nilmadhabdas
Whole String in Lower Case :
NILMADHABDAS
(i)
G:\VSCode\Java\Assignment4\twelve\i>java reverseString
Enter a String :
NiLmAdHaB
Reversed String :
BaHdAmLiN
Code :
public class threadConcept extends Thread {
public void run() {
try {
System.out.println("Thread " + Thread.currentThread().getId() + " is
running");
} catch (Exception e) {
System.out.println("Exception is caight");
}
}
}
public class demoThread {
public static void main(String[] args) {
int n = 8; // no. of Threads
for (int i = 0; i < n; i++) {
threadConcept obj = new threadConcept();
obj.start();
}
}
}
Output :
G:\VSCode\Java\Assignment4\thirteen>java demoThread
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 14 is running
Thread 16 is running
Thread 17 is running
Thread 15 is running
Thread 13 is running
Code :
public class counterOne extends Thread {
int counter = 5;
Output :
G:\VSCode\Java\Assignment4\fourteen>java testCounter
Thread counterOne printed 5
Thread counterTwo printed 10
Thread counterThree printed 100
Thread counterTwo printed 20
Thread counterOne printed 10
Thread counterTwo printed 30
Thread counterThree printed 200
Thread counterTwo printed 40
Thread counterThree printed 300
Thread counterTwo printed 50
Thread counterThree printed 400
Thread counterTwo printed 60
Thread counterThree printed 500
Thread counterTwo printed 70
Thread counterThree printed 600
Thread counterTwo printed 80
Thread counterThree printed 700
Thread counterTwo printed 90
Thread counterThree printed 800
Thread counterTwo printed 100
Thread counterThree printed 900
Thread counterThree printed 1000
Code :
public class counterOne extends Thread {
int counter = 5;
Output :
G:\VSCode\Java\Assignment4\fifteen>java testCounter
Alive ? : true
Thread counterOne printed 5
Thread counterOne printed 10
Alive ? : true
Thread counterTwo printed 10
Thread counterTwo printed 20
Thread counterTwo printed 30
Thread counterTwo printed 40
Thread counterTwo printed 50
Thread counterTwo printed 60
Thread counterTwo printed 70
Thread counterTwo printed 80
Thread counterTwo printed 90
Thread counterTwo printed 100
Alive ? : true
Thread counterThree printed 100
Thread counterThree printed 200
Thread counterThree printed 300
Thread counterThree printed 400
Thread counterThree printed 500
Thread counterThree printed 600
Thread counterThree printed 700
Thread counterThree printed 800
Thread counterThree printed 900
Thread counterThree printed 1000