Java Day 7

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

1. which exceptions are made mandatory by compiler to handle?

compile type error is mandatory to handle bcz it is crucial to handle at time of compilation

2. what is exception propagation?

exception is propagated to the method which has called it if it is not able to handle it.

3. what is difference between throw and throws?

Throw:- throw exception explicitly (means we can throw any exception any time anywhere)

Throws:- to declare the exception

4. difference between final finally and finalize

final: it is a keyword used to define a method or variable which can’t be changed throughout
the program

finally: we use finally {} after try and catch method to run the rest code whether try catch occurs
or not

finalize: finalize() method is called by garbage collector and performs the cleaning with respect to
the object before its destruction.

5. Custom Exception/User Defined exception:- Create own exception based on application


Assignment:-
1)create a program which take a product price from user
if price is negative throw Userdefined Exception
NegativePrice and display message Price in negative not allowed

public class Price extends RuntimeException {


Price(int a) {
System.out.println("Enter a greater no. ");
}
}
package exceptionHandling;
import java.util.*;
public class Demo {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter a NO.");
int a=sc.nextInt();
try {
if(a<0) {
throw new Price(a);
}
}
catch(Price e) {
System.out.println("Enter no greater than 0");
}
System.out.println("End");
}

 
2)Demostrate use of throws in exception handling
package exceptionHandling;
/*Demostrate use of throws in exception handling*/
public class HandlingDemo{
public static int divide(int a,int b) throws ArithmeticException{
int sum=0;
try {
sum=a/b;
}catch(ArithmeticException e) {
System.out.println("b cant be 0");
}
return sum;
}

public static void main(String[] args) {


divide(2,0);

}
3)Take names of 5 students display them using foreach loop
After that ask use to search for a student
Enter the name to search:priya
if present display found at position 3rd[2nd index]position
otherwise not found
package array;
public class StudentSearch {

public static void main(String[] args) {


String[] stud= {"aditya","priya","shanu","subham","akash"};
int flag=0,i=0;
for(String nm:stud) { //for each loop
if(nm=="priya") {
flag=1;
i++;
break;
}
}
/*for(i=0;i<stud.length;i++) { //for loop
if(stud[i]=="priya") {
flag=1;
break;
}
}*/
if(flag==1) {
System.out.println("priya student is found in position "+
(i+1));
}
else {
System.out.println("Not Found");
}
}

4)create a array of prices of products and find the product with highest price and lowest price
package array;
/*create a array of prices of products and find the product with highest price
and lowest price*/
public class Product {

public static void main(String[] args) {


int price[]={12,34,54,24,65,87,97,02,22,32};
int min=price[0],max=price[0];
for(int i=1;i<price.length;i++) {
if(min<price[i])
min=price[i];
else if(max>price[i])
max=price[i];
}
System.out.println("The array is: ");
for(int i=0;i<price.length;i++) {
System.out.print(price[i]+" ");
}
System.out.println();
System.out.println("The max price is: "+ max);
System.out.println("The min price is: "+ min);
}

}
5)Create 3 customer objects and store it into a arraylist
customer with id,name,age
and sort it by its age

public class Customer implements Comparable<Customer>{


int id,age;
String name;
Customer(int id, String name, int age){
super();
this.id=id;
this.name=name;
this.age=age;
}
@Override
public int compareTo(Customer obj) {
int flag;
if(age==obj.age) {
flag=0;
}
else if(age<obj.age) {
flag=-1;
}
else {
flag=1;
}
return flag;
}

}
public class CustomerArrayListDemo {

public static void main(String[] args) {


Customer cust1= new Customer(1001,"ADITYA",22);
Customer cust2= new Customer(101,"SHANU",2);
Customer cust3= new Customer(1001,"AKASH",32);
ArrayList<Customer> arrlist = new ArrayList<Customer>();
arrlist.add(cust1);
arrlist.add(cust2);
arrlist.add(cust3);
Collections.sort(arrlist);
for(Customer c: arrlist) {
System.out.println(c.id+ c.age+c.name);
}
}

}
6) Multiple Catch
package exceptionPractice;

import java.io.FileWriter;
import java.io.IOException;

public class MultipleCatch {

public static void main(String[] args) {


// TODO Auto-generated method stub
int[] arr= {23,45,67,43};
String str=null;
try {
for(int i=0;i<=arr.length+1;i++) {
System.out.println(arr[i]);
}
System.out.println(str.length());
System.out.println(2/0);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Enter less than array size");
}catch(NullPointerException e) {
System.out.println("Cant show null length");
}catch(ArithmeticException e) {
System.out.println("the denominator cant be 0");
}catch(Exception e) {
System.out.println("There is something wrong in the code");
}

Collection framework:
Classes
Interface
Algorithm

There is no limitation of size

List:- it can duplicate element

Arraylist: list<data type> al = new ArrayList< data type >(); or


ArrayList< data type > al = new ArrayList< data type >();

Search of element is faster in arraylist

Linkedlist:- list< data type > ll= new LinkedList< data type >(); or
LinkedList< data type > ll= new LinkedList< data type >();

Insertion and deletion of element is faster in linkedlist


NOTE:- linkedlist is used during addition or delection and arraylist is used during sorting

HashSet: - --------------------does not maintain order

LinkedHashlist: -------------------- maintain order in which we have provided

Treeset: -------------------------automatically sorts

Collection:- it is an interface

Collections:- it is a class with static methods

To sort user defined objects added in collection


1. Comparable: -
It is single sorting sequence

It uses only method CompareTo

2. Comparater:-

Multiple catch:- more then 1 catch to deal with multiple error

Try with Resource:-

Catch(Exception e)------------------ should be written as a last catch.

Lab book:
Exercise 1: Validate the age of a person and display proper message by using user defined exception.
Age of a person should be above 15.

public class LessAge extends RuntimeException{


LessAge(int a){
System.out.println("Less than 15 years old");
}
}

public class LabBookEx5_1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter the age");
int a=sc.nextInt();
try {
if(a<15) {
throw new LessAge(a);
}
}
catch(LessAge e) {
System.out.println("make age greater than 15");
}
System.out.println("End");

Exercise 2: Write a Java Program to validate the full name of an employee. Create and throw a user
defined exception if firstName and lastName is blank.

public class NameException extends RuntimeException {


NameException(String str) {
System.out.println("first and last name is null");
}

public class LabBookEx5_2 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String firstName=null;
String lastName=null;
//System.out.println("Enter 1st name");
//firstName = sc.nextLine();
System.out.println("Enter last name");
lastName = sc.nextLine();
try {
if(firstName == null) {
throw new NameException(firstName);
}
if(lastName == null) {
throw new NameException(lastName);
}
}catch(NameException e) {
System.out.println("The name CANT BE NULL");
}

Exercise 3: Create an Exception class named as “EmployeeException”(User defined Exception) in a


package named as “com.cg.eis.exception” and throw an exception if salary of an employee is below than
3000. Use Exception Handling mechanism to handle exception properly.

public class EmployeeException extends RuntimeException {


EmployeeException(int a){
System.out.println("salary is less than 3000");
}
}

import java.util.Scanner;

public class LabBookEx5_3 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter the salary of an employee");

try {
int salary=sc.nextInt();
if(salary<3000) {
throw new EmployeeException(salary);
}
}catch(EmployeeException e) {
System.out.println("Increase the salary");
}catch(Exception e) {
System.out.println("There is some error. Handle that");
}
System.out.println("bye bye");

You might also like