0% found this document useful (0 votes)
17 views

3 Mech - Java Programming Unit 3

Uploaded by

mokkapunai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

3 Mech - Java Programming Unit 3

Uploaded by

mokkapunai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 103

Please read this disclaimer before

proceeding:
This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document
contains proprietary information and is intended only to the respective group /
learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender
immediately by e-mail if you have received this document by mistake and delete
this document from your system. If you are not the intended recipient you are
notified that disclosing, copying, distributing or taking any action in reliance on
the contents of this information is strictly prohibited.
JAVA PROGRAMMING

Department : Mechanical Engineering

Batch / Year :2021-2025 / II Year

Created by :
Dr J.Sathiamoorthy Associate Professor / CSE

Date : 08.08.2022

4
1. CONTENTS
Page
S. No. Contents
No

1 Contents 5

2 Course Objectives 6

3 Pre Requisites 7

4 Syllabus 8

5 Course outcomes 9

6 CO- PO/PSO Mapping 10

7 Lecture Plan 11

8 Activity based learning 13

9 Lecture Notes 19

10 Assignments 78

11 Part A Questions & Answers 80

12 Part B Questions 89

13 Supportive online Certification courses 91

14 Real time Applications 92

15 Contents beyond the Syllabus 93

16 Assessment Schedule 95

17 Prescribed Text Books & Reference Books 96

18 Mini Project Suggestions 97

5
2. COURSE OBJECTIVES

• To understand Object Oriented Programming concepts and


fundamentals of Java
• To know the principles of packages, inheritance and
interfaces
• To define exceptions and multithreading
• To develop a java application with I/O streams and generics
classes
• To use the functionalities of Strings and Collections

6
3. PRE REQUISITES

Pre-requisite Chart

20CS302 – OBJECT ORIENTED


PROGRAMMING

20GE101 – PROBLEM SOLVING AND C


PROGRAMMING

7
4. SYLLABUS

20CS304 JAVA PROGRAMMING LTPC3003


OBJECTIVES:
• To understand Object Oriented Programming concepts and fundamentals of Java
• To know the principles of packages, inheritance and interfaces
• To define exceptions and multithreading
• To develop a java application with I/O streams and generics classes
• To use the functionalities of Strings and Collections
UNIT I : INTRODUCTION TO OOP AND JAVA FUNDAMENTALS 9
An Overview of Java - Data Types, Variables, and Arrays – Operators – Control
Statements – Class Fundamentals – Declaring objects – Methods – Constructors – this
keyword - Overloading methods - Overloading constructors - Access Control – Static –
Final.
UNIT II - INHERITANCE, PACKAGE AND INTERFACES 9
Inheritance: Inheritance basics, Using super, Method Overriding, Using Abstract Classes,
Using final with Inheritance – Package and Interfaces: Packages, Packages and member
access, Importing Packages, Interfaces, Static Methods in an Interface
UNIT III - MULTITHREADING, I/O AND GENERIC PROGRAMMING 9
Exception Handling: Exception-Handling Fundamentals, Exception Types, Uncaught
Exceptions, Using try and catch, Multiple catch Clauses, Nested try Statements, throw,
throws, finally, Java’s Built-in Exceptions. Multithreaded Programming: Thread Creation
UNIT IV I/O AND GENERIC PROGRAMMING 9
I/O: I/O Basics, Reading Console Input, Writing Console Output, Reading and Writing
Files – Generics: Introduction, Generic class, Bounded Types, Generic Methods, Generic
Interfaces, Generic Restrictions.
UNIT V STRING HANDLING AND COLLECTIONS 9
String Handling – Collections: The Collection Interfaces, The Collection Classes – List,
Array List, Set, Iterator – Map.
TOTAL: 45 PERIODS

OUTCOMES:
At the end of this course, the students will be able to:
CO1: Understand the Object Oriented Programming concepts and fundamentals of Java
CO2: Develop Java programs with the packages, inheritance and interfaces
CO3: Build applications using Exceptions and Threads.
CO4: Build Java applications with I/O streams and generics classes
CO5: Use Strings and Collections in applications

8
5. Course Outcomes

COURSE OUTCOMES HKL


Understand the Object Oriented Programming concepts and
CO1 K2
fundamentals of Java

Develop Java programs with the packages, inheritance and


CO2 K3
interfaces

CO3 Build applications using Exceptions and Threads. K3

CO4 Build Java applications with I/O streams and generics classes K3

CO5 Use Strings and Collections in applications K3


6. CO-PO/PSO Mapping

POs/PSOs
PS O
COs PO PO PO PO PO PO PO PO PO 9 PO1 PO1 PO1 PSO 1PSO 2 3
1 2 3 4 5 6 7 8 0 1 2

CO1 3 3 3 - - - - - - - - - 3 2 2
CO2 3 2 2 - - - - - - - - - 3 2 2
CO3 3 2 2 - - - - - - - - - 3 2 2
CO4 3 2 2 - - - - - - - - - 3 2 2
CO5 3 2 2 - - - - - - - - - 3 2 2
7. Lecture Plan
UNIT – III

S. Scheduled Actual Date Mode of Taxonomy


Topic CO
No. Date of Completion Delivery Level
Exception-Handling Video/
CO3
1 Fundamentals PPT K1
PPT/
Exception Types CO3 K1
2 Demo
PPT/
Uncaught Exceptions CO3 K1
3 Demo
Using try and catch, Multiple PPT/
4 CO3 K1
catch Clauses Demo
PPT/
Nested try Statements CO3
5 Demo K2

PPT/
throw, throws, finally CO3
6 Demo K2

Java’s Built-in Exceptions CO3 PPT/


7 Demo K3

PPT/
Multithreaded Programming CO3
8 Demo K2

Thread States, Thread PPT/


9 Creation CO3 Demo K3
LECTURE PLAN – UNIT III

• ASSESSMENT COMPONENTS MODE OF DELEIVERY


• AC 1. Unit Test MD 1. Oral presentation
• AC 2. Assignment MD 2. Tutorial
• AC 3. Course Seminar MD 3. Seminar
• AC 4. Course Quiz MD 4 Hands On
• AC 5. Case Study MD 5. Videos
• AC 6. Record Work MD 6. Field Visit
• AC 7. Lab / Mini Project
• AC 8. Lab Model Exam
• AC 9. Project Review
8. ACTIVITY BASED LEARNING – UNIT III

COMPLETE THE PUZZLES GIVEN BELOW

Across
3. Which of these class can be used to implement the input stream that uses a
character array as the source?
4. keyword is used to explicitly throw an exception
5. block is used to enclose the code that might throw an exception. It must be used
within the method.
7. divide any number by zero, there occurs
8. The wrong formatting of any value may occur
11. When does Exceptions in Java arises in code sequence?
13. Which of these classes can return more than one character to be returned to
input stream?

Down
1. inserting any value in the wrong index of array, it would result in
2. Which of these stream contains the classes which can work on character stream?
6. Which of these class is used to read characters in a file?
9. block is always executed whether an exception is handled or not
10. Which of these method of FileReader class is used to read characters from a file?
12. keyword is used to apply restrictions on class, method, and variable.
SCRAMBLED WORDS

ENCETPIOX _________________________

YTR __________________________

CTAHC __________________________

WORTH __________________________

NITUP __________________________

TSCAK __________________________

RARYNIEDX __________________________

UNMREBOFRAMT __________________________

