SlideShare a Scribd company logo
1 of 49
Exceptions 
sohamsengupta@yahoo.com1
Definition 
• An exception is an abnormal condition that arises 
while running a program. Exception handling in 
Java is same as in C++. 
• This is how Java handles Exceptions. When an 
exception occurs in a method, an object of 
Exception type is thrown. The method can either 
handle the exception or pass it on to the calling 
method. 
• Example of exceptions are : Attempt to divide by 
zero causes an exception to be thrown at run time, 
Attempt to call a method on an object that has is 
null. 
sohamsengupta@yahoo.com2
Keywords 
• Exceptions are typically generated by Java run 
time system. They could also be thrown manually 
by writing a code that throws exception. 
• Exception handling block: 
try{ 
… 
} 
catch(ExceptionType1 e){ …} 
catch(ExceptionType2 e){ …} 
. 
. 
. 
finally { 
... 
} 
sohamsengupta@yahoo.com3
Exception Types 
Throwable 
Exception Error 
Exception: This class is used for exceptional 
conditions that a user program should catch. Also 
when we generate Exceptions manually in the 
code we extend this class. Example divide by zero 
etc. 
Error: These are the exception that does not occur 
under the normal circumstances and hence are not 
excepted to be caught by the code. JRE handles 
these kind of exceptions. 
sohamsengupta@yahoo.com4
Exceptions 
• We will be looking only at Exception class. 
Some Subclasses of Exception: 
1. IOException 
2. ClassNotFoundException 
3. RuntimeException 
a. ArithmeticException 
b. NullPointerException 
c. ArrayIndexOutOfBoundsException 
d. ClassCastException 
sohamsengupta@yahoo.com5
Without Exceptions 
• Let us write a code that does not handle exception. 
class DivideByZero 
{ 
public static void main(String str[]) 
{ 
int z= 45/0; 
} 
} 
No compilation errors. 
Run time error generated by the system: 
Exception in thread "main" 
java.lang.ArithmeticException: / by zero 
at DivideByZero.main(DivideByZero.java:5) 
Default Exceptional handler handles the exception. 
This can sometimes run into pages. 
sohamsengupta@yahoo.com6
Why to handle exceptions 
• To give a user friendly message to the user. 
• To save all the work or to close open files or 
sockets etc. 
• To allow program to terminate gracefully. 
class DivideByZero{ 
public static void main”(String str[]) { 
int z=90; 
try{ 
z= 45/0; 
} catch(ArithemeticException e) 
{ System.out.println(“Division by zero”); 
z=0; // resetting to a valid value 
} 
System.out.println(“After catching exception”); 
} 
output: Division by zero 
After catching exception 
sohamsengupta@yahoo.com7
Multiple catches 
• There could be more than one exception that is 
raised in a piece of code. In this case we use 
multiple catch. We however have to be careful to 
catch Exceptions of subclass types first and then 
super class types. 
sohamsengupta@yahoo.com8
sohamsengupta@yahoo.com9 
class Catches { 
public static void main(String[] args) { 
try{ 
int i=10/Integer.parseInt(args[0]); 
} 
catch(ArithmeticException e){ 
System.out.println("div by zero"); 
} 
catch(ArrayIndexOutOfBoundsException e1){ 
System.out.println(“out of bound"); 
} 
} 
} c:> java Catches 0 > output : div by zero 
c:> java Catches > output: out of bound
Multiple catch must ensure that super Exception comes later 
sohamsengupta@yahoo.com10 
class DivideByZero { 
public static void main(String[] args) { 
try{ 
int i=10/0; 
} 
catch(Exception e){ 
System.out.println(“general error"); 
} 
catch(ArithmeticException e1){ 
System.out.println(“div by zero ");} 
} 
} 
• exception java.lang.ArithmeticException has already been caught 
catch(ArithmeticException e1){ 
^ 
1 error
Multiple try 
• A try statement can be nested inside another try 
statement. If an exception is raised in the inner try 
block and it does not have a catch handler for that 
exception then this exception is caught by the 
catch statement of the outer try block ( if there is a 
matching handler) 
sohamsengupta@yahoo.com11
throws 
• A method that does not want to handle exception 
can delegate this to the calling method. 
class DivideByZero { 
public static void method() throws ArithmeticException { 
int i=10/0; 
} 
public static void main(String[] args) { 
try{ 
sohamsengupta@yahoo.com12 
method(); 
}catch(Exception e){ 
System.out.println(“some exception ");} 
} 
}
throw & rethrow 
• Generate an Exception condition manually in the 
code 
class DivideByZero { 
public static void method() { 
try{ 
throw new NullPointerException(“exception”); 
}catch(NullPointerException e1){ 
System.out.println(“null pointer exception in method"); 
throw e1; 
} 
} 
} 
sohamsengupta@yahoo.com13
public static void main(String[] args) { 
try{ 
method(); 
} 
catch(NullPointerException e1){ 
System.out.println(“null pointer exception in main");} 
} 
} 
sohamsengupta@yahoo.com14
finally 
• When exceptions occur the program’s normal flow 
is disrupted. It is no longer in sequence. The 
methods that work with the system resources like 
files and sockets remain open if the program ends 
prematurely during exceptions. 
• finally is a block of statements that will definitely 
get executed whether or not an exception occurs. 
So the methods that deal with resources could 
release them in the finally block. 
sohamsengupta@yahoo.com15
sohamsengupta@yahoo.com16 
class Catches { 
public static void main(String[] args) { 
try{ 
int i=10/Integer.parseInt(args[0]); 
System.out.println(“Normal execution”); 
} 
catch(ArithmeticException e){ 
System.out.println("div by zero"); 
} 
catch(ArrayIndexOutOfBoundsException e1){ 
System.out.println(“out of bound"); 
} 
finally { System.out.println(“Thank you”); } 
} 
}
Output 
c:> java Catches 0 
> output : div by zero 
Thank you 
c:> java Catches 
> output: out of bound 
Thank you 
java Catches 1 
> output: Normal execution 
Thank you 
sohamsengupta@yahoo.com17
Code snippet 
class B { 
static int getVal(){ 
int x=12; 
int[] y=new int[5]; 
try{ 
return y[x]; 
}catch(ArithmeticException ae){ 
return -120; 
}finally{ 
return 940; 
} 
} 
public static void main(String[] ar) { 
System.out.println(getVal()); 
sohamsengupta@yahoo.com18 
}} 
Output: 940 
class B { 
static int getVal(){ 
int x=12; 
int[] y=new int[5]; 
try{ 
return y[x]; 
}catch(ArithmeticException ae){ 
return -120; 
} 
} 
public static void main(String[] ar) { 
System.out.println(getVal()); 
}} 
Exception in thread "main" 
java.lang.ArrayIndexOutOfBoundsE 
xception: 12 
at B.getVal(B.java:6) 
at B.main(B.java:12)
Another Code Snippet 
class B { 
static int getVal(){ 
int x=12; 
int[] y=new int[5]; 
try{ 
return y[x]; 
}catch(Exception ae){ 
return -120; 
} 
} 
public static void main(String[] ar) { 
System.out.println(getVal()); 
sohamsengupta@yahoo.com19 
}} 
Output: -120 
Exception catches subException 
ArrayIndexOutOfBoundsException 
and the catch Block Returns the -120 
Guess what if we omit the catch block and 
introduce the final block 
class B { 
static int getVal(){ 
int x=12; 
int[] y=new int[5]; 
try{ 
return y[x]; 
}finally{ 
return -570; 
} 
} 
public static void main(String[] ar) { 
System.out.println(getVal()); 
}}• 
Output -570 
• In the next slide we’ll omit the 
return statement from finally 
bloack. 
• See the magical perversion
Examples… contd. 
class B { 
static int getVal(){ 
int x=12; 
int[] y=new int[5]; 
try{ 
System.out.println("Inside try"); 
return y[x]; 
}finally{ 
System.out.println("From finally 
sohamsengupta@yahoo.com20 
without catch"); 
} 
} 
public static void main(String[] ar) { 
System.out.println(getVal()); 
}} Inside try 
From finally without catch 
Exception in thread "main" 
java.lang.ArrayIndexOutOfBoundsException: 12 
at B.getVal(B.java:7) 
at B.main(B.java:13) 
Checked Exception 
public static void main(String[] 
ar) { 
throw new Exception("My 
Exception"); 
} // Will be error Exception is 
checked and superclass of all. 
Replace with java.io.IOException, 
the same result will u get. 
But… 
public static void main(String[] ar) { 
throw new ArithmeticException("My 
Exception"); 
} // is OK it is subclass of Unchecked 
Exception 
java.lang.RuntimeException
A few facts about Exception handling 
• A try block must have at least one catch block or one 
finally block. 
• A catch block can detect only the declared exception type 
or any subclass exception of that type 
• If we use multiple catch block, super class Exception must 
come after sub class ones 
• If we use finally, finally is executed in all the cases. Even 
return in suitable catch can’t stop it. 
• To make a program terminate “gracefully” , we use 
multiple catch block in proper order followed by a 
catch(Throwable t) block at last 
• In case of overriding, the subclass overrider method can’t 
declare to throw broader Checked Exceptions. 
sohamsengupta@yahoo.com21
More on Exception handling 
• To debug a program we must call the 
Exception.printStackTrace() method. It’s not a static 
method so u must have use an instance of Exception or its 
sub class to call this method. This works in stack (LIFO) 
telling u how the Exception originated and in what line 
number of the code. Remember, this prints the stack trace 
on the console. So, be careful to call this method and make 
sure that u can see the console. This is generally performed 
inside the catch block because it’s only there that u get an 
instance of the raised exception. 
• From the experts' desk: Always try to incorporate proper 
exception handling in your application to make your end 
user feel comfortable and the developer get going in 
debugging a logical bug! 
sohamsengupta@yahoo.com22
User-defined exceptions 
• A user defined exception class can be created if 
one finds that there is no in-built exceptions that 
matches the exceptions that will be thrown by the 
code. 
• This class is created by extending the Exception 
class. 
sohamsengupta@yahoo.com23
class AgeClass { 
private int age ; 
private String description; 
public AgeClass(int age, String desc){ 
setAge(age); 
setDescription(desc); 
} 
public void setAge(int age){ 
if (age==0 || age>150) 
throw new AgeException(“Age = “+ age + “ is invalid”); 
else 
this.age=age; 
} 
public void setDescription(String desc){ 
// some code to describe age 
} 
sohamsengupta@yahoo.com24
class AgeException extends Exception { 
String exStr; 
public AgeException() 
{ 
exStr= “Age not in the permitted range”; 
} 
public AgeException(String s) 
{ 
exStr=s; 
} 
public String toString() 
{ 
return Exception: ” + exStr; 
} 
} 
sohamsengupta@yahoo.com25
Exercises 
• For the Student class that we created in last 
exercise, throw an exception if the marks 
entered is out of range (0-100). 
sohamsengupta@yahoo.com26
Wrapper Classes 
sohamsengupta@yahoo.com27
Wrapper Classes • A class that is created over a primitive data 
types or other classes giving it more 
functionality. 
• java.lang.Integer 
• java.lang.Boolean 
• java.lang.Float 
• java.lang.Double 
• java.lang.Short 
• java.lang.Long 
• java.lang.Byte 
sohamsengupta@yahoo.com28
Integer 
• We will look at just one wrapper class. Other 
classes are just similar. (Use Java 
Documentation for reference). 
• Constructor Summary 
• Integer(int value) 
Constructs a newly allocated Integer 
object that represents the specified int value. 
• Integer(String s) 
Constructs a newly allocated Integer 
object that represents the int value indicated by 
the String parameter. 
sohamsengupta@yahoo.com29
Important methods 
• static int parseInt(String s) 
Parses the string argument as a signed 
decimal integer. 
• int intValue() 
Returns the value of this Integer as an int. 
• static String toString(int i) 
Returns a String object representing the 
specified integer. 
• static Integer valueOf(String s) 
Returns an Integer object holding the value 
of the specified String. 
sohamsengupta@yahoo.com30
Example 
• Get the year from the command line argument 
and check if it is a leap year. 
class LeapYear 
{ 
public static void main(String args[]){ 
if (args.length>1) || (args[0].length()<>4){ 
System.out.println(“Impoprer argument”); 
else { 
int year=Integer.parseInt(args[0]); 
if (leapYear(year) 
System.out.println(“Leap Year”); 
else 
System.out.println(“Not a leap year”); 
} 
boolean leapYear(int year) {…} 
} 
sohamsengupta@yahoo.com31
Utility Classes 
sohamsengupta@yahoo.com32
java.util 
• Java utility classes are packaged in java.util 
package. 
• Most of the utility classes are collections 
(group of objects). 
• Collection interface is the root in the 
hierarchy. 
• Other than this interface we will be looking at 
following important utility classes/interfaces: 
sohamsengupta@yahoo.com33
ArrayList 
* In java, arrays are of a fixed length. 
* ArrayList class is used to support dynamic 
arrays. 
* It is a type of collection class. 
* Constructors: 
• ArrayList(): builds an empty array list. 
• ArrayList(int capacity): builds an array list 
of size capacity. 
sohamsengupta@yahoo.com34
methods 
• boolean add(Object obj) 
• Object remove(int index) 
• void trimToSize() 
• Iterator iterator() 
• Object get(int index) 
sohamsengupta@yahoo.com35
Example 
ArrayList a1= new ArrayList(); 
a1.add("A"); 
a1.add("B"); 
a1.add("C"); 
System.out.println(a1); 
a1.remove(2); 
sohamsengupta@yahoo.com36
Iterator interface 
• This interface helps us to iterate through any 
collection classes. 
a. With iterator we can to remove elements from the 
underlying collection. 
b. Method names have been improved. 
boolean hasNext() 
Returns true if the iteration has more elements. 
sohamsengupta@yahoo.com37 
Object next() 
Returns the next element in the iteration. 
void remove() 
Removes from the underlying collection the 
last element returned by the iterator (optional 
operation).
• An iterator() method is provided in almost all the 
collection classes that returns Iterator object. 
ArrayList a1= new ArrayList(); 
a1.add("A"); 
a1.add("B"); 
a1.add("C"); 
Iterator iterator=a1.iterator(); 
while(iterator.hasNext()) 
{ 
String str=(String)iterator.next(); 
System.out.println(str); 
} 
sohamsengupta@yahoo.com38
java.util.Date • Date is an older class added in Java 1.0 SDK. 
• Most of its methods are deprecated. 
Constructors: 
Date(): Current date and time. 
sohamsengupta@yahoo.com39
Methods 
• boolean after(Date when) 
Tests if this date is after the specified 
date. boolean 
• before(Date when) 
Tests if this date is before the specified 
date. 
• int compareTo(Date anotherDate) 
Compares two Dates for ordering. 
• int compareTo(Object o) 
Compares this Date to another Object. 
sohamsengupta@yahoo.com40
java.util.Calendar 
• * This class provides a set of methods that helps us to 
work with dates. 
• * It is an abstract class. 
• * But there is a static method, getInstance(), in the 
Calendar class (that is implemented) which returns a 
Calendar object. 
• * This method assumes the default locale and time 
zone. 
• * Calendar cal=Calendar.getInstance(); 
• * This initializes object with current date and time. 
sohamsengupta@yahoo.com41
methods 
• 1. final int get( int calendarField) : example: int 
month=cal.get(Calendar.MONTH) 
• 2. final void set(int year, int month, int day, [ int 
hours, int minutes, int secs ]) 
• 3. final void clear() 
• 4. final void set(int which, int value) 
• 5. some integer constants which can be used with 
get method: MONTH, YEAR, DATE, HOUR, 
MINUTE, SECOND 
sohamsengupta@yahoo.com42
import java.util.*; Example 
class CalendarExample { 
static final String 
month[]={“Jan”,”Feb”,”Mar”,”Apr”,”May”,”Jun”,”Jly”,”Aug”,”S 
ep”,”Oct”,”Nov”,”Dec”}; 
public static void main(String str[]) { 
printPayBillDateHeader(); 
} 
public static printPayBillHeader() 
{ 
Calendar c=Calendar.getInstance(); 
String m=month[c.get(Calendar.MONTH)]; 
System.out.print(“Paybill for the months of “ + m); 
System.out.println(“ “+ c.get(Calendar.DATE)); 
sohamsengupta@yahoo.com43 
} 
}
Exercises 
I. An office maintains a record of documents it 
receives. Following details about the 
douments are maintained: 
a. Document date 
b. Name of the person who sent the document 
c. Name of the person to whom this document 
was addessed. 
d. Department of the person who sent tis 
sohamsengupta@yahoo.com44 
document 
e. summary
• Create a console based java application to 
1. Add document details 
2. Remove document details 
3. Modify document details 
4. Display chronologically all the documents 
received so far. 
sohamsengupta@yahoo.com45
II. An electric contains many electrical 
appliances. Appliances are classified into 
appliance types and they are kept in a 
particular location. When an appliance is 
added it is given a new unique id number 
starting from 1 upto 1000. An appliance is 
tested after every n no. of days depending 
on appliance types. 
sohamsengupta@yahoo.com46
• Now there are two types of users in the 
application: 
• 1. Managers - login :mgr, password:mgrpw 
• 2. Testers - login:tester1, password:tester1pw 
• login:tester2, password:tester2pw 
• A test data consist of 
• appliance id, date of test, result (pass/fail), 
comments. 
sohamsengupta@yahoo.com47
• Managers can add/delete/modify appliance 
types and locations. 
• Testers and managers can 
add/delete/modify appliances. 
• Testers can add test but cannot delete test. 
• A tester who has added a test can only 
update the test. 
sohamsengupta@yahoo.com48
• Write a console java program to 
• 1. Add/Delete/Modify appliance type. 
• 2. Add/Delete/Modify location. 
• 3. Add/Delete/Modify appliances. 
• 4. Displays a report with all tests taken so 
far. 
• 5. Displays outstanding tests. 
sohamsengupta@yahoo.com49

More Related Content

What's hot

Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsMiquel Martin
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAmbigaMurugesan
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handlingHemant Chetwani
 
Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
What is an exception in java?
What is an exception in java?What is an exception in java?
What is an exception in java?Pramod Yadav
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and AssertionsCore Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and AssertionsWebStackAcademy
 

What's hot (13)

Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Exception
ExceptionException
Exception
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-Knows
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java unit3
Java unit3Java unit3
Java unit3
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
 
Built in exceptions
Built in exceptions Built in exceptions
Built in exceptions
 
Exception handling
Exception handlingException handling
Exception handling
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
 
What is an exception in java?
What is an exception in java?What is an exception in java?
What is an exception in java?
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and AssertionsCore Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
 

Viewers also liked

SpringClean Brochure
SpringClean BrochureSpringClean Brochure
SpringClean BrochureSpringClean
 
Tips and tricks for creating CM14 Reports - Oracle Primavera Collaborate 14
Tips and tricks for creating CM14 Reports - Oracle Primavera Collaborate 14Tips and tricks for creating CM14 Reports - Oracle Primavera Collaborate 14
Tips and tricks for creating CM14 Reports - Oracle Primavera Collaborate 14p6academy
 
Schedule analysis what could possibly go wrong - Oracle Primavera Collaborat...
Schedule analysis what could possibly go wrong  - Oracle Primavera Collaborat...Schedule analysis what could possibly go wrong  - Oracle Primavera Collaborat...
Schedule analysis what could possibly go wrong - Oracle Primavera Collaborat...p6academy
 
EFFECTIVE USE OF LOCAL RESOURCES IN CLASS ROOM TEACHING
EFFECTIVE USE OF LOCAL RESOURCES IN CLASS ROOM TEACHING EFFECTIVE USE OF LOCAL RESOURCES IN CLASS ROOM TEACHING
EFFECTIVE USE OF LOCAL RESOURCES IN CLASS ROOM TEACHING Ramesh Prasad Badoni
 

Viewers also liked (11)

Xmpp and java
Xmpp and javaXmpp and java
Xmpp and java
 
Jsp1
Jsp1Jsp1
Jsp1
 
Core java day1
Core java day1Core java day1
Core java day1
 
SpringClean Brochure
SpringClean BrochureSpringClean Brochure
SpringClean Brochure
 
Programmation
ProgrammationProgrammation
Programmation
 
Tips and tricks for creating CM14 Reports - Oracle Primavera Collaborate 14
Tips and tricks for creating CM14 Reports - Oracle Primavera Collaborate 14Tips and tricks for creating CM14 Reports - Oracle Primavera Collaborate 14
Tips and tricks for creating CM14 Reports - Oracle Primavera Collaborate 14
 
Doklad
DokladDoklad
Doklad
 
Schedule analysis what could possibly go wrong - Oracle Primavera Collaborat...
Schedule analysis what could possibly go wrong  - Oracle Primavera Collaborat...Schedule analysis what could possibly go wrong  - Oracle Primavera Collaborat...
Schedule analysis what could possibly go wrong - Oracle Primavera Collaborat...
 
EFFECTIVE USE OF LOCAL RESOURCES IN CLASS ROOM TEACHING
EFFECTIVE USE OF LOCAL RESOURCES IN CLASS ROOM TEACHING EFFECTIVE USE OF LOCAL RESOURCES IN CLASS ROOM TEACHING
EFFECTIVE USE OF LOCAL RESOURCES IN CLASS ROOM TEACHING
 
Core java day5
Core java day5Core java day5
Core java day5
 
Fc barcelona
Fc barcelonaFc barcelona
Fc barcelona
 

Similar to Exceptions

Similar to Exceptions (20)

Java Day-5
Java Day-5Java Day-5
Java Day-5
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - ii
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 

More from Soham Sengupta

More from Soham Sengupta (19)

Spring method-level-secuirty
Spring method-level-secuirtySpring method-level-secuirty
Spring method-level-secuirty
 
Spring security mvc-1
Spring security mvc-1Spring security mvc-1
Spring security mvc-1
 
JavaScript event handling assignment
JavaScript  event handling assignment JavaScript  event handling assignment
JavaScript event handling assignment
 
Networking assignment 2
Networking assignment 2Networking assignment 2
Networking assignment 2
 
Networking assignment 1
Networking assignment 1Networking assignment 1
Networking assignment 1
 
Sohams cryptography basics
Sohams cryptography basicsSohams cryptography basics
Sohams cryptography basics
 
Network programming1
Network programming1Network programming1
Network programming1
 
JSR-82 Bluetooth tutorial
JSR-82 Bluetooth tutorialJSR-82 Bluetooth tutorial
JSR-82 Bluetooth tutorial
 
Core java day2
Core java day2Core java day2
Core java day2
 
Core java day4
Core java day4Core java day4
Core java day4
 
Java.lang.object
Java.lang.objectJava.lang.object
Java.lang.object
 
Soham web security
Soham web securitySoham web security
Soham web security
 
Html tables and_javascript
Html tables and_javascriptHtml tables and_javascript
Html tables and_javascript
 
Html javascript
Html javascriptHtml javascript
Html javascript
 
Java script
Java scriptJava script
Java script
 
Sohamsg ajax
Sohamsg ajaxSohamsg ajax
Sohamsg ajax
 
Dhtml
DhtmlDhtml
Dhtml
 
Cookies and session
Cookies and sessionCookies and session
Cookies and session
 
Jdbc day-1
Jdbc day-1Jdbc day-1
Jdbc day-1
 

Recently uploaded

Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 

Recently uploaded (20)

Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 

Exceptions

  • 2. Definition • An exception is an abnormal condition that arises while running a program. Exception handling in Java is same as in C++. • This is how Java handles Exceptions. When an exception occurs in a method, an object of Exception type is thrown. The method can either handle the exception or pass it on to the calling method. • Example of exceptions are : Attempt to divide by zero causes an exception to be thrown at run time, Attempt to call a method on an object that has is null. sohamsengupta@yahoo.com2
  • 3. Keywords • Exceptions are typically generated by Java run time system. They could also be thrown manually by writing a code that throws exception. • Exception handling block: try{ … } catch(ExceptionType1 e){ …} catch(ExceptionType2 e){ …} . . . finally { ... } sohamsengupta@yahoo.com3
  • 4. Exception Types Throwable Exception Error Exception: This class is used for exceptional conditions that a user program should catch. Also when we generate Exceptions manually in the code we extend this class. Example divide by zero etc. Error: These are the exception that does not occur under the normal circumstances and hence are not excepted to be caught by the code. JRE handles these kind of exceptions. sohamsengupta@yahoo.com4
  • 5. Exceptions • We will be looking only at Exception class. Some Subclasses of Exception: 1. IOException 2. ClassNotFoundException 3. RuntimeException a. ArithmeticException b. NullPointerException c. ArrayIndexOutOfBoundsException d. ClassCastException sohamsengupta@yahoo.com5
  • 6. Without Exceptions • Let us write a code that does not handle exception. class DivideByZero { public static void main(String str[]) { int z= 45/0; } } No compilation errors. Run time error generated by the system: Exception in thread "main" java.lang.ArithmeticException: / by zero at DivideByZero.main(DivideByZero.java:5) Default Exceptional handler handles the exception. This can sometimes run into pages. sohamsengupta@yahoo.com6
  • 7. Why to handle exceptions • To give a user friendly message to the user. • To save all the work or to close open files or sockets etc. • To allow program to terminate gracefully. class DivideByZero{ public static void main”(String str[]) { int z=90; try{ z= 45/0; } catch(ArithemeticException e) { System.out.println(“Division by zero”); z=0; // resetting to a valid value } System.out.println(“After catching exception”); } output: Division by zero After catching exception sohamsengupta@yahoo.com7
  • 8. Multiple catches • There could be more than one exception that is raised in a piece of code. In this case we use multiple catch. We however have to be careful to catch Exceptions of subclass types first and then super class types. sohamsengupta@yahoo.com8
  • 9. sohamsengupta@yahoo.com9 class Catches { public static void main(String[] args) { try{ int i=10/Integer.parseInt(args[0]); } catch(ArithmeticException e){ System.out.println("div by zero"); } catch(ArrayIndexOutOfBoundsException e1){ System.out.println(“out of bound"); } } } c:> java Catches 0 > output : div by zero c:> java Catches > output: out of bound
  • 10. Multiple catch must ensure that super Exception comes later sohamsengupta@yahoo.com10 class DivideByZero { public static void main(String[] args) { try{ int i=10/0; } catch(Exception e){ System.out.println(“general error"); } catch(ArithmeticException e1){ System.out.println(“div by zero ");} } } • exception java.lang.ArithmeticException has already been caught catch(ArithmeticException e1){ ^ 1 error
  • 11. Multiple try • A try statement can be nested inside another try statement. If an exception is raised in the inner try block and it does not have a catch handler for that exception then this exception is caught by the catch statement of the outer try block ( if there is a matching handler) sohamsengupta@yahoo.com11
  • 12. throws • A method that does not want to handle exception can delegate this to the calling method. class DivideByZero { public static void method() throws ArithmeticException { int i=10/0; } public static void main(String[] args) { try{ sohamsengupta@yahoo.com12 method(); }catch(Exception e){ System.out.println(“some exception ");} } }
  • 13. throw & rethrow • Generate an Exception condition manually in the code class DivideByZero { public static void method() { try{ throw new NullPointerException(“exception”); }catch(NullPointerException e1){ System.out.println(“null pointer exception in method"); throw e1; } } } sohamsengupta@yahoo.com13
  • 14. public static void main(String[] args) { try{ method(); } catch(NullPointerException e1){ System.out.println(“null pointer exception in main");} } } sohamsengupta@yahoo.com14
  • 15. finally • When exceptions occur the program’s normal flow is disrupted. It is no longer in sequence. The methods that work with the system resources like files and sockets remain open if the program ends prematurely during exceptions. • finally is a block of statements that will definitely get executed whether or not an exception occurs. So the methods that deal with resources could release them in the finally block. sohamsengupta@yahoo.com15
  • 16. sohamsengupta@yahoo.com16 class Catches { public static void main(String[] args) { try{ int i=10/Integer.parseInt(args[0]); System.out.println(“Normal execution”); } catch(ArithmeticException e){ System.out.println("div by zero"); } catch(ArrayIndexOutOfBoundsException e1){ System.out.println(“out of bound"); } finally { System.out.println(“Thank you”); } } }
  • 17. Output c:> java Catches 0 > output : div by zero Thank you c:> java Catches > output: out of bound Thank you java Catches 1 > output: Normal execution Thank you sohamsengupta@yahoo.com17
  • 18. Code snippet class B { static int getVal(){ int x=12; int[] y=new int[5]; try{ return y[x]; }catch(ArithmeticException ae){ return -120; }finally{ return 940; } } public static void main(String[] ar) { System.out.println(getVal()); sohamsengupta@yahoo.com18 }} Output: 940 class B { static int getVal(){ int x=12; int[] y=new int[5]; try{ return y[x]; }catch(ArithmeticException ae){ return -120; } } public static void main(String[] ar) { System.out.println(getVal()); }} Exception in thread "main" java.lang.ArrayIndexOutOfBoundsE xception: 12 at B.getVal(B.java:6) at B.main(B.java:12)
  • 19. Another Code Snippet class B { static int getVal(){ int x=12; int[] y=new int[5]; try{ return y[x]; }catch(Exception ae){ return -120; } } public static void main(String[] ar) { System.out.println(getVal()); sohamsengupta@yahoo.com19 }} Output: -120 Exception catches subException ArrayIndexOutOfBoundsException and the catch Block Returns the -120 Guess what if we omit the catch block and introduce the final block class B { static int getVal(){ int x=12; int[] y=new int[5]; try{ return y[x]; }finally{ return -570; } } public static void main(String[] ar) { System.out.println(getVal()); }}• Output -570 • In the next slide we’ll omit the return statement from finally bloack. • See the magical perversion
  • 20. Examples… contd. class B { static int getVal(){ int x=12; int[] y=new int[5]; try{ System.out.println("Inside try"); return y[x]; }finally{ System.out.println("From finally sohamsengupta@yahoo.com20 without catch"); } } public static void main(String[] ar) { System.out.println(getVal()); }} Inside try From finally without catch Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12 at B.getVal(B.java:7) at B.main(B.java:13) Checked Exception public static void main(String[] ar) { throw new Exception("My Exception"); } // Will be error Exception is checked and superclass of all. Replace with java.io.IOException, the same result will u get. But… public static void main(String[] ar) { throw new ArithmeticException("My Exception"); } // is OK it is subclass of Unchecked Exception java.lang.RuntimeException
  • 21. A few facts about Exception handling • A try block must have at least one catch block or one finally block. • A catch block can detect only the declared exception type or any subclass exception of that type • If we use multiple catch block, super class Exception must come after sub class ones • If we use finally, finally is executed in all the cases. Even return in suitable catch can’t stop it. • To make a program terminate “gracefully” , we use multiple catch block in proper order followed by a catch(Throwable t) block at last • In case of overriding, the subclass overrider method can’t declare to throw broader Checked Exceptions. sohamsengupta@yahoo.com21
  • 22. More on Exception handling • To debug a program we must call the Exception.printStackTrace() method. It’s not a static method so u must have use an instance of Exception or its sub class to call this method. This works in stack (LIFO) telling u how the Exception originated and in what line number of the code. Remember, this prints the stack trace on the console. So, be careful to call this method and make sure that u can see the console. This is generally performed inside the catch block because it’s only there that u get an instance of the raised exception. • From the experts' desk: Always try to incorporate proper exception handling in your application to make your end user feel comfortable and the developer get going in debugging a logical bug! sohamsengupta@yahoo.com22
  • 23. User-defined exceptions • A user defined exception class can be created if one finds that there is no in-built exceptions that matches the exceptions that will be thrown by the code. • This class is created by extending the Exception class. sohamsengupta@yahoo.com23
  • 24. class AgeClass { private int age ; private String description; public AgeClass(int age, String desc){ setAge(age); setDescription(desc); } public void setAge(int age){ if (age==0 || age>150) throw new AgeException(“Age = “+ age + “ is invalid”); else this.age=age; } public void setDescription(String desc){ // some code to describe age } sohamsengupta@yahoo.com24
  • 25. class AgeException extends Exception { String exStr; public AgeException() { exStr= “Age not in the permitted range”; } public AgeException(String s) { exStr=s; } public String toString() { return Exception: ” + exStr; } } sohamsengupta@yahoo.com25
  • 26. Exercises • For the Student class that we created in last exercise, throw an exception if the marks entered is out of range (0-100). sohamsengupta@yahoo.com26
  • 28. Wrapper Classes • A class that is created over a primitive data types or other classes giving it more functionality. • java.lang.Integer • java.lang.Boolean • java.lang.Float • java.lang.Double • java.lang.Short • java.lang.Long • java.lang.Byte sohamsengupta@yahoo.com28
  • 29. Integer • We will look at just one wrapper class. Other classes are just similar. (Use Java Documentation for reference). • Constructor Summary • Integer(int value) Constructs a newly allocated Integer object that represents the specified int value. • Integer(String s) Constructs a newly allocated Integer object that represents the int value indicated by the String parameter. sohamsengupta@yahoo.com29
  • 30. Important methods • static int parseInt(String s) Parses the string argument as a signed decimal integer. • int intValue() Returns the value of this Integer as an int. • static String toString(int i) Returns a String object representing the specified integer. • static Integer valueOf(String s) Returns an Integer object holding the value of the specified String. sohamsengupta@yahoo.com30
  • 31. Example • Get the year from the command line argument and check if it is a leap year. class LeapYear { public static void main(String args[]){ if (args.length>1) || (args[0].length()<>4){ System.out.println(“Impoprer argument”); else { int year=Integer.parseInt(args[0]); if (leapYear(year) System.out.println(“Leap Year”); else System.out.println(“Not a leap year”); } boolean leapYear(int year) {…} } sohamsengupta@yahoo.com31
  • 33. java.util • Java utility classes are packaged in java.util package. • Most of the utility classes are collections (group of objects). • Collection interface is the root in the hierarchy. • Other than this interface we will be looking at following important utility classes/interfaces: sohamsengupta@yahoo.com33
  • 34. ArrayList * In java, arrays are of a fixed length. * ArrayList class is used to support dynamic arrays. * It is a type of collection class. * Constructors: • ArrayList(): builds an empty array list. • ArrayList(int capacity): builds an array list of size capacity. sohamsengupta@yahoo.com34
  • 35. methods • boolean add(Object obj) • Object remove(int index) • void trimToSize() • Iterator iterator() • Object get(int index) sohamsengupta@yahoo.com35
  • 36. Example ArrayList a1= new ArrayList(); a1.add("A"); a1.add("B"); a1.add("C"); System.out.println(a1); a1.remove(2); sohamsengupta@yahoo.com36
  • 37. Iterator interface • This interface helps us to iterate through any collection classes. a. With iterator we can to remove elements from the underlying collection. b. Method names have been improved. boolean hasNext() Returns true if the iteration has more elements. sohamsengupta@yahoo.com37 Object next() Returns the next element in the iteration. void remove() Removes from the underlying collection the last element returned by the iterator (optional operation).
  • 38. • An iterator() method is provided in almost all the collection classes that returns Iterator object. ArrayList a1= new ArrayList(); a1.add("A"); a1.add("B"); a1.add("C"); Iterator iterator=a1.iterator(); while(iterator.hasNext()) { String str=(String)iterator.next(); System.out.println(str); } sohamsengupta@yahoo.com38
  • 39. java.util.Date • Date is an older class added in Java 1.0 SDK. • Most of its methods are deprecated. Constructors: Date(): Current date and time. sohamsengupta@yahoo.com39
  • 40. Methods • boolean after(Date when) Tests if this date is after the specified date. boolean • before(Date when) Tests if this date is before the specified date. • int compareTo(Date anotherDate) Compares two Dates for ordering. • int compareTo(Object o) Compares this Date to another Object. sohamsengupta@yahoo.com40
  • 41. java.util.Calendar • * This class provides a set of methods that helps us to work with dates. • * It is an abstract class. • * But there is a static method, getInstance(), in the Calendar class (that is implemented) which returns a Calendar object. • * This method assumes the default locale and time zone. • * Calendar cal=Calendar.getInstance(); • * This initializes object with current date and time. sohamsengupta@yahoo.com41
  • 42. methods • 1. final int get( int calendarField) : example: int month=cal.get(Calendar.MONTH) • 2. final void set(int year, int month, int day, [ int hours, int minutes, int secs ]) • 3. final void clear() • 4. final void set(int which, int value) • 5. some integer constants which can be used with get method: MONTH, YEAR, DATE, HOUR, MINUTE, SECOND sohamsengupta@yahoo.com42
  • 43. import java.util.*; Example class CalendarExample { static final String month[]={“Jan”,”Feb”,”Mar”,”Apr”,”May”,”Jun”,”Jly”,”Aug”,”S ep”,”Oct”,”Nov”,”Dec”}; public static void main(String str[]) { printPayBillDateHeader(); } public static printPayBillHeader() { Calendar c=Calendar.getInstance(); String m=month[c.get(Calendar.MONTH)]; System.out.print(“Paybill for the months of “ + m); System.out.println(“ “+ c.get(Calendar.DATE)); sohamsengupta@yahoo.com43 } }
  • 44. Exercises I. An office maintains a record of documents it receives. Following details about the douments are maintained: a. Document date b. Name of the person who sent the document c. Name of the person to whom this document was addessed. d. Department of the person who sent tis sohamsengupta@yahoo.com44 document e. summary
  • 45. • Create a console based java application to 1. Add document details 2. Remove document details 3. Modify document details 4. Display chronologically all the documents received so far. sohamsengupta@yahoo.com45
  • 46. II. An electric contains many electrical appliances. Appliances are classified into appliance types and they are kept in a particular location. When an appliance is added it is given a new unique id number starting from 1 upto 1000. An appliance is tested after every n no. of days depending on appliance types. sohamsengupta@yahoo.com46
  • 47. • Now there are two types of users in the application: • 1. Managers - login :mgr, password:mgrpw • 2. Testers - login:tester1, password:tester1pw • login:tester2, password:tester2pw • A test data consist of • appliance id, date of test, result (pass/fail), comments. sohamsengupta@yahoo.com47
  • 48. • Managers can add/delete/modify appliance types and locations. • Testers and managers can add/delete/modify appliances. • Testers can add test but cannot delete test. • A tester who has added a test can only update the test. sohamsengupta@yahoo.com48
  • 49. • Write a console java program to • 1. Add/Delete/Modify appliance type. • 2. Add/Delete/Modify location. • 3. Add/Delete/Modify appliances. • 4. Displays a report with all tests taken so far. • 5. Displays outstanding tests. sohamsengupta@yahoo.com49