Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Record 3 VINU

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

Ex no: 41

Date:14/11/2022 Handling Unchecked Exceptions

Question

Write Java programs to handle the following exceptions:


a. InputMismatchException
b. NumberFormatException
c. ArrayIndexOutofBoundsException
d. NullPointerException

Aim
To develop a java program to handle the unchecked exceptions.

Code

// InputMismatchException
package noitpecxe;
import java.util.InputMismatchException;
import java.util.Scanner;
public class DemoInputMismatchException {
public static void main(String[] args) {
Scanner bm=new Scanner(System.in);
try {
int n=bm.nextInt();
int a=0;
int b=1;
int c;
System.out.print(a+" "+b+" ");
for(int i=2;i<n;i++) {
c=a+b;
System.out.print(c+" ");
a=b;
b=c;
}
}catch(InputMismatchException e) {
System.out.println(e);
}
}
}

//NumberFormatException
package noitpecxe;
import java.util.Scanner;
public class NumberFormat {
public static void main(String[] args) {

717821f216-GUNARANJAN R
Scanner bm=new Scanner(System.in);
String s=bm.next();
try {
int fact=1;
int number=Integer.parseInt(s);
for(int i=1;i<=number;i++) {
fact=fact*i;
}
System.out.println(fact);
}catch(NumberFormatException e) {
System.out.println(e);
}
bm.close();
}
}

// ArrayIndexOutofBoundsException
package noitpecxe;
import java.util.Scanner;
public class DemoArrayIndexBounds {
public static void main(String[] args) {
Scanner bm=new Scanner(System.in);
int[] arr=new int[5];
arr[0]=bm.nextInt();
arr[1]=bm.nextInt();
arr[2]=bm.nextInt();
arr[3]=bm.nextInt();
arr[4]=bm.nextInt();
try {
arr[5]=bm.nextInt();
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i]+" ");
}
bm.close();
}
}

// NullPointerException
package noitpecxe;
public class NullPointer {
public static void main(String[] args) {
try {
String st1="Java programing";
System.out.println(st1);
String st2=null;
System.out.println(st2.length());
}catch(NullPointerException e) {
System.out.println(e);
}
}
}

717821f216-GUNARANJAN R
Output

Result

Thus, the Java program to handle the unchecked exception has been developed successfully and the
output was verified .

717821f216-GUNARANJAN R
Ex no: 42
Date:14/11/2022 Handling Arithmetic Exception

Question
Write an application that throws and catches an ArithmeticException when you attempt to take the
square root of a negative value. Prompt the user for an input value and try the Math.sqrt() method on
it. The application either displays the square root or catches the thrown Exception and displays an
appropriate message.

Aim

To develop a java program to handle Arithmetic Exception

Code

package noitpecxe;

import java.util.Scanner;

public class ArithmeticDemo {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);


System.out.println("Enter any value:");
int a=sc.nextInt();
Squareroot(a);
sc.close();
}

private static void Squareroot(int a) {


try {
if(a>=0) {
double val=Math.sqrt(a);
System.out.println(val);

}
else {
throw new ArithmeticException();
}
}
catch(ArithmeticException e) {
System.out.println(e);
}
}

717821f216-GUNARANJAN R
Output

Result
Thus, the Java to handle arithmetic exception has been developed successfully and the output was
verified.

717821f216-GUNARANJAN R
Ex no: 43
Date:14/11/2022 Implementing User Defined Exception

Question
Write a Java program based on the following statements:
• Create a CourseException class that extends Exception and whose constructor receives a String
that holds a college course’s department (for example, CIS), a course number (for example, 101),
and a number of credits (for example, 3). Save the file as CourseException.java.
• Create a Course class with the same fields and whose constructor requires values for each field.
Upon construction, throw a CourseException if the department does not consist of three letters, if the
course number does not consist of three digits between 100 and 499 inclusive, or if the credits are
less than 0.5 or more than 6. Save the class as Course.java.
• Write an application that establishes an array of at least six Course objects with valid and invalid
values. Display an appropriate message when a Course object is created successfully and when one is
not.

Aim
To develop a java program to create and handle the user defined exception.

Code

package noitpecxe;
public class CourseException extends Exception{
public CourseException(String course) {
super(course);
}
}

package noitpecxe;
public class Course {
private String course_department;
private String course_number;
private float credits;

public Course(String course_department,String course_number,float credits) {


try {
if(course_department.length()==3 && course_number.length()==3 &&
(credits>0.5 && credits<6)) {

this.course_department=course_department;
this.course_number=course_number;
this.credits=credits;
}else {
throw new
CourseException("course_department"+"course_number"+"creadits");
}
}catch(CourseException e) {
System.out.println(e);
}

717821f216-GUNARANJAN R
}
public String toString() {
return "Course [course_department=" + course_department + ", course_number=" +
course_number + ", credits="+ credits + "]";
}
}