LIEF __________________________

TSERAM __________________________
WORD SEARCH

Q X T Y U I O P A Q G J K E L O Z
J K W R R R E A D S A N T H A K U
L Q O E Q P Q E E T T Q W R I T E
E G A E W R W O R C A T C H R A V
W K R D E P E U Q M J A K N H S V
X L R S A E R V R I J U L U J Y V
Z A Y F E X C E P T I O N M C A I
V W I U S A Y I C A U P K B F Y I
B I N P U M T K H Y L S U E W N N
M L D I L P R B I Y H T H R O W J
H P E T H R O W S A H R S F K A U
K O X P Y O I I G P W E P O O T T
L S L O L W O T E P K A F R L P T
Q S K Q S T A C K A H M Y M H H H
W T E W S E P H E N B S S A E R E
A E H E Y X O U T P U T L T Q W R
R W F I L E N V X M P O Y E T R Y

EXCEPTION INPUT OUTPUT TRY


THROW WRITE CATCH THROWS
FILE ARRAYINDEX STACK
READ NUMBERFORMAT STREAMS
Multithreading In Java – Complete The Puzzle

Across Down
5. The . . . . . . . . . . . . keyword tells 1. In java, thread can be created by
Java to make the block of code in the implementing...............interface
method thread safe. This means that 2. What is the name of the method
only one thread will be allowed inside used to start a thread execution?
this method at once, and other 3. In java, thread is created by
threads will have to wait until the extending--------------class
currently running thread is finished 4. Which method is called internally
with it before they can begin running by Thread start() method?
it.
Test Yourself:

1.Thread priority in Java is?


a) Integer
b) Float
c) double
d) long

Ans :a

2.What will happen if two thread of the same priority are called to be
processed simultaneously?
a) Anyone will be executed first lexographically
b) Both of them will be executed simultaneously
c) None of them will be executed
d) It is dependent on the operating system

Ans:d

3.What will be the output of the following Java code?


classmultithreaded_programing
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println(t);
}
}

Ans: Thread[main,5,main]
4. Which of the following cannot be Type parameterized?
a) Overloaded Methods
b) Generic methods
c) Class methods
d) Overriding methods

Ans:a

5. Which of these instance cannot be created?


a) Integer instance
b) Generic class instance
c) Generic type instance
d) Collection instances

Ans:c
Exceptions
Exceptions

Java exception is an object that describes an exceptional (that is, error) condition
that has occurred in a piece of code. When an exceptional condition arises, an
object representing that exception is created and thrown in the method that
caused the error. That method may choose to handle the exception itself, or pass
it on.
Java exception handling is managed via five keywords: try, catch, throw, throws,
and finally. Here is how they work.

• Program statement that we want to monitor for exceptions are contained


within a try block.

• If an exception occurs within the try block, it is thrown.

• Our code can catch this exception (using catch) and handle it in some rational
manner.

• System-generated exceptions are automatically thrown by the Java run-time


system.

• To manually throw an exception, use the keyword throw.

• Any exception that is thrown out of a method must be specified as such by a


throws clause.
• Any code that absolutely must be executed after a try block completes is put
in a finally block.

General Form:
try {
//block of code to monitor for errors
}catch (ExceptionType1 exob) {
// exception handler for ExceptionType1
}
//..
Finally {
//block of code to be executed after try block ends
}
Exception is an event that interrupts the normal flow of execution of the java
program.
Quiz
1. What method of an Exception object prints a list of methods that were called
before the exception was thrown?
a. printErrors() b. getMessage()
c. printStackTrace() d. traceStack()
2. What method of an Exception object returns a message string?
a. printErrors() b. getMessage()
c. printStackTrace() d. traceStack()
3. What happens during execution if an negative value is used for an array index?
a. An IndexOutOfBoundsException is thrown.
b. A NumberFormatException is thrown.
c. The first slot of the array is used.
d. This is an Error, so the program immediately terminates no matter what.

4. A method must do either of two things with a checked exception. What are those
two things?
a. (1) Ignore the exception, or (2) check the exception.
b. (1) Handle the exception in a catch{} block, or (2) return the exception to
the sender.
c. (1) Handle the exception in a catch{} block, or (2) throw the exception to
the method that called this method.
d. (1) Handle the exception in a catch{} block, or (2) handle the exception in
a try{} block
5. Say that methodA calls methodB, and methodB calls methodC. MethodC might
throw a NumberFormatException. Can the program be written so that methodA
handles the exception?.
a. No, the exception must be handled by methodC or its caller, methodB.
b. No, methodC must handle the exception.
c. Yes, if the header for methodC says ...throws NumberFormatException
d. Yes, if the headers for methodC and methodB say ...throws
NumberFormatException
Exception
Hierarchy
Exception Hierarchy

All exception classes are the subtypes of the java.lang.Exception class. The exception
class is the sub class of the Throwable class. Other than the exception class there is
another subclass called Error which is derived from the throwable class.

Uncaught Exception:

Let us see what happens if we don’t handle exceptions. Following small program
includes an expression that intentionally causes a divide-by-zero error:
class Exc0{
public static void main(String args[]) {
int d=0;
int a=42/d; //divided by zero
}
}
When the java run-time system detects the attempts to divide by zero, it constructs a
new exception object and then throws this exception. This causes the execution of the
program to stop. In this example, we haven’t supplied any exception handlers of our
own, so the exception is caught by the default handler provided by the java run time
system. The default handler displays a string describing the exception and terminates
the program. Here is the exception generated when this example is executed:

Java.lang.ArithematicException: // by zero
at Exc0.main (Exc0.java:4)
Throwing and
Catching
Exception
Throwing and Catching
Exceptions:
Although the default exception handler provided by the Java run-time system is useful
for debugging, we will usually want to handle an exception our self and provides two
benefits. First, it allows us to fix the error. Second, it prevents the program from
automatically terminating.
To guard against and handle a run-time error, simply enclose the code that we want to
monitor inside a try block. Immediately following the try block, include a catch clause
that specifies the exception type that you wish to catch.

class Exc2
{
public static void main (String args[])
{
int d, a;
try
{ //monitor a block of code.
d=0;
a=42/d;
System.out.println(“This will not be printed”);
}
catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println(“Division by zero”);
}
System.out.println(“After catch statement”)
}
}
The program generate following output:
Division by zero
After catch statement
Notice that the call to println() inside the try block is never executed. Once an exception
is thrown, program control transfers out of the try block into the catch block. Put
differently, catch is not “called,” so execution never “returns” to the try block from a
catch. Thus, the line “This will not be printed.” Is not displayed. Once the catch
statement has executed, program control continues with the next line in the program
following the entire try/catch mechanism.
A try and its catch statement form a unit. The scope of the catch clause is restricted to
those statements specified by the immediately preceding try statement. A catch
statement cannot catch an exception thrown by another try statement.

Multiple catch Clauses


In some cases, more than one exception could be raised by a single piece of code. To
handle this type of situation, we can specify two or more catch clauses, each catching a
different type of exception. When an exception is thrown, each catch statement is
inspected in order, and the first one whose type matches that of the exception is
executed. After one catch statement executes, the others are bypassed, and execution
continues after the try/catch block.
The following example traps two different exception types:

//Demonstrate multiple catch statements.


