BK Mod 3 Java

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

EXP NO:

PROGRAMS ON EXCEPTION HANDLING

DATE:

QUESTION 1:

Write Java programs to handle the following exceptions.

a. InputMismatchException:

b. NumberFormatException:

c. ArrayIndexOutofBoundsException:
d.NullPointerException:

AIM:

To complete the given programs using exception handling.

CODE:

import java.util.InputMismatchException;
import java.util.Scanner;
public class EX_1 {
void p(){
Scanner s = new Scanner(System.in);
System.out.println("ENTER AN INTEGER");
try{
int i= s.nextInt();
System.out.println(i);
}
catch(InputMismatchException ex) {
System.out.println(ex);
}
s.close();
}
void n(){
try {
int i =Integer.parseInt("hello");
System.out.println(i);
}
catch(NumberFormatException ex) {
System.out.println(ex);
}

717822L210
}
void m(){
int arr[]= {1,2,3,4,5};
try {
System.out.println(arr[7]);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
}
void o() {
String st=null;
try {
System.out.println(st.length());
}
catch(NullPointerException e) {
System.out.println(e);
}
}
public static void main(String[] args) {

System.out.println("717822L210");
System.out.println("M Dheivani ");
EX_1 k=new EX_1();
k.p();
k.n();
k.m();
k.o();
System.out.println("normal flow...");
}
}

OUTPUT:

RESULT:

Therefore,the given questions have been completed using an exception handling mechanism.

717822L210
717822L210
QUESTION 2:

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 complete the given programs using exception handling.

CODE:
package module3;
import java.util.*;
public class Math
{
private static double sqrt(double number) {
return number*number; }
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("717822L210");
System.out.println("M Dheivani ");
try{
int number;
Scanner s = new Scanner(System.in);
System.out.println("Enter the number: ");
number = s.nextInt();
if (number < 0) {
throw new ArithmeticException();}
else{
System.out.format("Square root: "+Math.sqrt(number));}}
catch(ArithmeticException e){
System.out.println("Error");
}
}

}
OUTPUT

RESULT:

Therefore,the given questions have been completed using an error handling mechanism.

717822L210
QUESTION 3:

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 complete the given programs using exception handling.

CODE:

package module3;
public class Course
{ String dept;
int coursenum;
int credit;
public Course(String dept, int coursenum, int credit){
try{
if (dept.length() != 3 || coursenum < 100 && coursenum >
499 || credit < 0.6 && credit > 6){
throw new CourseException(dept, coursenum, credit);
}
else{
System.out.println("Department name = "+dept+", Course number =
"+coursenum+", Credit = "+credit);
}
}
catch(CourseException e){
System.out.println("Need to clear the Course Exception error");}}
public static void main(String[] args) {
System.out.println("717822L210");
System.out.println("Dheivani M");
Course v1 = new Course("ece", 101, 5);
System.out.println("");
Course v2 = new Course("AI", 151, 4);
System.out.println("");
Course v3 = new Course("IT", 250, 4);
System.out.println("");
Course v4 = new Course("CSD", 149, 2);
System.out.println("");
Course v5 = new Course("CST", 500, 1);
System.out.println("");
Course v6 = new Course("Civil", 160, 2);
}

}
717822L210
OUTPUT:

RESULT:

Therefore,the given questions have been completed using an error handling mechanism.

717822L210
QUESTION 4:

Write a Java program based on the following statements:

• 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 complete the given programs using exception handling.

CODE:

package module3;
public class UsedCarException extends Exception{
public UsedCarException(int VIN ,String make, int year, int mileage,
double price)
{
System.out.println("Error needs to be cleared!!");
}
}
package module3;
public class Usedcar {
int VIN, year, mileage;
String make;
double price;
public Usedcar(int VIN, String make, int year, int mileage,
double price) { try
{
if (VIN < 1000 && VIN > 9999 || make != "Ford"&& make !=
"Toyoto"&& make != "Honda"&& make !=
"Crysler"&& make != "Other" || year < 1997 && year > 2017 ||
mileage < 0 || price < 0)
{
throw new UsedCarException(VIN, make, year, mileage, price);
}
else {
System.out.println("Car name = "+make+", VIN number =
"+VIN+",Year = "+year+", Mileage ="+mileage+", Price = "+price);
}
}
catch(UsedCarException e)
{
System.out.println("Need to clear the exception");
}
}
public static void main(String[] args) {

717822L210
System.out.println("717822L210");
System.out.println("M Dheivani ");
Usedcar v1 = new Usedcar(2136,"Ford",2013,30,20000.00);
System.out.println();
Usedcar v2 = new Usedcar(1001,"Hyundai",2016,30,30000.00);
System.out.println();
Usedcar v3 = new Usedcar(1001,"Ford",2020,30,10000.00);
System.out.println();
Usedcar v4 = new Usedcar(1001,"Toyoto",2015,-10,10000.00);
System.out.println();
Usedcar v5 = new Usedcar(1001,"Honda",2016,30,10000.00);
}
}

717822L210
OUTPUT:

RESULT:

Therefore,the given questions have been completed using an error handling mechanism.

717822L210
EXP NO:
PROGRAMS USING LIST COLLECTIONS

DATE:

QUESTION 5:

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 complete the given programs using list collection.

CODE:
package module3;
import java.util.*;
public class CarCareDemo {
public static void main(String[] args) {
System.out.println("717822L210");
System.out.println("M Dheivani ");
Boolean flag=false;
List<String> l=new ArrayList<String>();
l.add("oil change");
l.add("tire rotation");
l.add("battery check");
l.add("brake inspection");
List<Integer> l1=new ArrayList<Integer>();
l1.add(25);
l1.add(22);
l1.add(15);
l1.add(5);
Scanner input = new Scanner(System.in);
System.out.println("Enter Selection:");
String choice = input.nextLine();
for(int x = 0; x < l1.size();++x)
{
if(l.get(x).equals(choice))
{
flag=true;
System.out.println(l.get(x) +" price is $" + l1.get(x));
}
}

if(flag==false)
{
System.out.println("invalid");
}
}

717822L210
OUTPUT:

RESULT:

Therefore,the given questions have been completed using list collections.

717822L210
QUESTION 6:

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 complete the given programs using list collection.

CODE:
package module3;
import java.util.*;
public class exno6 {
public static void main(String[] args) {
System.out.println("717822L210");
System.out.println("M Dheivani ");
List<String> flower=new LinkedList<>();
flower.add("Rose");
flower.add("Lily");
flower.add("Dalia");
flower.add("jasmine");
flower.add("lotus");
System.out.println(flower.isEmpty())
; flower.remove("Dalia");
for(String i:flower)
{
System.out.println(i);
}
}

717822L210
OUTPUT:

RESULT:

Therefore,the given questions have been completed using list collections.

717822L210
EXP NO:

PROGRAMS USING SET COLLECTIONS


DATE:

QUESTION 7:

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 complete the given programs using set collection.

CODE:
package module3;
import java.util.*;
public class EX7 {
public static void main(String[] args) {
/ System.out.println("717822L210");
System.out.println("M Dheivani ");
HashSet<String> animals=new HashSet<>();
animals.add("dog");
animals.add("ant");
animals.add("bird");
animals.add("elephant")
; animals.add("cat");
Iterator <String> i=animals.iterator();
while(i.hasNext()) {
System.out.println(i.next());}
animals.add("monkey");
animals.remove("monkey");
System.out.println(animals.contains("monkey"));
}

717822L210
OUTPUT:

RESULT:

Therefore,the given questions have been completed using set collections.

717822L210
QUESTION 8:

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:

Empid Name Age Designation Salary

7624 SMITH 23 CLERK 10000


7640 ALLEN 35 SALESMAN 25000
7625 JONES 27 MANAGER 50000
7641 MARTIN 30 SALESMAN 30000
7601 TURNER 28 SALESMAN 27000
• 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 complete the given programs using set collection.

CODE:

package module3;
import java.util.*;
public class Employee implements Comparable<Employee>{
private Integer empid;
private String name;
private Integer age;
private String
destination; private
Integer salary;
public Employee(int empid,String name,int age,String destination,int
salary)
{
this.empid=empid
;
this.name=name;
this.age=age;
this.destination=destination
; this.salary=salary;
}
public void setEmpid(int id)
{

717822L210
empid=id;
}
public int getEmpid()
{
return empid;
}
public void setName(String n)
{
name=n;
}
public String getName()
{
return name;
}
public void setAge(int a)
{
age=a;
}
public int getAge()
{
return age;
}
public void setDestination(String a)
{
destination=a;
}
public String getDestination()
{
return destination;
}
public void setSalary(int a)
{
salary=a;
}
public int getSalary()
{
return salary;
}
public String toString()
{
return empid+""+name +""+age+""+destination+""+salary+"";
}
public int compareTo(Employee e){
return this.empid.compareTo(e.empid);
}
public static void main(String arg[])
{
System.out.println("717822L210");
System.out.println("M Dheivani ");
TreeSet <Employee> employeeset=new TreeSet<>();
employeeset.add(new Employee(7624,"smith",23,"clerk",10000));
employeeset.add(new Employee(7640,"allen",35,"SALESMAN",25000));
employeeset.add(new
Employee(7625,"jones",27,"MANAGER",50000));
employeeset.add(new
Employee(7641,"martin",30,"SALESMAN",30000)); employeeset.add(new
Employee(7601,"turner",28,"SALESMAN",27000));
Iterator<Employee> i=employeeset.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
for(Employee e:employeeset)
717822L210
{

if(e.destination.equalsIgnoreCase("manager"))
{
System.out.println("manager id"+e.empid);
}
}
for(Employee e:employeeset)
{
if(e.destination.equalsIgnoreCase("salesman"))
{
System.out.println("name and age of salesman"+e.name+""+e.age);
}
}
for(Employee e:employeeset)
{
if(e.salary>25000)
{
System.out.println(" greater then 250000 salary"+e.destination);
}
}
}
}
OUTPUT:

RESULT:
Therefore,the given questions have been completed using set collections.

717822L210
717822L210
717822L210
.

717822L210
EXP NO:
PROGRAMS USING MAP COLLECTIONS
DATE:

QUESTIONS 9:

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 complete the given programs using map collection.

CODE:

package module3;
import java.util.*;
public class Exno9 {
public static void main(String[] args) {
System.out.println("717822L210");
System.out.println("M Dheivani ");
HashMap<Integer , String> fruits=new HashMap<>();
fruits.put(301,"apple");
fruits.put(302,"mango ");
fruits.put(303,"Grapes");
fruits.put(304,"papaya");
fruits.put(305,"strawberry");
System.out.println(fruits.get(302));
System.out.println(fruits.containsKey(303));
System.out.println(fruits.remove(302));
System.out.println(fruits.entrySet());
}
}

717822L210
OUTPUT:

RESULT:

Therefore,the given questions have been completed using map collections.

717822L210
QUESTION 10:

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:

Key (String) Value (Basket Object)

Banana Basket [item=Banana, price=40.0]


Apple Basket [item=Apple, price=105.0]
Mango Basket [item=Mango, price=75.0]
Orange Basket [item=Orange, price=55.0]
Papaya Basket [item=Papaya, price=25.0]
• 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 complete the given programs using map collection.

CODE:

package module3;
import java.util.*;
public class Basket
{
private String item;
private Double price;
public Basket(String item,Double price)
{
this.item=item;
this.price=price
;
}
void setItem(String item)
{
this.item=item;
}
String getItem()
{
return item;
}

717822L210
void setPrice(Double price)
{
this.price=price;
}
public String toString()
{
return "item "+item+" price"+price;
}
public static void main(String[] args)
{
System.out.println("717822L210");
System.out.println("M Dheivani ");
TreeMap<String,Basket> fruits=new TreeMap<>();
Basket b=new Basket("banana",40.0);
Basket b1=new Basket("Apple",105.0);
Basket b2=new Basket("Mango",75.0);
Basket b3=new Basket("Orange",55.0);
Basket b4=new Basket("gauva",25.0);
fruits.put("Banana",b);
fruits.put("Apple",b1);
fruits.put("Mango",b2);
fruits.put("Orange",b3);
fruits.put("Papaya",b4);
System.out.println(fruits.entrySet())
;
//
System.out.println(fruits.containsValue(25.0));
System.out.println(fruits.containsKey("Orange"));
fruits.remove("Orange");
System.out.println(fruits.values());
System.out.println(fruits.keySet());
}

717822L210
OUTPUT:

RESULT:

Therefore,the given questions have been completed using map collections.

717822L210
EXP NO:
PROGRAMS USING WRAPPER CLASSES
DATE:

QUESTION 11:

Write a Java program to use Integer wrapper class for the following tasks:

a. Convert a string representing a financial figure "1234" to an Integer object for further calculations.

b. Parse a string "5678" representing a transaction amount to a primitive int for a


calculation function.

c. Compare the values of two Integer objects representing two different account balances (e.g.,
10 and 20) and determine which is larger.

d. For a security feature, calculate the number of one-bits in the binary representation of an
account ID (e.g., 29).

e. Convert an Integer representing a total transaction count (e.g., 100) to a String for a report.

AIM:

To complete the given questions using wrapper classes.

CODE:
package module3;
public class IntegerWrapperExample {
public static void main(String[] args) {
System.out.println("717822L210");
System.out.println("M Dheivani ");
String financialFigureString = "1234";
Integer financialFigureInteger =
Integer.valueOf(financialFigureString);
System.out.println("Converted Integer object: " +
financialFigureInteger);
String transactionAmountString = "5678";
int transactionAmount = Integer.parseInt(transactionAmountString);
System.out.println("Parsed int value: " + transactionAmount);
Integer balance1 = 10;
Integer balance2 = 20;
int comparisonResult = balance1.compareTo(balance2);
if (comparisonResult < 0)
{
System.out.println(balance2 + " is larger than " + balance1);
}
else if (comparisonResult > 0)
{
System.out.println(balance1 + " is larger than " + balance2);
}
else
717822L210
{
System.out.println("Both balances are equal.");
}
int accountID = 29;
int numberOfOneBits = Integer.bitCount(accountID);
System.out.println("Number of one-bits in binary representation of
account ID " + accountID + ": " + numberOfOneBits);
Integer totalTransactionCount = 100;
String transactionCountString = totalTransactionCount.toString();
System.out.println("Converted String for report: " +
transactionCountString);
}

OUTPUT:

RESULT:

Therefore,the given questions have been completed using wrapper class.

717822L210
717822L210
QUESTION 12:

Write a Java program to use Character wrapper class for the following tasks:

a. Verify if a given character (e.g., 'a') from user input is a letter, ensuring that only
alphabetic characters are used in certain fields.

b. Check if a given character (e.g., '1') from a numeric input field is a digit.

c. Convert a lowercase character (e.g., 'b') to uppercase for standardized display, and vice versa
(e.g., 'G' to lowercase).

d. Check if a given character (e.g., ' ') in user input is a whitespace, to validate proper word spacing
in text fields.

AIM:

To complete the given questions using wrapper classes.

CODE:

package module3;
import java.util.Scanner;
public class CharacterWrapperExample {
public static void main(String[] args) {
System.out.println("717822L210");
System.out.println("M Dheivani ");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
char inputChar = scanner.next().charAt(0);
boolean isLetter = Character.isLetter(inputChar);
System.out.println("Is the character a letter? " + isLetter);
System.out.print("Enter a character: ");
char digitChar = scanner.next().charAt(0);
boolean isDigit = Character.isDigit(digitChar);
System.out.println("Is the character a digit? " + isDigit);
System.out.print("Enter a lowercase or uppercase character: ");
char caseConversionChar = scanner.next().charAt(0);
char convertedChar;
if (Character.isLowerCase(caseConversionChar))
{
convertedChar = Character.toUpperCase(caseConversionChar);
}
else
{
convertedChar = Character.toLowerCase(caseConversionChar);
}
System.out.println("Converted character: " + convertedChar);
System.out.print("Enter a character: ");
char whitespaceChar = scanner.next().charAt(0);
boolean isWhitespace = Character.isWhitespace(whitespaceChar);
System.out.println("Is the character a whitespace? " +
isWhitespace);
scanner.close();
}

717822L210
OUTPUT:

RESULT:

Therefore,the given questions have been completed using wrapper class.

717822L210
717822L210

You might also like