package noitpecxe;
public class Testcourse {

public static void main(String[] args) {


Course[] c1=new Course[6];
c1[0]=new Course("CSE","123",2);
c1[1]=new Course("IT","174",4);
c1[2]=new Course("CST","89",1);
c1[3]=new Course("ECE","567",7);
c1[4]=new Course("EEE","123",0.5f);
c1[5]=new Course("AIDS","265",1);
for(int i=0;i<6;i++) {
System.out.println(c1[i]);
}
}
}

Output

Result
Thus, the Java program to create and handle the user defined exception has been developed
successfully and the output was verified.

717821f216-GUNARANJAN R
Ex no: 44
Date:14/11/2022 Implementing User Defined Exception

Question
Create a UsedCarException class that extends Exception;
• its constructor receives a value for a vehicle identification number (VIN) that is passed to the parent
constructor so it can be used in a getMessage() call. Save the class as UsedCarException.java.
• Create a UsedCar class with fields for VIN, make, year, mileage, and price. The UsedCar
constructor throws a UsedCarException when the VIN is not four digits; when the make
is not Ford, Honda, Toyota, Chrysler, or Other; when the year is not between 1997 and 2017
inclusive; or either the mileage or price is negative. Save the class as UsedCar.java.
• Write an application that establishes an array of at least seven UsedCar objects and handles any
Exceptions. Display a list of only the UsedCar objects that were constructed successfully. Save the
file as ThrowUsedCarException.java.

Aim
To develop a java program to create and handle the user defined exception.

Code
package noitpecxe;
public class UsedCarException extends Exception{
public UsedCarException(String VId_number) {
super(VId_number);
}
}

package noitpecxe;
public class UsedCar {
private String VIN;
private String make;
private int year;
private int mileage;
private double price;

public UsedCar(String VIN,String make,int year,int mileage,double price) {


try {
if(VIN.length()==4 && (make.equals("Ford") || make.equals("Honda") ||
make.equals("Toyota") || make.equals("Chrysler")) && (year>=1997 && year<=2017) &&
mileage>0 && price>0) {
this.VIN=VIN;
this.make=make;
this.year=year;
this.mileage=mileage;
this.price=price;

}else {
throw new UsedCarException("VIN");
}
}catch(UsedCarException e){
System.out.println(VIN);
}

717821f216-GUNARANJAN R
}
public String toString() {
return "UsedCar [VIN=" + VIN + ", make=" + make + ", year=" + year + ", "
+ "mileage=" + mileage + ", price=" + price+ "]";
}
}

package noitpecxe;
public class ThrowUsedCarException {
public static void main(String[] args) {
UsedCar[] car=new UsedCar[7];
car[0]=new UsedCar("2396","Honda",2010,10000,83000);
car[1]=new UsedCar("2059","Ford",2018,100002,23000);
car[2]=new UsedCar("111","TVS",1999,110000,56000);
car[3]=new UsedCar("9","Toyota",1947,100001,70000);
car[4]=new UsedCar("8976","Chrysler",2021,-10,74000);
car[5]=new UsedCar("5432","BMW",2003,597660,-83000);
car[6]=new UsedCar("8523","RR",2023,743568,330000);
for(int i=0;i<7;i++) {
System.out.println(car[i]);
}
}
}
Output

Result
Thus, the Java program to create and handle the user defined exception has been developed
successfully and the output was verified.

717821f216-GUNARANJAN R
Ex no:45
Date:14/11/2022 Implementing JAVA Collections - ArrayList

Question
Write an application for Cody’s Car Care Shop that shows users a list (ArrayList) of available
services: oil change, tire rotation, battery check, or brake inspection. Allow the user to enter a string
that corresponds to one of the options, and display the option and its price as $25, $22, $15, or $5,
accordingly. Display an error message if the user enters an invalid item.
Aim
To develop a java program for the given condition using java collections.

Code

package noitpecxe;
import java.util.ArrayList;
import java.util.Scanner;

public class CarCareShop {

public static void main(String[] args) {


Scanner bm=new Scanner(System.in);
ArrayList<String> list=new ArrayList<String>();
list.add("oil change\n");
list.add("tire rotation\n");
list.add("battery check\n");
list.add("brake inspection\n");
System.out.println(list);
System.out.println("Enter your choice");
String str=bm.nextLine();
if(str.equalsIgnoreCase("oil change")) {
System.out.println("$25");
}
else if(str.equalsIgnoreCase("tire roation")) {
System.out.println("$22");
}
else if(str.equalsIgnoreCase("battery check")) {
System.out.println("$15");

717821f216-GUNARANJAN R
}
else if(str.equalsIgnoreCase("brake inspection")) {
System.out.println("$5");
}
bm.close();
}
}