class MultiCatch {
public static void main (String args[]) {
try {
int a = args.length;
System.out.println(“a=“ + a);
int b = 42 / a;
int c[] = {1};
c[42] = 99;
} catch (ArithmeticException e) {
System.out.println(“Divide by zero” + e);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(“Array Index OOB” + e) {
}
System.out.println(“After try/catch block”);
}
}
This program will cause a division-by-zero exception if it is started with no command
line arguments, since a will equal zero. It will survive the division if you provide if you
provide a command-line argument, setting a to something larger than zero. But it will
cause an ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet
the program attempts to assign a value to c[42].
Here is the output generated by running it both ways:
C:\>java MultiCatch
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultiCatch TestArg
a=1
Array Index OOB: java.lang.ArrayIndexOutofBoundsException: 42
After try/catch blocks.

Nested try Statements:


The try statement can be nested. That is, a try statement can be inside the block of
another try. Each time a try statement is entered, the context of that exception is
pushed on the stack. If an inner try statement does not have a catch handler for a
particular exception, the stack is unwound and the next try statement’s catch handlers
are inspected for a match. This continues until one of the catch statements succeeds,
or until all of the nested try statements are exhausted. If no catch statement matches,
then the Java run-time system will handle the exception.
Here is an example that uses nested try statements:

//An example of nested try statements.


class NestTry {
public static void main(String args []) {
try {
int a = args.length;
/* If command -line args are present, The following statement will generate Divide-by-
zero exception. */
int b = 42/a;
System.out.printIn(“a = ” + a ) ;
try { // nested try block
/* If one command_ line arg is used, Then a divide – by-zero exception will be
generated by the following code. * /
if(a==1) a = a/(a-a) ; // division by zero
/* If two command- line args are used, then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 } ;
c [ 42 ] = 99 ; // generate an out – of-bounds exception
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.printIn(“Array index out-of-bounds: “ + e) ;
}
} catch (ArithmeticException e) {
System.out.printIn(“Divide by 0 : “ + e) ;
}
}
}
As we can see , this program nests one try block within another .The peogarm works
as follows.when you execute the program with no command_line arguments , a
divide-by-zero exception is generated by the outer try block .Execution of the
program with one command -line argument generates a divide by zero exception from
within the nested try block.Since the inner block doesnot catch this exception. It is
passed on to the outer try block,where it is handled. If you execute the program with
two command-line-arguments,an arrayboundary exception is generated from within
the inner try block. Here are sample runs that illustrate each case:

Output:
C:\>java NestTry
Divide by 0 : java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a=1
Divide by 0 : java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a=2
Array index out- of -bounds:
java.lang.ArrayIndexout of Bounds Exception:42
Throw
So far, we have only been catching exceptions that are thrown by the Java run-time
system. However, it is possible for our program to throw an exception explicitly,
using the throw statement. The general form throw is shown here:

throw ThrowableInstance:
Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable. Primitive types, such as int or char, as well as non-Throeable classes,
such as String and Object, cannot be used as exceptions.
The flow of execution stops immediately after the throw statement; any subsequent
statements are not executed. The nearest enclosing try block is inspected to see if it
has a catch statement that matches the type of exception. If it does find a match,
control is transferred to that statement. If not, then the next enclosing try statement
is inspected, and so on. If no matching catch is found, then the default exception
handler halts the program and prints the stack trace.

Here is a sample program that creates and throws an exception. The handler that
catches the exception rethrows it to the outer handler.

//Demonstrate throw.
class ThrowDemo {
static void demoproc () {
try {
Throw new NullPointerException (“demo’);
} catch (NullPointerException e)
{
System.out.println(“Caught inside demoproc”);
throw e; //rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println(“Recaught:” + e);

}
}
}
This program gets two chances to deal with the same error. First, main() sets up an
exception context and then calls demoproc(). The demoproc() method then sets up
another exceptionhandling context and immediately throws a new instance of
NullPointerException, which is caught on the next line. The exception is then
rethrown.
Here is the resulting output:
Caught inside demoproc.
Recaught : java.lang.NullPointerException: demo

Throws
If a method is capable of causing an exception that it does not handle, it must specify
this behavior so that callers of the method can guard themselves against that
exception. You do this by including a throws clause in the method’s declaration. A
throws clause lists the types of exceptions that a method might throw. This is
necessary for all exceptions that a method can throw must be declared in the throws
clause. If they are not, a compile-time error will result.

General Form:
Type method-name(parameter-list) throws exception-list
{
//body of method
}
Here exception-list is a comma-separated list of the exceptions that a method can
throw

Example
// This program contains an error and will not compile.
class ThrowsDemo {
static void throwOne() {
System.out.println(“Inside throwOne”);
throw new IllegalAccessException(“demo”);
}
public static void main(String args[]) {
throwOne();
}
}
To make this example compile, we need to make two changes. First, we need to
declare that throwOne() throws IllegalAccessException. Second, main() must define a
try/catch statement that catches this exception.

The corrected example is shown here:


//This is now correct.
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println(“Inside throwOne”);
}
public static void main(String args[]) {
try {
throwOne();
} catch(IllegalAccessException e) {
System.out.println(“Caught:” + e);
}
}
}

Output:
Inside throwOne
Caught java.lang.IllegalAccessException: demo

finally
finally creates a block of code that will be executed after a try/catch block has
completed and before the code following the try/catch block. The finally block will
execute whether or not an exception is thrown. If an exception is thrown, the finally
block will execute even if no catch statement matches the exception. This can be
useful for closing file handles and freeing up any other resources that might have been
allocated at the beginning of a method. The finally clause is optional. However, each
try statement requires at least one catch or a finally clause.
General Form:
try {
// Statements that may cause an exception
}
catch {
// Handling exception
}
finally {
// Statements to be executed
}

Example:

public class MyFinallyBlock


{
public static void main(String args[] a)
{
try
{
int i = 10/0;
}
catch(Ecxception ex)
{
Sysytem.out.println(“Inside 1st catch block”);
}
Finally
{
System.out.println(“Inside 1st finally block”);
}
try
{
int i = 10/0;
}
catch(Exception ex)
{
System.out.println(“Inside 2nd catch block”);
}
Finally
{
System.out.println(“Inside 2nd finally block”);
}
}
}
Output:
Inside 1st catch block
Inside 1st finally block
Inside 2nd finally block
• The finally block always execute immediately after try-catch block exits.
• The finally block is executed incase even if an unexpected exception occurs.
• The main usage of finally block is to do clean up job. Keeping cleanup code in a
finally block is always a good practice, even when no exceptions are occurred.
• The runtime system always executes the code within the finally block regardless of
what happens in the try block. So it is the ideal place to keep clean up code.
Built-In
Exceptions
Built-In-Exceptions
Inside the standard package java.lang, java defines several exception classes. The
most general of these exceptions are subclasses of the standard type
RuntimeException. These exceptions need not be included in any method’s throws
list. In java, these are called unchecked exceptions because the compiler does not
check to see if a method handles or throws these exceptions.

Unchecked Run-Time Exception

S.No. Exception & Description


1 ArithmeticException
Arithmetic error, such as divide-by-zero.
2 ArrayIndexOutOfBoundsException
Array index is out-of-bounds.
3 ArrayStoreException
Assignment to an array element of an incompatible type.
4 ClassCastException
Invalid cast.
5 IllegalArgumentException
Illegal argument used to invoke a method.
6 IllegalMonitorStateException
Illegal monitor operation, such as waiting on an unlocked thread.
7 IllegalStateException
Environment or application is in incorrect state.
8 IllegalThreadStateException
Requested operation not compatible with the current thread state.
9 IndexOutOfBoundsException
Some type of index is out-of-bounds.
10 NegativeArraySizeException
Array created with a negative size.
11 NullPointerException
Invalid use of a null reference.
12 NumberFormatException
Invalid conversion of a string to a numeric format.
S.No Exception & Description

13 SecurityException
Attempt to violate security.
14 StringIndexOutOfBounds
Attempt to index outside the bounds of a string.
15 UnsupportedOperationException
An unsupported operation was encountered.

Checked Run-Time Exception

S.No. Exception & Description

1 ClassNotFoundException
Class not found.

2 CloneNotSupportedException
Attempt to clone an object that does not implement the Cloneable
interface.

3 IllegalAccessException
Access to a class is denied.

4 InstantiationException
Attempt to create an object of an abstract class or interface.

5 InterruptedException
One thread has been interrupted by another thread.

6 NoSuchFieldException
A requested field does not exist.

7 NoSuchMethodException
A requested method does not exist.
Creating Own
Exceptions
Creating Own Exceptions
Although java’s built-in exceptions handle most common errors, we will
probably want to create your own exception types to handle specific situations. This
is quite easy to do: just define a subclass of Exception (which is, of course, a
subclass of Throwable) that allows us to use them as exceptions. The Exception
class does not define any methods of its own instead, it inherits those methods
provided by Throwable.

Example
// A Class that represents use-defined exception
class MyException extends Exception{
public MyException (String s){
// Call constructor of parent Exception
super(s);}
}
// A Class that uses above MyException
public class Main{
// Driver Program
public static void main(String args[]) {
try {
// Thorw an object of user defined exception
throw newMyException(“My Exception”);
}catch(MyException ex){
System.out.println(“cought”);
// print the message from MyException object
System.out.println(ex.getMessage());
}
}
}
Output:
Caught
My Exception
In the above code, constructor of MyException requires a string as its argument.
The string is passed to parent class Exception’s constructors using super(). The
constructor of Exception class can also be called without a parameter and call to
super is not mandatory.
Quiz
1. Output of the following Java program?
class Main {
public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
}
a. Compiler Error
b. Compiles and Run fine
c. Compiles fine but throws ArithmaticException
d. Compiles fine but throws NullPointerException
2. Output of the following Java program?
class Test{
public static void main(String[] args){
try{
int a[]= {1, 2, 3, 4};
for (int i = 1; i <= 4; i++)
{
System.out.println ("a[" + i + "]=" + a[i] + "n");}
}catch (Exception e){
System.out.println ("error = " + e);
}catch (ArrayIndexOutOfBoundsException e){
System.out.println ("ArrayIndexOutOfBoundsException");}
}
}
a. Compiler Error b. Runtime Error
c. Error code is printed d. Array is printed
3. Predict Output of the following Java program?

class Test{
String str = "a";

void A(){
try
{
str +="b";
B();
}
catch (Exception e)
{
str += "c";
}
}

void B() throws Exception{


try
{
str += "d";
C();
}catch(Exception e)
{
throw new Exception();
}finally
{
str += "e";
}

str += "f";
}
void C() throws Exception{
throw new Exception();
}
void display(){
System.out.println(str);
}
public static void main(String[] args)
{
Test object = new Test();
object.A();
object.display();
}
}

a. abdef b. abdec c. abdefc e. acbef


Stack Trace
Elements
Stack Trace Elements
The Stack Trace Element class describes a single frame, which is an individual
element of a stack trace when an exception occurs. Each stack frame represents an
execution point, which includes such things as the name of the class, the name of
the method, the name of the file, and the source-code line number. An array of
StackTraceElement has one constructor:
StackTraceElement (String className, String methname, String filename, int line)
Here, the name of the class is specified by classsName, the name of the method is
specified in methName, the name of the file is specified by filename, and the line
number is passed in line.

Example:
The following example shows the usage of
java.lang.StackTraceElement.getMethodName() method

import java.lang.*;
public class StackTraceElementDemo {
public static void main(String[] args) {
function1();
}
public static void function1() {
new StackTraceElementDemo().function2();
}
public void function2() {
int i;
System.out.println(“method name”);
// print stack trace
for(i=1;i<=3;i++) {
System.out.println(Thread.currentThread().getStackTrace()[i].getMethodName());
}
}
}
Output:
method name:
function2
function 1
Main

Example:
Return the line number of a program
import java.lang.*;
import java.io.*;
import java.util.*;
public class StackTraceElementDemo
{
public static void main(String[] args)
{
System.out.println(“line number”);
for(int i=0;i<2;i++)
System.out.println(Thread.currentThread().getStackTrace()[i].getLineNumber());
}
}

Output:
line number:
1556
10
Predict the output of the following
code snippets
1. What will be the output of the following Java program?
public class SimpleDivisionOperation {
public static void main(String[] args) {
System.out.println(divide(4, 2));
if (args.length > 1) {
// Convert a string to an integer
int arg0 = Integer.parseInt(args[0]);
int arg1 = Integer.parseInt(args[1]);
System.out.println(divide(arg0, arg1));
}
}
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("You can\'t divide by zero!");
} else {
return a / b;
}
}
}
Predict the output of the following
code snippets
2. What will be the output of the following Java program?
Public class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}
MULTITHREADING

Thread:
A thread is referred as a light weight smallest part of a process. Threads are
independent because all the threads follow a separate path of execution within the
program. Each thread has its own program counter, stack and local variables. It
uses a shared memory area, files and per-process state.

Multithreading
The process of executing multiple threads simultaneously is known as
multithreading. Multithreading is a programming concept where a program
(process) is divided into two or more subprograms (process), which can be
implemented at the same time in parallel. A multithreaded program contains two or
more parts that can run concurrently and each part can perform different task at the
same time making optimal use of the available resources. Each part of such a
program is called a thread, and each thread defines a separate path of execution.

Advantages of Java Multithreading


• It doesn't block the user because threads are independent and multiple
operations can be performed at the same time.
• It can perform many operations together, hence saves time.
• Threads are independent, so it doesn't affect other threads if an exception
occurs in one thread.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. Multitasking is
when multiple processes share common processing resources such as a CPU.
Multitasking can be achieved in two ways:
• Process-based Multitasking (Multiprocessing)
• Thread-based Multitasking (Multithreading)
Differences between Multi-threading and Multi-tasking

• Process-based multi-tasking (Multiprocessing)


Executing various jobs or process together where each process is a separate
independent operation is called process-based multi-tasking. Each process has a
separate address in memory and switching from one process to another requires
some time for saving and loading registers and updating lists. A process is heavy
weight and cost of communication between the process is high.

• Thread-based multi-tasking (Multithreading)


Executing several tasks simultaneously where each task is a separate independent
part of the same program is called Thread-based multitasking and each independent
part is called Thread. The main goal of multi-tasking is to make or do a better
performance of the system by reducing response time. Threads share the same
address space. A thread is light weight and cost of communication between the
thread is low.
Life Cycle of a Thread

A thread can be in any of the following states:


• New
• Runnable
• Running
• Blocked
• Waiting
• Timed Waiting
• Terminated
• New: A newly created thread that has not yet started the execution. It
remains in this state until the program starts the thread using start() method.
It is also referred to as a born thread.
• Runnable: If a thread is in this state it means that the thread is ready for
execution and waiting for the availability of the processor. If all threads in
queue are of same priority then they are given time slots for execution in
round robin fashion.
• Running: It means that the processor has given its time to the thread for
execution. A thread keeps running until the following conditions occurs:
(a) Thread give up its control on its own and it can happen in the following
situations:
• A thread gets suspended using suspend() method which can only be
revived using resume() method.
• A thread is made to sleep for a specified period of time using
sleep(time) method, where time is specified in milliseconds.
• A thread is made to wait for some event to occur using wait () method.
In this case a thread can be scheduled to run again using notify()
method.
(b) A thread is pre-empted by a higher priority thread.
• Blocked: If a thread is prevented from entering into runnable state or
waiting for I/O to complete, then a thread is said to be in Blocked state. A
thread in this state cannot continue its execution until it is moved to runnable
state. Any thread in these states does not consume any CPU cycle.
Life Cycle of a Thread

• Waiting: A thread waits indefinitely for another thread to perform a task. A


thread transitions back to the runnable state only when another thread
signals the waiting thread to continue executing.
• Timed Waiting: A thread that is waiting for another thread to perform a
task for a specified interval of time. A thread in this state transitions back to
the runnable state when that time interval expires or when the event it is
waiting for occurs.
• Terminated: A runnable thread enters the dead or terminated state when it
successfully completes its task or otherwise terminated due to any error or
even forcefully killed.
The Thread life cycle is given in below Fig.4.1.

Fig.4.1 Life Cycle of a Thread


The Main() thread

• When we run any java program, the program begins to execute its code
starting from the main method.
• Therefore, the JVM creates a thread to start executing the code present in
main method. This thread is called as main thread.
• Although the main thread is automatically created, it can be controlled by
obtaining a reference to it by calling currentThread() method.
Two important things to know about main thread are,
• It is the thread from which other threads will be produced.

• main thread must be always the last thread to finish execution.


Thread Priorities
Thread priorities

• Thread priorities are integers which decide how one thread should be treated with respect to
the others.
• Thread priority decides when to switch from one running thread to another, and the process
is called context switching.
• A thread can voluntarily release control and the highest priority thread that is ready to run is
given the CPU.
• A thread can be preempted by a higher priority thread no matter what the lower priority
thread is doing. Whenever a higher priority thread wants to run it does.
• To set the priority of the thread, setPriority() method is used which is a method of the class
Thread Class.
• In place of defining the priority in integers, we can use MIN_PRIORITY with value 1,
NORM_PRIORITY(Default Priority) with value 5, MAX_PRIORITY with value 10.

Get and Set Thread Priority:

• int getPriority(): Thread.getPriority() method returns priority of given thread.


• void setPriority(int newPriority): Thread.setPriority() method changes the priority of
thread to the value newPriority. This method throws IllegalArgumentException if value of
parameter newPriority goes beyond minimum(1) and maximum(10) limit.
Example:
public class Demo extends Thread
{
public void run()
{
System.out.println("Inside run method");
}
Thread Priorities

public static void main(String args[])


{
Demo t1 = new Demo();
Demo t2 = new Demo();
System.out.println("t1 thread priority:"+t1.getPriority());
System.out.println("t2 thread priority:"+t2.getPriority());
t1.setPriority(2);
t2.setPriority(5);
System.out.println("t1 thread priority:"+t1.getPriority());
System.out.println("t2 thread priority:"+t2.getPriority());
System.out.println(Thread.currentThread().getName());
System.out.println("Main thread Priority:“
+Thread.currentThread().
getPriority());
Thread.currentThread().setPriority(10);
System.out.println("Main thread Priority:“

+Thread.currentThread().getPriority());
}
}

Output:
t1 thread priority:5
t2 thread priority:5
t1 thread priority:2
t2 thread priority:5
Main
Main thread priority:5
Main thread priority:10
Methods of Thread Class

Methods

• getName(): It is used for obtaining a thread’s name


• setName(): changes the name of the thread
• getPriority(): Obtain a thread’s priority
• setPriority(): changes the priority of the thread
• isAlive(): Determine if a thread is still running
• join(): Wait for a thread to terminate
• run(): Entry point for the thread
• sleep(): Suspend a thread for a period of time
• start(): Start a thread by calling its run() method
• isDaemon(): tests if the thread is a daemon thread
• Thread currentThread(): returns the reference of currently
executing thread.
• Thread.State getState(): returns the state of the thread.
• sleep(): Causes the currently executing thread to sleep

Commonly used Constructors of Thread Class

• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r, String name)
Creation of Thread

There are two ways to create a thread in Java:


• 1) By implementing Runnable Interface
• 2) By extending Thread Class

1. By Implementing Runnable Interface


The easiest way to create a thread is to create a class that implements the Runnable
interface. To implement Runnable, a class need only implement a single method
called run().

Example:
class Demo implements Runnable
{
public void run()
{
try
{
for (int i = 4; i > 0; i--)
{
System.out.println("Child Thread:"
+i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted");
}
System.out.println("Exiting Child Thread");
}
}
Creation of Thread - By Implementing Runnable Interface
public class MainThread
{
public static void main(String args[])
{
Demo d = new Demo();
Thread s = new Thread(d);
s.start();
try
{
for (int i = 4; i > 0; i--)
{
System.out.println("Main Thread:"
+i);
Thread.sleep(5000);
}
}
catch (InterruptedException e)
{
System.out.println("Main interrupted");
}
System.out.println("Exiting Main Thread");
}
}
Output:
Main Thread:4
Child Thread:4
Child Thread:3
Child Thread:2
Child Thread:1
Main Thread:3
Exiting Child Thread
Main Thread:2
Main Thread:1
Exiting Main Thread
Creation of Thread – By Extending Thread Class

2. By Extending Thread Class


The second way to create a thread is to create a new class that extends Thread, and
then to create an instance of that class. The extending class must override the
run( ) method, which is the entry point for the new thread. It must also call start( )
to begin execution of the new thread.
Example:
class Demo1 extends Thread
{
public void run()
{
try
{
for (int i = 4; i > 0; i--)
{
System.out.println("Child Thread:"
+i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted");
}
System.out.println("Exiting Child Thread");
}
}
public class MainThread
{
public static void main(String args[])
{
Creation of Thread – By Extending Thread Class

Demo1 d = new Demo1();


d.start();
try
{
for (int i = 4; i > 0; i--)
{
System.out.println("Main Thread:"
+i);
Thread.sleep(5000);
}
}
catch (InterruptedException e)
{
System.out.println("Main interrupted");
}
System.out.println("Exiting Main Thread");
}
}
Output:
Main Thread:4
Child Thread:4
Child Thread:3
Child Thread:2
Child Thread:1
Main Thread:3
Exiting Child Thread
Main Thread:2
Main Thread:1
Exiting Main Thread
Synchronizing Threads

Java Synchronization:

Synchronization in java is the capability to control the access of multiple threads to any
shared resource. Java Synchronization is a better choice if we want to allow only one
thread to access the shared resource.

Need for Synchronization:

When two or more threads start within a program, there arises a situation where multiple
threads try to access the same resources and finally produce erroneous and unforeseen
results. For ex., if multiple threads try to write within a same file then they may corrupt the
data because one of the threads can override data or while one thread is opening the same
file at the same time another thread might be closing the same file. So there is a need to
synchronize the action of multiple threads and make sure that only one thread can access
the resource at a given point in time. This is implemented using a concept
called monitors. Each object in Java is associated with a monitor, which a thread can lock
or unlock. Only one thread at a time may hold a lock on a monitor. Java programming
language provides a way of creating threads and synchronizing their task by
using synchronized blocks.

General Syntax:
synchronized(object)
{
//statement to be synchronized
}

Synchronization is mainly used to


• To prevent thread interference.
• To prevent consistency problem.
Synchronizing Threads

Types of Synchronization:
There are two types of synchronization
• Process Synchronization: The simultaneous execution of multiple threads
or processes to reach a state such that they commit to a certain sequence of
actions.
• Thread Synchronization: When more than one thread tries to access a
shared resource, it should be ensured that the resource will be used by only
one thread at a time.

Thread Synchronization:
There are two types of thread synchronization namely mutual exclusive and inter-
thread communication.
• Mutual Exclusive
• Synchronized method.
• Synchronized block.
• Static synchronization.
• Cooperation (Inter-thread communication in java)

1. Mutual Exclusive helps keeping threads from interfering with one another while
sharing data. This can be done by three ways in java:
• by synchronized method
• by synchronized block
• by static synchronization

Synchronized method:
• If you declare any method as synchronized, it is known as synchronized
method.
• Synchronized method is used to lock an object for any shared resource.
• When a thread invokes a synchronized method, it automatically acquires the
lock for that object and releases it when the thread completes its task.
Synchronized Method

Example of synchronized method

public class SynThread


{
public static void main(String args[])
{
sync s = new sync();
ThreadDemo m1 = new ThreadDemo(s, "Thread1");
ThreadDemo m2 = new ThreadDemo(s, "Thread2");
ThreadDemo m3 = new ThreadDemo(s, "Thread3");
}
}
class ThreadDemo extends Thread
{
sync s;
ThreadDemo(sync s, String str)
{
super(str);
this.s = s;
start();
}
public void run()
{
s.print(Thread.currentThread().getName());
}
}
class sync
{
public synchronized void print(String str)
{
Synchronized Method
for (int i = 0; i < 3; i++)
{
System.out.println("Started:" + str);
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
}
}
}
}
Output:
Started:Thread1
Started:Thread1
Started:Thread1
Started:Thread3
Started:Thread3
Started:Thread3
Started:Thread2
Started:Thread2
Started:Thread2

Synchronized Block

• Synchronized block can be used to perform synchronization on any specific resource


of the method.
• For ex. If you have 20 lines of code in a method, and you want to synchronize only 5
lines, synchronized block can be used. If you put all the codes of the method in the
synchronized block, it will work same as the synchronized method.
Synchronized Block

Syntax for synchronized block


synchronized (object reference expression)
{
//code block
}
An example of Synchronized block is given in the below Fig.4.2.

Fig.4.2 Synchronized Block


Synchronized Block

class syncblock
{
void print(int n)
{
synchronized(this)
{ //synchronized block
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}
class Thread1 extends Thread
{
syncblock s;
Thread1(syncblock s)
{
this.s=s;
}
` public void run()
{
s.print(5);
}
}
Synchronized Block
class Thread2 extends Thread
{
syncblock s;
Thread2(syncblock s)
{
this.s=s;
}
public void run()
{
s.print(100);
}
}
public class SynchBlock
{
public static void main(String args[])
{
syncblock obj = new syncblock(); //only one object
Thread1 t1=new Thread1(obj);
Thread2 t2=new Thread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
Use synchronized keyword on the static method to perform static synchronization.

Example:
class staticsync
{
synchronized static void print(int n)
{
for(int i=1;i<=3;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(500);
}
catch(Exception e)
{
}
}
}
}
class Thread1 extends Thread
{
public void run()
{
staticsync.print(1);
}
}
class Thread2 extends Thread
{
public void run()
{
staticsync.print(3);
}
}
Static synchronization

class Thread3 extends Thread


{
public void run()
{
staticsync.print(50);
}
}
public class TestSynch
{
public static void main(String args[])
{
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
Thread3 t3=new Thread3();
t1.start();
t2.start();
t3.start();
}
}
Output:

3
6
9
1
2
3
50
100
150
INTER-THREAD COMMUNICATION

Definition
• Inter-Thread communication or Co-operation is defined as the process
of allowing synchronized threads to communicate with each other.
• It is a mechanism in which a thread is paused running in its critical section
and another thread is allowed to enter (or lock) in the same critical section to
be executed.

Methods of Object class used to implement Inter-


Thread Communication
Inter-Thread Communication can be implemented by following
methods of Object class

• wait()

• notify()

• notifyAll()
wait() Method causes current thread to release the lock and wait
until either another thread invokes the notify() method or the notifyAll() method for
this object, or a specified amount of time has elapsed. Figure 4.1 illustrates the
functionality of wait() method.

Figure 2.1: wait() Method Role


Syntax:
public final void wait()throws InterruptedException
public final void wait(long timeout)throws InterruptedException

notify() method wakes up a single thread that is waiting on this


object's monitor. If any threads are waiting on this object, one of them is chosen to
be awakened. Figure 4.2 illustrates the functionality of notify() method in Inter-
Process Communication.

Figure 4.2: Role of notify() method

Syntax: public final void notify()

notifyAll() wakes up all the threads that called wait() on the same
object.

Syntax: public void notifyAll()

Example for Inter-Thread Communication (Producer


Consumer Problem)
• Producer-consumer problem (also known as the bounded-buffer problem) is a
classic example of a multi-process synchronization problem

• The problem describes two processes, the producer and the consumer, which
share a common, fixed-size buffer used as a queue
• The producer’s job is to generate data, put it into the buffer, and start again

• At the same time, the consumer is consuming the data (i.e. removing it from
the buffer), one piece at a time. Figure 4.3 depicts the Producer-Consumer
Problem

Figure 4.3: Producer-Consumer Problem

While implementing, the following two conditions should be satisfied:

• Producer should not try to add data into the buffer when it is full

• Consumer should not try to remove data from an empty buffer


PROGRAM FOR PRODUCER CONSUMER PROBLEM
IMPLEMENTATION

public class ProducerConsumerTest {


public static void main(String[] args) {
Buffer c = new Buffer();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}

class Buffer {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
} catch (InterruptedException e) {}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) { }
}
contents = value;
available = true;
notifyAll();
}
}

class Consumer extends Thread {


private Buffer buff;
private int number;
public Consumer( Buffer c, int number) {
buff = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 5; i++) {
value = buff.get();
System.out.println("Consumer got: " + value);
}
}
}
class Producer extends Thread {
private Buffer buff;
private int number;
public Producer( Buffer c, int number) {
buff = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 5; i++) {
buff.put(i);
System.out.println("Producer put: " + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}

OUTPUT
Producer put: 0
Consumer got: 0
Producer put: 1
Consumer got: 1
Producer put: 2
Consumer got: 2
Producer put: 3
Consumer got: 3
Producer put: 4
Consumer got: 4
10. Assignment
1. Explain the exception handling mechanism with a suitable
example.

2. (i) How will you create your own exceptions? Explain


with an example
(ii) Demonstrate rethrowing an exception.
11. PART – A
Question and Answers
PART - A
1. What are the Exception Handling Keywords in Java? (K1, CO3)

Try-catch
Throw
Throws
Finally

2. What are important methods of Java Exception Class? (K1, CO3)

String getMessage()
String getLocalizedMessage()
synchronized Throwable getCause()
String toString()
void printStackTrace()

3. What is difference between Checked and Unchecked Exception in Java?


(K1, CO3)

Checked Exceptions should be handled in the code using try-catch block or


else method should use throws keyword to let the caller know about the
checked exceptions that might be thrown from the method. Exception is the
super class of all checked exceptions. Checked exceptions are error scenarios
that requires to be handled in the code, or else you will get compile time error.
Unchecked Exceptions are not required to be handled in the program or to
mention them in throws clause of the method. RuntimeException is the super
class of all unchecked exceptions. Note that RuntimeException is the child class
of Exception. Unchecked exceptions are mostly caused by poor programming,
for example NullPointerException when invoking a method on an object
reference without making sure that it’s not null.

4. What is difference between throw and throws keyword in Java? (K1,


CO3)

throws keyword is used with method signature to declare the exceptions that the
method might throw whereas throw keyword is used to disrupt the flow of program
and handing over the exception object to runtime to handle it
PART - A

5. What is difference between final, finally and finalize in Java? (K1, CO3)

final and finally are keywords in java whereas finalize is a method.final keyword can
be used with class variables so that they can’t be reassigned, with class to avoid
extending by classes and with methods to avoid overriding by subclasses, finally
keyword is used with try-catch block to provide statements that will always gets
executed even if some exception arises, usually finally is used to close resources.
finalize() method is executed by Garbage Collector before the object is destroyed,
it’s great way to make sure all the global resources are closed.
Out of the three, only finally is related to java exception handling.

6. List out some checked exception (K3, CO3)

NoSuchFieldException

InstantiationException

IllegalAccessException

ClassNotFoundException

NoSuchMethodException

CloneNotSupportedException

InterruptedException
PART - A

7. List out some Un-Checked Exception (K3, CO3)

IndexOutOfBoundsException

ArrayIndexOutOfBoundsException

ClassCastException

ArithmeticException

NullPointerException

IllegalStateException

SecurityException

8. What are the type of Errors? (K1, CO3)

Compile-Time Error

Run-Time Error

9. Define Java Exception. (K1, CO3)

A java exception is an object that describes an exceptional condition that has


occurred in a piece of code. When an exceptional condition arises, an object
representing that exception is created an thrown in the method that caused the
error.

10. What is chained exception? (K1, CO3)


Chained exception allows to relate one exception with another exception, ie one
exception describes cause of another exception. For example, consider a situation in
which a method throws an ArithmeticException because of an attempt to divide by
zero but the actual cause of exception was an I/O error which caused the divisor to
be zero.
PART - A

11. Draw the exception hierarchy. (K2, CO3)

12. What does java.lang.StackTraceElement represent? (K1, CO3)


The java.lang.StackTraceElement class element represents a single stack frame. All
stack frames except for the one at the top of the stack represent a method
invocation. The frame at the top of the stack represents the excecution point at
which the stack trace was generated.

13. What are the useful methods of throwable class? (K1, CO3)
Public String getMesage()
Public String getLocalizeMessage()
Public String toString()
Public synchronized Throwable getCause()
Public void printStackTrace()

14. Compare throw and throws(K2, CO3)


Throw is used to throw an exception & throws is used to declare an exception
Throw is used in method implementation & throws is used in method signature
PART - A
15. What is the use of try and catch exception? (K1, CO3)
Try-catch block is used for exception handling in the program code. Try is the start
of the block and catch is at the end of try block to handle the exceptions. A program
can have multiple catch blocks with a try and try-catch block can be nested also.
Catch block requires a parameter that should be of type exception.

16. Can we have an empty catch block? (K2, CO3)


We can have an empty catch block but it’s the example of worst programming. We
should never have empty catch block because if the exception is caught by that
block, we will have no information about the exception and it will be a nightmare to
debug it.

17. How Java Exception Hierarchy categorized? (K1, CO3)


Java Exceptions are hierarchical and inheritance is used to categorize different types
of exceptions. Throwable is the parent class of Java Exceptions Hierarchy and it has
two child objects – Error and Exception. Exceptions are further divided into checked
exceptions and runtime exception.
PART – A
18. What is thread in Java? (K1, CO4)
• A Thread is a concurrent unit of execution. Or in other words you can say that it is
part of process that can run concurrently with other parts of the process.
19 What is Multithreading? (K1, CO4)
• The process of executing multiple threads simultaneously is known as
multithreading. Java supports multithreading.
• The main advantage of multithreading is reducing CPU idle time and improving the
CPU utilization. This makes the job to be completed in less time.
20 What is the difference between a process and a thread in Java? (K1,
CO4)
• A program in execution is often referred as process. A thread is a subset(part) of the
process.
• A process consists of multiple threads. A thread is a smallest part of the process that
can execute concurrently with other parts(threads) of the process.
• A process is sometime referred as task. A thread is often referred as lightweight
process.
• A thread can communicate with other thread (of the same process) directly by using
methods like wait(), notify(), notifyAll(). A process can communicate with other
process by using inter-process communication.
• New threads are easily created. However the creation of new processes require
duplication of the parent process.
• Threads have control over the other threads of the same process. A process does
not have control over the sibling process, it has control over its child processes only.
21 What are the two ways of creating a thread? (K1, CO4)
• We can create a thread by using any of the two following methods.
1) By implementing Runnable interface
2) By extending Thread class
22 What is life cycle of thread? (K1, CO4)
• New born state.
PART – A
• Runnable state
• Running state
• Blocked state
• Dead state
23 Can we start a thread twice in Java? (K1, CO4)
• No, once a thread is started, it can never be started again. Doing so will
throw an illegalThreadStateException
24 Can we call run() method of Thread class? (K1, CO4)
• We can call run() method if we want but then it would behave just like a
normal method and we would not be able to take the advantage of
multithreading. In general run() methods starts execution when we call
start() method of a Thread class.
25 What is deadlock? (K1, CO4)
• A deadlock is a condition when two or more threads are in waiting for each
other to release the resources that they need. For example Thread A holds a
resource X and need resource Y whereas Thread B holds a resource Y and
need X, in this case both threads are waiting for each other to release the
resource and are in blocked condition.
26 What is synchronization? (K1, CO4)
• It is a technique of granting access to the shared resources in multithread
environment to avoid inconsistencies in the results.
27. What is the difference between notify() and notifyAll()? (K1, CO4)
• notify() wakes up the first thread that called wait() on the same object,
whereas the notifyAll() method wakes up all the waiting threads.
28. What does join() method do? (K1, CO4)
• The join() method is used to hold the execution of currently running thread
until the specified thread is dead (finished execution).
29. How does thread communicate with each other? (K1, CO4)
• when threads share resources, communication between Threads is important
to coordinate their efforts.
PART – A
• Object class wait(), notify() and notifyAll() methods allows threads to
communicate about the lock status of a resource.
30. What is the difference between wait() and sleep() method? (K1,
CO4)
wait() sleep()

The wait() method is defined in The sleep() method is defined


Object class. in Thread class.

The wait() method releases the The sleep() method doesn't


lock. release the lock.

31. What is Daemon Threads in Java? (K1, CO4)


• Daemon thread is a thread that has no other role than to serve other threads.
• Daemon thread have low priority.
• Methods:
1. setDaemon(boolean on)
2. isDeamon()
32 What is thread group? (K1, CO4)
• Thread group is a collection of thread that can be managed together.
• All the threads belong to the same thread group.
• Methods:
1. activeCount()
2. activeGroupCount()
3. checkAccess()
4. getName()
5. destroy()
6. enumerate()
7. interrupt()
12. PART – B
Questions
PART - B
1. Explain in detail the important methods of Java Exception Class? (K2, CO3)
2. How will you create your Own Exception Subclasses? (K2, CO3)
3. Explain in detail Chained exception with an example program. (K1, CO3)
4. Explain in detail the various exception types with its hierarchy. (K1, CO3)
5. Write programs to illustrate arithmetic exception, ArrayIndexOutOfBounds
Exception and NumberFormat Exception. (K2, CO3)
6. Write a calculator program using exceptions and functions. (K2, CO3)

7. Create two exception classes that can be used by the stack classes developed by
TRY (K3, CO3)

8. Explain the different scenarios causing “Exception in thread main”? (K2, CO3)
9. What is a thread? Describe the lifecycle and states of thread with example. (K1,
K4, CO4)
10. Summarize briefly about thread synchronization with an example. (K2, CO4)
11. Demonstrate Inter thread communication and suspending, resuming and
stopping threads. (K2, CO4)
12. List the two ways of implementing threads with example. (K4, CO4)
13. Show how to extend thread class and how to implement runnable interface for
creating and starting threads? (K2, CO4)
13. Online Certifications
1. https://www.hackerrank.com/skills-verification/java_basic
2. https://www.sololearn.com/Course/Java/
3. https://www.coursera.org/specializations/object-oriented-programming
4. https://www.udemy.com/course/java-the-complete-java-developer-course/ [Paid]
5. https://nptel.ac.in/courses/106/105/106105191/ [Paid]
6. https://education.oracle.com/java-se-8-fundamentals/courP_3348 [Paid]
14. Real Time Applications

• Android Apps

• Scientific Applications

• Financial Applications

• Games

• Desktop Applications

• Web Applications

92
15. Content Beyond Syllabus

Java Exception propagation


An exception is first thrown from the top of the stack and if it is not caught, it
drops down the call stack to the previous method,If not caught there, the
exception again drops down to the previous method, and so on until they are
caught or until they reach the very bottom of the call stack.This is called
exception propagation.
Rule: By default Unchecked Exceptions are forwarded in calling chain
(propagated).

class TestExceptionPropagation1{
void m()
{
int data=50/0;
}
void n()
{
m();
}
void p(){
try
{
n();
}
catch(Exception e)
{
System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
OutPut: exception handled
normal flow…
• In the above example exception occurs in m() method where it
is not handled, so it is propagated to previous n() method
where it is not handled, again it is propagated to p() method
where exception is handled.
• Exception can be handled in any method in call stack either in
main() method,p() method,n() method or m() method.
16. Assessment Schedule
• Tentative schedule for the Assessment During
2021-2022 odd semester

Name of the
S.NO Start Date End Date Portion
Assessment

1 IAT 1 20.09.2021 25.09.2021 UNIT 1 & 2

2 IAT 2 22.10.2021 28.10.2021 UNIT 3 & 4

3 REVISION 13.11.2021 16.11.2021 UNIT 5 , 1 & 2

4 MODEL 18.11.2021 29.11.2021 ALL 5 UNITS

114
17. Text Books & References
TEXT BOOKS
1.Herbert Schildt, “Java The complete reference”, 11th Edition, McGraw Hill Education,
2019.

REFERENCES
1.Cay S. Horstmann, Gary cornell, “Core Java Volume –I Fundamentals”, 9th Edition,
Prentice Hall, 2019.
2.Paul Deitel, Harvey Deitel, “Java SE 8 for programmers”, 3rd Edition, Pearson, 2015.
3.Steven Holzner, “Java 2 Black book”, Dreamtech press, 2011.
4.Timothy Budd, “Understanding Object-oriented programming with Java”, Updated
Edition, Pearson Education, 2008.
5.https://www.tutorialspoint.com/java/index.htm
6.https://www.javatpoint.com/java-tutorial
7.https://www.w3schools.com/java/
8.https://www.geeksforgeeks.org/java-tutorial/
9.https://docs.oracle.com/javase/tutorial/
18. Mini Project
Interest Calculator with Exception handling
Calculate interest based on the type of the account and the status
of the account holder. The rates of interest changes according to
the amount (greater than or less than 1 crore), age of account
holder (General or Senior citizen) and number of days if the type
of account is FD or RD.
Some sample rates are given in the below tables: Rate of FD
citizen) and interest for amounts below 1 Crore:

Current Rates of interest


Maturity Period General Senior Citizen
7 days to 14 days 4.50 5.00

15 days to 29 days 4.75 5.25

30 days to 45 days 5.50 6.00

45 days to 60 days 7 7.50

61 days to 184 days 7.50 8.00

185 days to 1 year 8.00 8.50

Rate of FD interest for amounts above 1 Crore:

Maturity Period Interest Rate


7 days to 14 days 6.50
15 days to 29 days 6.75
30 days to 45 days 6.75
45 days to 60 days 8

61 days to 184 days 8.50

185 days to 1 year 10.00


Rate of RD interests:
Current Rates of interest
Maturity
General Senior Citizen
Period
6 months 7.50 8.00
9 months 7.75 8.25
12 months 8.00 8.50
15 months 8.25 8.75
18 months 8.50 9.00
21 months 8.75 9.25

SB Account interest rates:


Type of Account Interest Rate

Normal 4%
NRI 6%

Requirements:
1. Separate classes should be created for the different types of
accounts.
2. All classes should be derives from an abstract class named
‘Account’ which contains a method called ‘calculateInterest’.
3. Implement the calculateInterest method according to the type of
the account, interest rates, amount and age of the account holder.
4. If the user is entering any invalid value (For eg. Negative value) in
any fields, raise a user defined exception.
Sample class structure is given below:

Account(Abstract)

double interestRate

double amount
FDAccount
double interestRate
double amount
int noOfDays
ageOfACHolder
abstract double calculateInterest()

SBAccount
double interestRate
double amount
abstract double calculateInterest()

RDAccount
double interestRate
double amount
int noOfMonths;
double
monthlyAmount;
abstract double calculateInterest()

Hint: Use method overriding


Sample Output:
Select the option:

1.Interest Calculator –SB


2.Interest Calculator –FD
3.Interest Calculator –RD
4.Exit
1

Enter the Average amount in your account: 10000


Interest gained: Rs. 400 Select the option:
1.Interest Calculator –SB
2.Interest Calculator –FD
3.Interest Calculator –RD
4.Exit
2

Enter the FD amount: 10000

Enter the number of days: 91

Enter your age: 65


Interest gained is: 800 Select the option:

1.Interest Calculator –SB


2.Interest Calculator –FD
3.Interest Calculator –RD
4.Exit

Enter the FD amount: 10000

Enter the number of days: 91

Enter your age: 34

Interest gained is: 750


Select the option:

1. Interest Calculator –SB


2. Interest Calculator –FD
3. Interest Calculator –RD
4. Exit

Enter the FD amount: 10000

Enter the number of days: -7

Enter your age: 78

Invalid Number of days. Please enter correct values.


Thank you

Disclaimer:

This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.

You might also like