0% found this document useful (0 votes)
47 views26 pages

Java 113-6

The document describes Java programs that demonstrate the use of wrapper classes. It includes programs that: 1. Convert a string representing a financial figure to an Integer object for calculations. 2. Parse a string representing a transaction amount to a primitive int for calculations. 3. Compare the values of two Integer objects representing account balances and determine which is larger. 4. Demonstrate autoboxing and unboxing of primitive types to their corresponding wrapper classes. The programs aim to use wrapper classes for various tasks like conversions, comparisons and calculations.

Uploaded by

dontk2179
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views26 pages

Java 113-6

The document describes Java programs that demonstrate the use of wrapper classes. It includes programs that: 1. Convert a string representing a financial figure to an Integer object for calculations. 2. Parse a string representing a transaction amount to a primitive int for calculations. 3. Compare the values of two Integer objects representing account balances and determine which is larger. 4. Demonstrate autoboxing and unboxing of primitive types to their corresponding wrapper classes. The programs aim to use wrapper classes for various tasks like conversions, comparisons and calculations.

Uploaded by

dontk2179
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

21DD13-Java Programming

Ex no: 6
PROGRAM USING EXCEPTIONS HANDLING MECHANISM
Date:

Question 6.1:

Write Java programs to handle the following exceptions:


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

To write java programs using exception handling mechanism.


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

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

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) {
EX_1 k=new EX_1();
k.p();
k.n();
k.m();
k.o();
System.out.println("normal flow...");
}
}

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Output:

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

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Question 6.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 write java programs using exception handling mechanism.


Code:
import java.util.Scanner;
public class EX_2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("ENTER AN INTEGER");
try{
int i= sc.nextInt();
double k=Math.sqrt(i);
if (i<0) {
throw new ArithmeticException();
}
System.out.println(k);
}
catch(ArithmeticException ex) {
System.out.println(ex);
}
sc.close();
}
}

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Output:

Result:
Thus, the java program using exception handling mechanism was executed successfully and the Output
was verified.

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Question 6.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.
• 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 write java programs using exception handling mechanism.


Code:
class CourseException extends Exception{
CourseException(String dept, int coursenum, int credit){
System.out.println("Course Exception has occurred");
}
}
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+", Coursenumber =
"+coursenum+", Credit = "+credit);
}
}catch(CourseException e){
System.out.println("Need to clear the Course Exception error");
}
}
public static void main(String[] args) {
Course v1 = new Course("CSE", 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);

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

}
}
Output:

Result:
Thus, the java program using exception handling mechanism was executed successfully and the output
was verified.

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Question 6.4:

Write a Java program based on the following statements:


• 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 write java programs using exception handling mechanism.


Code:
class UsedCarException extends Exception{
public UsedCarException(int VIN ,String make, int year, int mileage, double price) {
System.out.println("Error needs to be cleared!!");
}
}
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) {
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);
}

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

}
Output:

Result:
Thus, the java program using exception handling mechanism was executed successfully and the output
was verified.

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Ex no: 7
PROGRAM USING WRAPPER CLASSES
Date:

Question 7.1:
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 write java programs using wrapper classes.

Code:
public class IntergerWrapperClass {
public static void main(String[] args) {
String financialFigure = "1234";
Integer financialInteger = Integer.valueOf(financialFigure);
System.out.println("Financial Integer Object: " + financialInteger);
String transactionAmount = "5678";
int parsedTransactionAmount = Integer.parseInt(transactionAmount);
System.out.println("Parsed Transaction Amount (primitive int): " + parsedTransactionAmount);
Integer balance1 = 10;
Integer balance2 = 20;
int comparisonResult = balance1.compareTo(balance2);
if (comparisonResult < 0)
System.out.println("Balance 2 is larger than Balance 1");
else if (comparisonResult > 0)
System.out.println("Balance 1 is larger than Balance 2");
else
System.out.println("Balance 1 and Balance 2 are equal");
int accountID = 29;
int numberOfOneBits = Integer.bitCount(accountID);
System.out.println("Number of one-bits in the binary representation of Account ID: " +
numberOfOneBits);
Integer transactionCount = 100;
String reportString = transactionCount.toString();
System.out.println("Transaction Count as String for Report: " + reportString);
}
}

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Output:

Result:
Thus, the java program using wrapper classes was executed successfully and the output was verified

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Question 7.2:
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 write java programs using wrapper classes.

Code:
import java.util.Scanner;
public class CharacterWrapper {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character to check if it's a letter: ");
char inputLetter = scanner.next().charAt(0);
if (Character.isLetter(inputLetter)) {
System.out.println(inputLetter + " is a letter.");
} else {
System.out.println(inputLetter + " is not a letter.");
}
System.out.print("Enter a character to check if it's a digit: ");
char inputDigit = scanner.next().charAt(0);
if (Character.isDigit(inputDigit)) {
System.out.println(inputDigit + " is a digit.");
} else {
System.out.println(inputDigit + " is not a digit.");
}
System.out.print("Enter a lowercase or uppercase character to convert: ");
char inputChar = scanner.next().charAt(0);
if (Character.isLowerCase(inputChar)) {
char upperCaseChar = Character.toUpperCase(inputChar);
System.out.println("Uppercase conversion: " + upperCaseChar);
} else if (Character.isUpperCase(inputChar)) {
char lowerCaseChar = Character.toLowerCase(inputChar);
System.out.println("Lowercase conversion: " + lowerCaseChar);
} else {
System.out.println("Invalid input.");
}
System.out.print("Enter a character to check if it's a whitespace: ");
char inputWhitespace = scanner.next().charAt(0);
if (Character.isWhitespace(inputWhitespace)) {
System.out.println(inputWhitespace + " is a whitespace.");
} else {
System.out.println(inputWhitespace + " is not a whitespace.");
}

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

scanner.close();
}
}
Output:

Result:
Thus, the java program using wrapper classes was executed successfully and the output was verified.

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Ex no: 8
PROGRAM USING LIST COLLECTION
Date:

Question 8.1:

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 write java programs using List collection.

Code:
import java.util.*;
public class CarCareDemo{
public static void main(String[] args){
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");
}
}
}

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Output:

Result:
Thus, the java program using List collection was executed successfully and the output was verified.

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Question 8.2:

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 write java programs using List collection.

Code:
import java.util.*;
public class FlowerList{
public static void main(String[] args){
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);
}
}
}

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Output:

Result:
Thus, the java program using List collection was executed successfully and the output was verified.

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Ex no: 9
PROGRAM USING MAP COLLECTION
Date:

Question 9.1:

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 write java programs using map collection.


Code:
import java.util.*;
public class FruitCollection{
public static void main(String[] args){
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());

}
}

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Output:

Result:
Thus, the java program using Map collection was executed successfully and the output was verified.

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Question 9.2:

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. • 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 write java programs using map collection.


Code:
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; }
void setPrice(Double price){this.price=price;}
public String toString(){
return "item "+item+" price"+price;
}
public static void main(String[] args){
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("Papaya",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.containsKey("Orange"));
fruits.remove("Orange");
System.out.println(fruits.values());
System.out.println(fruits.keySet());
}
}

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Output:

Result:
Thus, the java program using Map collection was executed successfully and the output was verified.

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Ex no: 10
PROGRAM USING SET COLLECTION
Date:

Question 10.1:

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 write java programs using set collection.

Code:
import java.util.*;
public class AnimalSet{

public static void main(String args[]) {


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

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Output:

Result:
Thus, the java program using set collection was executed successfully and the output was verified.

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Question 10.2:

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. • 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 write java programs using set collection.

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

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

return empid+" "+name +" "+age+" "+destination+" "+salary+" ";


}
public int compareTo(Employee e){
return this.empid.compareTo(e.empid);
}
public static void main(String arg[]){
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){
if(e.destination.equalsIgnoreCase("manager")){
System.out.println("managerid"+e.empid);
}
}
for(Employee e:employeeset){
if(e.destination.equalsIgnoreCase("salesman")){
System.out.println("name and age ofsalesman"+e.name+" "+e.age);
}
}
for(Employee e:employeeset){
if(e.salary>25000){
System.out.println(" greater then 250000salary"+e.destination);
}
}
}
}

717822D113 – DIVYA LAKSHMI P


21DD13-Java Programming

Output:

Result:
Thus, the java program using set collection was executed successfully and the output was verified.

717822D113 – DIVYA LAKSHMI P

You might also like