Output

Result
Thus, the Java program for the given condition has been developed successfully and the output was
verified.

717821f216-GUNARANJAN R
Ex no: 46
Date:21/11/2022 Implementing JAVA Collections- Linked List

Question
Write an application using LinkedList that contains Flower names Rose, Lily, Dalia and Jasmine.
Perform following set of operations on LinkedList:
a. Add a new flower Lotus.
b. Verify whether the LinkedList is empty or not.
c. Remove the flower Dalia from the LinkedList.
d. Display all the elements in the LinkedList.

Aim

To develop a java program for the given condition using java collections.

Code

package noitpecxe;

import java.util.LinkedList;

public class FlowersList {

public static void main(String[] args) {

LinkedList<String> list=new LinkedList<String>();

list.addFirst("Rose");
list.addFirst("Lily");
list.addFirst("Dalia");
list.addFirst("Jasmine");
list.addLast("Lotus");

System.out.println(list);
System.out.println(list.isEmpty());
System.out.println(list.remove(1));
System.out.println(list);

717821f216-GUNARANJAN R
Output

Result
Thus, the Java program for the given condition has been developed successfully and the output was
verified.

717821f216-GUNARANJAN R
Ex no: 47
Date:21/11/2022 Implementing JAVA Collections - HashSet

Question
Write a Java program based on the following conditions:
a. Create a HashSet and add these strings: "dog", "ant", "bird", "elephant", "cat".
b. Use an Iterator to print the items in the set.
c. Add a new element into the set.
d. Delete an element from the set.
e. Check whether “ant” is present in the set.

Aim

To develop a java program for the given condition using java collections.

Code

package noitpecxe;

import java.util.HashSet;
import java.util.Iterator;

public class DemoSet {

public static void main(String[] args) {

HashSet<String> hset= new HashSet<String>();

hset.add("dog");
hset.add("ant");
hset.add("bird");
hset.add("elephant");
hset.add("cat");

Iterator<String> it=hset.iterator();

while(it.hasNext()) {
System.out.println(it.next());
}

hset.add("lion");
System.out.println(hset);
hset.remove("ant");
System.out.println(hset.contains("ant"));
}

717821f216-GUNARANJAN R
Output

Result
Thus, the Java program for the given condition has been developed successfully and the output was
verified.

717821f216-GUNARANJAN R
Ex no: 48
Date:21/11/2022 Implementing JAVA Collections - TreeSet

Question
Write a Java program for the statements given below:
a. Create a class Employee with attributes empid, name, age, designation and salary. Include a
parameterized constructor to assign the values to each attribute. Create get and set methods for all the
fields. Include a toString() method.
b. The Employee class must implement Comparable interface and override the compareTo()
method to sort the employees based in the empid.
c. Create a TreeSet to store five employees given below and perform the following operations:

• Display all the employees.

• Display the empid of the employees who are managers.


• Display the name and age of all the employees who are salesman.
• Display the designation of the employees who earn more than Rs. 25000.
Aim
To develop a java program for the given condition using java collections.

Code
package noitpecxe;
public class Employee implements Comparable{
private int empid;
private String name;
private int age;
private String designation;
private double salary;

public Employee(int empid, String name, int age, String designation, double salary) {
this.empid = empid;
this.name = name;
this.age = age;
this.designation = designation;
this.salary = salary;
}
public int getEmpid() {
return empid;
}
public void setEmpid(int empid) {
this.empid = empid;
}

717821f216-GUNARANJAN R
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String toString() {
return "["+empid+","+name+","+age+","+designation+","+salary+"]";
}
public int compareTo(Object o) {
Employee emp=(Employee)o;
if(this.getEmpid() > emp.getEmpid()) {
return 1;
}else if(this.getEmpid() < emp.getEmpid()) {
return -1;
}else {
return 0;
}
}
}

package noitpecxe;
import java.util.Iterator;
import java.util.TreeSet;
public class DemoTreeSet {

public static void main(String[] args) {


Employee[] emp=new Employee[5];
emp[0]=new Employee(7624,"SMITH",23,"CLERK",10000.0);
emp[1]=new Employee(7640,"ALLEN",35,"SALESMAN",25000.0);
emp[2]=new Employee(7625,"JONES",27,"MANAGER",50000.0);
emp[3]=new Employee(7641,"MARTIN",30,"SALESMAN",30000.0);
emp[4]=new Employee(7601,"TURNER",28,"SALESMAN",27000.0);
TreeSet<Employee> set=new TreeSet<Employee>();
for(int i=0;i<5;i++) {
set.add(emp[i]);
}

717821f216-GUNARANJAN R
System.out.println(set);
Iterator<Employee> it=set.iterator();
Employee n=null;
while(it.hasNext()) {
n=it.next();
if(n.getDesignation().equals("MANAGER")) {
System.out.println(n.getEmpid());
}
}
it=set.iterator();
while(it.hasNext()) {
n=it.next();
if(n.getDesignation().equals("SALESMAN")) {
System.out.println(n.getName()+" "+n.getAge());
}
}
it=set.iterator();
while(it.hasNext()) {
n=it.next();
if(n.getSalary()==25000.0) {
System.out.println(n.getDesignation());
}
}
}
}

Output

Result
Thus, the Java program for the given condition has been developed successfully and the output was
verified.

717821f216-GUNARANJAN R
Ex no: 49
Date:21/11/2022 Implementing JAVA Collections - HashMap

Question
Create a HashMap that consists of Fruit names Apple, Mango, Grapes and Papaya with the key
values 301, 302, 303 and 304 respectively. Develop a program to perform basic operations on
HashMap:
a. Add a new fruit Strawberry with a key 305.
b. Display the fruit name for the key 302.
c. Check whether the map has a key 303 or not.
d. Remove an element from the map. e. Display all the elements of the HashMap.

Aim

To develop a java program for the condition using java collections.

Code

package noitpecxe;

import java.util.HashMap;

public class DemoMap {

public static void main(String[] args) {

HashMap<Integer,String> map=new HashMap<Integer,String>();

map.put(301,"Apple");
map.put(302,"Mango");
map.put(303,"Grapes");
map.put(304,"Papaya");
map.put(305,"Strawberry");

System.out.println(map.get(302));
System.out.println(map.containsKey(303));
map.remove(303);

System.out.println(map);

717821f216-GUNARANJAN R
Output

Result
Thus, the Java program for the given condition has been developed successfully and the output was
verified

717821f216-GUNARANJAN R
Ex no: 50
Date:21/11/2022 Implementing JAVA Collections - TreeMap

Question
Write a Java program for the statements given below:
a. Create a class Basket with attributes item and price. Include a parameterized constructor to
assign the values to each attribute. Create get and set methods for all the fields. Include a
toString() method.
b. Create a TreeMap to store five items given below and perform the following operations:

• Display all the elements in the map.


• Check whether the map contains any item with price Rs. 25.0.
• Check whether the map contains the key “Orange”.
• Remove an entry from the map.
• Display all the values in the map.
• Display all the keys in the map.

Aim
To develop a java program for the given condition using java collections.

Code

package noitpecxe;

public class Basket {

private String item;


private double price;

public Basket(String item,double price) {


this.item=item;
this.price=price;
}

public String getItem() {


return item;
}

public void setItem(String item) {


this.item = item;
}

public double getPrice() {


return price;

717821f216-GUNARANJAN R
}

public void setPrice(double price) {


this.price = price;
}

@Override
public String toString() {
return "Basket [item=" + item + ", price=" + price + "]";
}

package noitpecxe;

import java.util.TreeMap;

public class DemoTreeMap {

public static void main(String[] args) {

int count=0;
Basket[] basket=new Basket[5];
basket[0]=new Basket("Banana",40.0);
basket[1]=new Basket("Apple",105.0);
basket[2]=new Basket("Mango",75.0);
basket[3]=new Basket("Orange",55.0);
basket[4]=new Basket("Papaya",25.0);

TreeMap<String,Basket> map=new TreeMap<String,Basket>();

map.put("Banana", basket[0]);
map.put("Apple", basket[1]);
map.put("Mango", basket[2]);
map.put("Orange", basket[3]);
map.put("Papaya", basket[4]);

System.out.println(map.get("Banana"));
System.out.println(map.get("Apple"));
System.out.println(map.get("Mango"));
System.out.println(map.get("Orange"));
System.out.println(map.get("Papaya"));

for (int i = 0; i < 5; i++) {


if (basket[i].getPrice() == 25.0) {
System.out.println(map.containsValue(basket[i]));
count++;
break;
}
}
if (count==0) {
System.out.println("false");
}

717821f216-GUNARANJAN R
System.out.println(map.containsKey("Orange"));
System.out.println(map.remove("Papaya"));
System.out.println(map.values());
System.out.println(map.keySet());
}

Output

Result
Thus, the Java program for the given condition has been developed successfully and the output was
verified.

717821f216-GUNARANJAN R

You might also like