Sei sulla pagina 1di 50

JAVA ASSIGNMENTS

(3&4)

Government College of Engineering and Textile


Technology , Serampore ;

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() {

public String getAccountHolderName() {

return this.accountHolderName;

public void setAccountHolderName(String var1) {

this.accountHolderName = var1;

public int getAccountNumber() {


return this.accountNumber;

public void setAccountNumber(int var1) {

this.accountNumber = var1;

public String getAddress() {

return this.address;

public void setAddress(String var1) {

this.address = var1;

public double getBalance() {

return this.balance;

public void setBalance(double var1) {

this.balance = var1;

public abstract double withdraw(double var1);

public abstract double deposit(double var1);

public abstract void display();

class SavingsAccount extends Account {

private double rateOfInterest;

SavingsAccount(double var1) {

this.rateOfInterest = var1;

public double calculateAmount() {

return this.balance * this.rateOfInterest + this.balance;

public void display() {

System.out.println("Acc Holder Name : "+this.accountHolderName);


System.out.println("Address : "+this.address);

System.out.println("Acc Number : "+this.accountNumber);

System.out.println("Interest rate : "+this.rateOfInterest);

System.out.println("Final Amount : "+this.calculateAmount());

public double withdraw(double var1) {

if (this.balance > var1) {

this.balance -= var1;

else {

System.out.println("Insufficient balance");

return this.balance;

public double deposit(double var1) {

if (var1 > 0.0D) {

this.balance += var1;

return this.balance;

class CurrentAccount extends Account {

private double overdraftLimit;

CurrentAccount(double var1) {

this.overdraftLimit = var1;

public void display() {

System.out.println("Acc Holder Name : "+this.accountHolderName);

System.out.println("Address : "+this.address);

System.out.println("Acc Number : "+this.accountNumber);

System.out.println("Over Draft Limit : "+this.overdraftLimit);

}
public double withdraw(double var1) {

if (this.balance + this.overdraftLimit > var1) {

this.balance -= var1;

} else {

System.out.println("Insufficient balance");

return this.balance;

public double deposit(double var1) {

if (var1 > 0.0D) {

this.balance += var1;

return this.balance;

class Test {

public Test() {

public static void main(String[] var0) {

SavingsAccount var1 = new SavingsAccount(0.04D);

CurrentAccount var2 = new CurrentAccount(40.0D);

var1.setAccountHolderName("Nil Das");

var1.setAccountNumber(6022);

var1.setAddress("Serampore");

var1.setBalance(80.0D);

var1.display();

var1.deposit(40.0D);

System.out.println("Updated Final Amount :


"+var1.calculateAmount());

var1.withdraw(90.0D);

System.out.println("Updated Final Amount :


"+var1.calculateAmount());
System.out.println();

var2.setAccountHolderName("Shouvik");

var2.setAccountNumber(6018);

var2.setAddress("Serampore");

var2.setBalance(0.0D);

var2.deposit(40.0D);

var2.withdraw(30.0D);

var2.display();

System.out.println("Final Balance : "+var2.getBalance());

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() {

abstract void display();

class Employee extends Person {

private int empNo;

private String empName;

private String address;

Employee(int var1, String var2, String var3) {

this.empNo = var1;

this.empName = var2;

this.address = var3;

public int getEmpNo() {

return this.empNo;

public void setEmpNo(int var1) {

this.empNo = var1;

public String getAddress() {

return this.address;

public void setAddress(String var1) {

this.address = var1;

public String getEmpName() {

return this.empName;

public void setEmpName(String var1) {


this.empName = var1;

void display() {

System.out.println("Employee name : "+this.empName);

System.out.println("Employee no : "+this.empNo);

System.out.println("Address : "+this.address);

class Worker extends Person {

private String name;

private int workingHours;

Worker(String var1, int var2) {

this.name = var1;

this.workingHours = var2;

public String getName() {

return this.name;

public void setName(String var1) {

this.name = var1;

public int getWorkingHours() {

return this.workingHours;

public void setWorkingHours(int var1) {

this.workingHours = var1;

void display() {

System.out.println("Worker name : "+this.name);

System.out.println("Working hours : "+this.workingHours);

}
public class Test {

public Test() {

public static void main(String[] var0) {

Employee var1 = new Employee(1, "Satadal", "Midnapore");

var1.display();

var1.setEmpName("Shouvik");

var1.setEmpNo(2);

var1.setAddress("Serampore");

var1.display();

Worker var2 = new Worker("Nil", 10);

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 {

int process(int var1, int var2);

class Sum implements Numbers {

public Sum() {

public int process(int var1, int var2) {

return var1 + var2;

class Average implements Numbers {

public Average() {

public int process(int var1, int var2) {

return (var1 + var2) / 2;

public class Test {

public Test() {

public static void main(String[] var0) {

Sum var1 = new Sum();

System.out.println(var1.process(5, 6));

Average var2 = new Average();

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 {

boolean pass(int var1);

interface Classify {

String division(int var1);

class Result implements Examination, Classify {

public Result() {

public boolean pass(int var1) {

return var1 >= 50;

public String division(int var1) {

if (var1 >= 60) {

return "First";

} else {

return var1 >= 50 ? "Second" : "No Division";

}
}

public class Test {

public static void main(String[] args) {

Result r = new Result();

System.out.println("Marks: " + 55);

System.out.println("Passed: " + r.pass(55));

System.out.println("Division: " + r.division(55));

System.out.println("Marks: " + 45);

System.out.println("Passed: " + r.pass(45));

System.out.println("Division: " + r.division(45));

System.out.println("Marks: " + 75);

System.out.println("Passed: " + r.pass(75));

System.out.println("Division: " + r.division(75));

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();

class Sphere implements Shape {

private double radius;

Sphere(double radius) {

this.radius = radius;

public double surfaceArea() {

return 4 * Math.PI * radius * radius;

public double volume() {

return 4 * Math.PI * Math.pow(radius, 3) / 3;

class Cone implements Shape {

private double height;

private double radius;

Cone(double height, double radius) {

this.height = height;

this.radius = radius;

public double volume() {

return Math.PI * radius * radius * height / 3;

public double surfaceArea() {

return Math.PI * radius * (radius + Math.pow((height * height +


radius * radius), 0.5));
}

class Cylinder implements Shape {

private double height;

private double radius;

Cylinder(double height, double radius) {

this.height = height;

this.radius = radius;

public double surfaceArea() {

return 2 * Math.PI * radius * (radius + height) ;

public double volume() {

return Math.PI * radius * radius * height;

public class Test {

public static void main(String[] args) {

Cone c = new Cone(5.00, 6.00);

Cylinder cd = new Cylinder(5.00, 6.00);

Sphere s = new Sphere(5.00);

System.out.println("Sphere: ");

System.out.println("Area: " + s.surfaceArea());

System.out.println("Volume: " + s.volume());

System.out.println("Cone: ");

System.out.println("Area: " + c.surfaceArea());

System.out.println("Volume: " + c.volume());

System.out.println("Cylinder: ");

System.out.println("Area: " + cd.surfaceArea());

System.out.println("Volume: " + cd.volume());

}
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;

private Item[] a = new Object[2];

Stack() {

public boolean isEmpty() {

return this.n == 0;
}

public int size() {

return this.n;

private void resize(int var1) {

assert var1 >= this.n;

Object[] var2 = new Object[var1];

for(int var3 = 0; var3 < this.n; ++var3) {

var2[var3] = this.a[var3];

this.a = var2;

public void push(Item var1) {

if (this.n == this.a.length) {

this.resize(2 * this.a.length);

this.a[this.n++] = var1;

public Item pop() {

if (this.isEmpty()) {

throw new NoSuchElementException("stack underflow");

} else {

Object var1 = this.a[this.n - 1];

this.a[this.n - 1] = null;

--this.n;

if (this.n > 0 && this.n == this.a.length / 4) {

this.resize(this.a.length / 2);

return var1;

}
public class StackTest {

public StackTest() {

public static void main(String[] var0) {

Stack var1 = new Stack();

Scanner var2 = new Scanner(System.in);

System.out.println("Enter 1 to push to stack");

System.out.println("Enter 2 to pop from stack");

System.out.println("Enter 0 to exit");

boolean var3 = false;

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 Item[] q = new Object[2];

private int n = 0;

private int first = 0;

private int last = 0;

public Queue() {

}
public boolean isEmpty() {

return this.n == 0;

public int size() {

return this.n;

private void resize(int var1) {

assert var1 >= this.n;

Object[] var2 = new Object[var1];

for(int var3 = 0; var3 < this.n; ++var3) {

var2[var3] = this.q[(this.first + var3) % this.q.length];

this.q = var2;

this.first = 0;

this.last = this.n;

public void enqueue(Item var1) {

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;

public Item dequeue() {

if (this.isEmpty()) {

throw new NoSuchElementException("Queue underflow");

} else {

Object var1 = this.q[this.first];

this.q[this.first] = null;
--this.n;

++this.first;

if (this.first == this.q.length) {

this.first = 0;

if (this.n > 0 && this.n == this.q.length / 4) {

this.resize(this.q.length / 2);

return var1;

public class QueueTester {

public QueueTester() {

public static void main(String[] var0) {

Queue var1 = new Queue();

Scanner var2 = new Scanner(System.in);

System.out.println("Enter 1 to enqueue");

System.out.println("Enter 2 to dequeue");

System.out.println("Enter 0 to exit");

boolean var3 = false;

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);

public class StringReversal implements Reversal {

public String reverse(String data) {

char[] validData = data.toCharArray();

for(int i = 0; i < validData.length / 2; i++) {

char temp = validData[i];

validData[i] = validData[validData.length - i - 1];

validData[validData.length - i - 1] = temp;

return new String(validData);

public static void main(String[] args) {

StringReversal sr = new StringReversal();

System.out.println(sr.reverse("I am nil das"));

System.out.println(sr.reverse("I like JAVA"));

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;

public class TestPackage {


public TestPackage() {

public static void main(String[] var0) {

Addition var1 = new Addition();

System.out.println(var1.add(5, 6));

Output :
G:\Assignment 3\Nine>java TestPackage
11

Problem Statement 10:


Create a class FactorialIterative which defines a method for finding out the factorial of a given number in
iteratively. Create another class FactorialRecursive which defines a method for finding out the factorial of
a given number in recursively. Place the FactorialIterative class in "iterative" package and the
FactorialRecursive class in "recursive" package. Create a class TestFactorial containing main() method in
"default" package which uses both classes (i.e. FactorialIterative and FactorialRecursive) to find out the
factorial of a number. Compile and run this program without using an IDE.

Code :
package iterative;

public class FactorialIterative {

public int factorialIterative(int n){

int result=1,i=1;

while(i<=n){

result=result*i;

i++;

return result;

package recursive;

public class FactorialRecursive {

public int factorialRecursive(int n){


if(n <= 1){

return 1;

else{

return n*factorialRecursive(n-1);

import iterative.FactorialIterative;

import recursive.FactorialRecursive;

public class TestFactorial {

public static void main(String[] args) {

FactorialIterative fi = new FactorialIterative();

System.out.println(fi.factorialIterative(10));

FactorialRecursive fr = new FactorialRecursive();

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.*;

public class TestResult {


public static void main(String[] args) {
String stdName;
int marks;
int sum = 0;
float percent;
int[] subMarks = new int[6];
Scanner sc = new Scanner(System.in);
System.out.println("Enter Student's Name : ");
stdName = sc.nextLine();
System.out.println("Enter the marks of the student :");
try {
for (int i = 0; i < subMarks.length; i++) {
marks = sc.nextInt();
if (marks < 0) {
throw new RangeException();
} else if (marks > 50) {
throw new RangeException();
} else {
subMarks[i] = marks;
}
}

System.out.println("Student's Name : " + stdName);


System.out.println("Result :: ");
for (int j = 0; j < subMarks.length; j++) {
System.out.println("Subject " + (j + 1) + " : " + subMarks[j]);
}
for (int k = 0; k < subMarks.length; k++) {
sum = sum + subMarks[k];
}
System.out.println("Total marks : " + sum);
percent = ((sum / (subMarks.length)) * 2);
System.out.println("Percentage : " + percent);
} catch (RangeException e) {
System.out.println("All the marks should be in the range of 0 to 50
!!");
System.out.println("Try running the program again.");
return;
}
}
}
public class RangeException extends Exception {
public RangeException() {
super();
}
}

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;

public class bankAccount {


public static void main(String[] args) {
int minBalance = 1000;
int withdrawBalance;
int currentBalance;
Scanner sc = new Scanner(System.in);
try {
System.out.println("Enter amount to withdraw : ");
withdrawBalance = sc.nextInt();
if (withdrawBalance > minBalance) {
throw new lowBalance();
} else {
currentBalance = (minBalance - withdrawBalance);
System.out.println("Current balance in your account : " +
currentBalance);
}
} catch (lowBalance lb) {
System.out.println("!!!!..Transaction failed..!!!!");
System.out.println("Low Balance in your Account");
}
}
}
public class lowBalance extends Exception {
lowBalance() {
super();
}
}

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.*;

public class stringExcept extends Exception {


String str;

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");
}
}

public void first() {


try {
throw new MyException1();
this.second();
} catch (MyException1 e1) {
System.out.println("My Exception-1 Caught");
} catch (MyException2 e3) {
System.out.println("My Exception-2 caught in first() method");
}
}

public static void main(String[] args) {


TestExceptClass obj = new TestExceptClass();
obj.first();
}
}
public class MyException1 extends Exception {
MyException1() {
super();
}
}
public class MyException2 extends Exception {
MyException2() {
super();
}
}

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;

public class TestClass {


Scanner sc = new Scanner(System.in);
int choice;

public void test() throws MyException1, MyException2, MyException3 {


System.out.println("Choose a Number from below :");
System.out.println("(1)");
System.out.println("(2)");
System.out.println("(3)");
choice = sc.nextInt();
if (choice == 1) {
throw new MyException1();
} else if (choice == 2) {
throw new MyException2();
} else if (choice == 3) {
throw new MyException3();
} else {
System.out.println("Enter a valid choice");
}
}
}
public class TestDemo {
public static void main(String[] args) {
TestClass tc = new TestClass();
try {
tc.test();
} catch (MyException1 | MyException2 | MyException3 e) {
// no code is needed here
}
}
}
public class MyException1 extends Exception {
MyException1() {
//super();
System.out.println("MyException1 arrised.");
}
}
public class MyException2 extends Exception {
MyException2() {
// super();
System.out.println("MyException2 arrised.");
}
}
public class MyException3 extends Exception {
MyException3() {
// super();
System.out.println("MyException3 arrised.");
}
}
Output :
G:\VSCode\Java\Assignment4\eight>java TestDemo
Choose a Number from below :
(1)
(2)
(3)
3
MyException3 arrised.

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;

Student(String name, int rollNo, int age, String course) throws


AgeNotWithinRange, NameNotValid {

this.rollNo = rollNo;
this.course = course;

if (name == null || name.trim().isEmpty()) {


System.out.println("Incorrect format of string");
return;
}
Pattern p = Pattern.compile("[^A-Za-z0-9]");
Matcher m = p.matcher(name);
boolean b1 = m.matches();
boolean b2 = m.find();
if (b1 == true || b2 == true)
throw new NameNotValid();
else
this.name = name;
if (age < 15) {
throw new AgeNotWithinRange();
} else if (age > 21) {
throw new AgeNotWithinRange();
} else {
this.age = age;
}
}

public void display() {


System.out.println("Name : " + this.name);
System.out.println("Age : " + this.age);
System.out.println("Roll No : " + this.rollNo);
System.out.println("Course : " + this.course);
}
}
public class NameNotValid extends Exception {
NameNotValid() {
System.out.println("Name should not contain any special character or
number");
}
}
public class AgeNotWithinRange extends Exception {
AgeNotWithinRange() {
System.out.println("Age should be between 15 to 21");
}
}
public class TestDemo {
public static void main(String[] args) {
try {
Student st = new Student(“Nil", 17, 22, "cse");
st.display();

} catch (AgeNotWithinRange | NameNotValid e) {


// TODO: handle exception
}
}
}

Output :
G:\VSCode\Java\Assignment4\nine>java TestDemo
Age should be between 15 to 21

Problem Statement 10:


Write a Java program to find the exception "Marks out of Bounds". Create a class Student. If mark is
greater than 100, it must generate user defined exception called "Marks out of Bounds" and throw it.

Code :
import java.util.Scanner;

public class Student {


int marks;

Student(int marks) throws MarksOutOfBound {


this.marks = marks;

if(marks < 0){


throw new MarksOutOfBound();
}
else if(marks > 100){
throw new MarksOutOfBound();
}
}

public void display() {


System.out.println("Marks entered is : " + this.marks);
}
}
public class MarksOutOfBound extends Exception {
MarksOutOfBound() {
System.out.println("Marks should be between 0 - 100");
}
}
import java.util.Scanner;

public class Test {


public static void main(String[] args) {
int testMarks;
Scanner sc = new Scanner(System.in);
System.out.print("Enter marks : ");
testMarks = sc.nextInt();
try {
Student st = new Student(testMarks);
st.display();
} catch (MarksOutOfBound e) {
// TODO: handle exception
}
}
}

Output :
G:\VSCode\Java\Assignment4\ten>java Test
Enter marks : 25
Marks entered is : 25

Problem Statement 11:


Write a program in Java to check if entered data is alphabet or digit. If it is alphabet, then print if it is
capital or small case. If digit is entered throw user defined exception "digit not allowed".

Code :
public class testClass {
char input;

testClass(char input) throws DigitNotAllowed {


this.input = input;
if (input >= 65 && input <= 90) {
System.out.println("Upper Case Alphabet");
} else if (input >= 97 && input <= 122) {
System.out.println("Lower Case Alphabet");
} else {
throw new DigitNotAllowed();
}
}
}
public class DigitNotAllowed extends Exception {
DigitNotAllowed() {
System.out.println("Digit and Special Character Entering is not allowed");
}
}
import java.util.Scanner;

public class demo {


public static void main(String[] args) {
char testInput;
Scanner sc = new Scanner(System.in);
System.out.print("Enter for Case checking : ");
testInput = sc.next().charAt(0);
try {
testClass tc = new testClass(testInput);
} catch (Exception e) {
// TODO: handle exception
}
}
}

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

Problem Statement 12:


Write Java programs to implement the followings (take the input from the keyboard):
a. Find the length of a String.
b. Find the length of a String except whitespaces.
c. Convert a double value to a String.
d. Check whether a String contains characters or digits or both.
e. Input two Strings – check whether the second String is reverse of the first one or not.
f. Compare two Strings and find if they are equal or not.
g. Remove the 6th to 8th characters from a String.
h. Convert a String to lowercase and uppercase.
i. Reverse a String.

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;

public class noWhiteSpace {


public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String :");
String input = sc.nextLine();
// System.out.println(input);
String str = input;
int len = input.replace(" ", "").length();
System.out.println("Length of the String without White Space : " + len);
}

}
(c)
import java.util.Scanner;

public class doubleToString {


public static void main(String[] args) {
double input;
String changed;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Double value : ");
input = sc.nextDouble();
changed = Double.toString(input);
System.out.println("After converting the Double to String : " + changed);
System.out.println("And Length of this String : " + changed.length());
}
}
(d)
import java.util.Scanner;

public class demo {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String : ");
String input = sc.nextLine();
String n = ".*[0-9].*";
String A = ".*[A-Z].*";
String a = ".*[a-z].*";
if (input.matches(n) && !(input.matches(A) || input.matches(a))) {
System.out.println("Contains only Numbers");
} else if ((input.matches(A) || input.matches(a)) && !(input.matches(n))) {
System.out.println("Contains only Characters");
} else if ((input.matches(A) || input.matches(a)) && input.matches(n)) {
System.out.println("Contains both Numbers and Characters");
} else {
System.out.println("Contains only Special Characters");
}
}
}
(e)
import java.util.Scanner;

public class checkStrings {


public static void main(String[] args) {
String first;
String second;
String reversed = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter first String :");
first = sc.nextLine();
System.out.println("Enter second String :");
second = sc.nextLine();
for (int i = second.length() - 1; i >= 0; i--) {
reversed = reversed + second.charAt(i);
}
if (first.equals(reversed)) {
System.out.println("Second String is the reverse of the First String");
} else {
System.out.println("Second String is not the reverse of the First
String");
}
}
}
(f)
import java.util.Scanner;

public class checkStrings {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first String :");
String first = sc.nextLine();
System.out.println("Enter second String :");
String second = sc.nextLine();
if (first.equals(second)) {
System.out.println("Both Strings are Equal");
} else {
System.out.println("Strings are not Equal");
}
}
}
(g)
import java.util.Scanner;
public class removeChar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String :");
String input = sc.nextLine();
StringBuilder sb = new StringBuilder(input);
sb.deleteCharAt(5);
sb.deleteCharAt(7);
System.out.println("After removing 6th and 8th char the string is :");
System.out.println(sb.toString());
}
}
(h)
import java.util.Scanner;

public class lowerUpper {


public static void main(String[] args) {
String lower;
String upper;
Scanner sc = new Scanner(System.in);
System.out.println("Enter String mixing LowerCase & UpperCase letters :");
String input = sc.nextLine();
lower = input.toLowerCase();
upper = input.toUpperCase();
System.out.println("Whole String in Lower Case :");
System.out.println(lower);
System.out.println("Whole String in Lower Case :");
System.out.println(upper);
}
}
(i)
import java.util.Scanner;

public class reverseString {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String :");
String input = sc.nextLine();
StringBuilder sb = new StringBuilder(input);
sb.reverse();
System.out.println("Reversed String :");
System.out.println(sb.toString());
}
}

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

Problem Statement 13:


Write a Java program to implement Thread concept.

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

Problem Statement 14:


Write a program that demonstrates the use of multithreading with the use of three counters with three
threads defined for each. Three threads should represent the counters as follows:
a. One counter starts from 5 and increments with the step of 5.
b. Second counter starts from 10 and increments with the step of 10.
c. Third counter starts with 100 and increments with the step of 100.
Assign proper priority to the threads and then run the threads.

Code :
public class counterOne extends Thread {
int counter = 5;

public void run() {


try {
for (int i = 5; i <= 10; i += 5) {
System.out.println("Thread " + Thread.currentThread().getName() + "
printed " + i);
}
} catch (Exception e) {
System.out.println("Exception Caught");
}
}
}
public class counterTwo extends Thread {
public void run() {
try {
for (int i = 10; i <= 100; i += 10) {
System.out.println("Thread " + Thread.currentThread().getName() + "
printed " + i);
}
} catch (Exception e) {
System.out.println("Exception Caught");
}
}
}
public class counterThree extends Thread {
public void run() {
try {
for (int i = 100; i <= 1000; i += 100) {
System.out.println("Thread " + Thread.currentThread().getName() + "
printed " + i);
}
} catch (Exception e) {
System.out.println("Exception Caught");
}
}
}
public class testCounter {
public static void main(String[] args) {
counterOne c1 = new counterOne();
counterTwo c2 = new counterTwo();
counterThree c3 = new counterThree();
c1.setName("counterOne");
c2.setName("counterTwo");
c3.setName("counterThree");
c1.setPriority(8);
c2.setPriority(9);
c3.setPriority(10);
c1.start();
c2.start();
c3.start();
}
}

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

Problem Statement 15:


Write a Java program to use join() and isAlive() in Multi-Threading.

Code :
public class counterOne extends Thread {
int counter = 5;

public void run() {


try {
for (int i = 5; i <= 10; i += 5) {
System.out.println("Thread " + Thread.currentThread().getName() + "
printed " + i);
}
} catch (Exception e) {
System.out.println("Exception Caught");
}
}
}
public class counterTwo extends Thread {
public void run() {
try {
for (int i = 10; i <= 100; i += 10) {
System.out.println("Thread " + Thread.currentThread().getName() + "
printed " + i);
}
} catch (Exception e) {
System.out.println("Exception Caught");
}
}
}
public class counterThree extends Thread {
public void run() {
try {
for (int i = 100; i <= 1000; i += 100) {
System.out.println("Thread " + Thread.currentThread().getName() + "
printed " + i);
}
} catch (Exception e) {
System.out.println("Exception Caught");
}
}
}
public class testCounter {
public static void main(String[] args) {
counterOne c1 = new counterOne();
counterTwo c2 = new counterTwo();
counterThree c3 = new counterThree();
c1.setName("counterOne");
c2.setName("counterTwo");
c3.setName("counterThree");
c1.setPriority(8);
c2.setPriority(9);
c3.setPriority(10);
// System.out.println("Alive ? : " + c1.isAlive());
c1.start();
System.out.println("Alive ? : "+c1.isAlive());
try {
c1.join();
} catch (Exception e) {
System.out.println("Exception Caught");
}
c2.start();
System.out.println("Alive ? : "+c2.isAlive());
try {
c2.join();
} catch (Exception e) {
System.out.println("Exception Caught");
}
c3.start();
System.out.println("Alive ? : "+c3.isAlive());
}
}

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

Potrebbero piacerti anche