0% found this document useful (0 votes)
9 views98 pages

Java CH 1

The document provides an overview of Java programming, focusing on variables, data types, and control statements. It explains different variable types such as String, int, float, char, and boolean, as well as the concepts of classes, objects, interfaces, and arrays. Additionally, it covers decision-making statements like if-else and ternary operators, along with examples to illustrate their usage.

Uploaded by

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

Java CH 1

The document provides an overview of Java programming, focusing on variables, data types, and control statements. It explains different variable types such as String, int, float, char, and boolean, as well as the concepts of classes, objects, interfaces, and arrays. Additionally, it covers decision-making statements like if-else and ternary operators, along with examples to illustrate their usage.

Uploaded by

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

Chapter- one

Overview of Java Programming


BY:
Andargie Mekonnen
Java Variables
Variables are containers for storing data values.

In Java, there are different types of variables, for example:


String - stores text, such as "Hello". String values are surrounded by double quotes

Integer(int) - stores integers (whole numbers), without decimals, such as 123 or -123

float - stores floating point numbers, with decimals, such as 19.99 or -19.99

char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes

boolean - stores values with two states: true or false

11/18/2024 Andargie Mekonnen 2


Java Variables and Data Types
Declaring (Creating) Variables
To create a variable, you must specify the type and assign it a value:

 SyntaxGet your own Java Server

type variableName = value;

Where type is one of Java's types (such as int or String), and variableName is the name of the
variable (such as x or name). The equal sign is used to assign values to the variable.

Example :Create a variable called name of type String and assign it the value "John":

String name = "John";

[Link](name);
11/18/2024 Andargie Mekonnen 3
Java Variables and Data Types
Data Types in Java

Data types in Java are of different sizes and values that can
be stored in the variable that is made as per convenience and
circumstances to cover up all test cases.

Java has two categories in which data types are segregated


 Primitive Data Type: are only single values and have no special
capabilities. such as boolean, char, int, short, byte, long, float, and
double
 Non-Primitive Data Type or Object Data type: will contain a
memory address of variable values because the reference types
won’t store the variable value directly in memory. such as String,
Array, objects etc.

11/18/2024 Andargie Mekonnen 4


Java Variables and Data Types
Strings
 Strings are defined as an array of characters. The difference between a character array and a string in Java is, that the
string is designed to hold a sequence of characters in a single variable whereas, a character array is a collection of
separate char-type entities. Unlike C/C++, Java strings are not terminated with a null character.

 Syntax: Declaring a string

<String_Type> <string_variable> = “<sequence_of_string>”;

 Example:

// Declare String without using new operator

String s = "GeeksforGeeks";

// Declare String using new operator

String s1 = new String("GeeksforGeeks");


11/18/2024 Andargie Mekonnen 5
Java Variables and Data Types
 Class

A class is a user-defined blueprint or prototype from which objects are created.

It represents the set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
 Modifiers: A class can be public or has default access. Refer to access specifiers for classes or
interfaces in Java
 Class name: The name should begin with an initial letter (capitalized by convention).
 Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.
 Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by
the keyword implements. A class can implement more than one interface.
 Body: The class body is surrounded by braces, { }.
11/18/2024 Andargie Mekonnen 6
Java Variables and Data Types
Object
An Object is a basic unit of Object-Oriented Programming and represents real-life entities.

A typical Java program creates many objects, which as you know, interact by invoking methods.
An object consists of :
State: It is represented by the attributes of an object. It also reflects the properties of an
object.
Behavior: It is represented by the methods of an object. It also reflects the response of an
object to other objects.
Identity: It gives a unique name to an object and enables one object to interact with other
objects.

11/18/2024 Andargie Mekonnen 7


Java Variables and Data Types
Interface
An interface is a completely "abstract class" that is used to group related methods with
empty bodies:

Example

interface Animal {

public void animalSound(); // interface method (does not have a body)

public void run(); // interface method (does not have a body)

11/18/2024 Andargie Mekonnen 8


Java Variables and Data Types
Arrays in Java
In Java, Array is a group of like-typed variables referred to by a common name. Arrays in Java
work differently than they do in C/C++. Following are some important points about Java arrays.

In Java, all arrays are dynamically allocated.

Arrays may be stored in contiguous memory [consecutive memory locations].

Since arrays are objects in Java, we can find their length using the object property length. This is
different from C/C++, where we find length using sizeof.

A Java array variable can also be declared like other variables with [] after the data type.

The variables in the array are ordered, and each has an index beginning with 0.
11/18/2024 Andargie Mekonnen 9
Java Variables and Data Types
Arrays in Java
Java array can also be used as a static field, a local variable, or a method parameter.
An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class depending
on the definition of the array.
In the case of primitive data types, the actual values might be stored in contiguous memory
locations(JVM does not guarantee this behavior). In the case of class objects, the actual objects
are stored in a heap segment.
Note: This storage of arrays helps us randomly access the elements of an array [Support Random
Access].

11/18/2024 Andargie Mekonnen 10


Java Variables and Data Types
Creating, Initializing, and Accessing an Arrays
 One-Dimensional Arrays
 The general form of a one-dimensional array declaration is
- - type var-name[];
-- type[] var-name;

An array declaration has two components: the type and the name. type declares the
element type of the array.
 Example:
// both are valid declarations
int intArray[];
int[] intArray;
// an array of references to objects of the class MyClass (a class created by user)
MyClass myClassArray[];
// array of Object
Object[] ao,
// array of Collection of unknown type
Collection[] ca;
11/18/2024 Andargie Mekonnen 11
Java Variables and Data Types
Instantiating an Array in Java
When an array is declared, only a reference of an array is created. To create or give memory to the array, you
create an array like this: The general form of new as it applies to one-dimensional arrays appears as follows:

var-name = new type [size];

Example:

//declaring array

int intArray[];

// allocating memory to array

intArray = new int[20];

// combining both statements in one

int[] intArray = new int[20];

11/18/2024 Andargie Mekonnen 12


Java Variables and Data Types
Instantiating an Array in Java
Note: The elements in the array allocated by new will automatically be initialized
to zero (for numeric types), false (for boolean), or null (for reference types). Do
refer to default array values in Java.
In a situation where the size of the array and variables of the array are already known, array literals can be
used.

// Declaring array literal

int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

The length of this array determines the length of the created array.

There is no need to write the new int[] part in the latest versions of Java.
11/18/2024 Andargie Mekonnen 13
Java Variables and Data Types
Accessing Java Array Elements using for Loop
Each element in the array is accessed via its index. The index begins with 0 and ends at
(total array size)-1.

All the elements of array can be accessed using Java for Loop.

// accessing the elements of the specified array

for (int i = 0; i < [Link]; i++)

[Link]("Element at index " + i + " : "+ arr[i]);

11/18/2024 Andargie Mekonnen 14


Java Variables and Data Types
Arrays of Objects in Java
An array of objects is created like an array of primitive-type data items in the following
way.

Student[] arr = new Student[5]; //student is a user-defined class

Syntax:

-- data type[] arrName;

-- datatype arrName[];

-- datatype [] arrName;
11/18/2024 Andargie Mekonnen 15
Java Variables and Data Types
class Student { arr[0] = new Student(1, "aman");
public int roll_no;
arr[1] = new Student(2, "vaibhav");
public String name;
Student(int roll_no, String name) arr[2] = new Student(3, "shikar");
{
arr[3] = new Student(4, "dharmesh");
this.roll_no = roll_no;
[Link] = name; }} arr[4] = new Student(5, "mohit");
public class GFG {
for (int i = 0; i < [Link]; i+
public static void main(String[] args)
{ [Link]("Element at " + i + " : "
Student[] arr;
+ arr[i].roll_no + " "
// allocating memory for 5 objects of type
Student. + arr[i].name); }}
arr = new Student[5];
11/18/2024 Andargie Mekonnen 16
Java Variables and Data Types
Multidimensional Arrays in Java
Multidimensional arrays are arrays of arrays with each element of the array
holding the reference of other arrays.
A multidimensional array is created by appending one set of square brackets
([]) per dimension.
Syntax of Java
-- datatype [][] arrayrefvariable;
-- datatype arrayrefvariable[][];

11/18/2024 Andargie Mekonnen 17


Java Variables and Data Types
Example
// Java Program to demonstrate // Number of Rows
// Java Multidimensional Array
[Link]("Number of
import [Link].*; Rows:"+
[Link]);
// Driver class
class GFG {
public static void main(String[] args) // Number of Columns
{ [Link]("Number of
// Syntax Columns:"+
int[][] arr = new int[3][3]; arr[0].length);
// 3 row and 3 column }
}
11/18/2024 Andargie Mekonnen 18
Java Variables and Data Types
Example
package exzmple6; for (int j = 0; j<arr[0].length; j++)
{
public class Exzmple6 {
[Link](arr[i][j]+"
public static void main(String[] ");
args) { }
// Syntax [Link](" ");
int[][] arr }
={{1,2,3},{4,5,6},{7,8,9}};
for (int i=0;i<[Link];i++) { }
}
11/18/2024 Andargie Mekonnen 19
Decision and Repetition statement
Java If-else Statement
The Java if statement is used to test the condition. It checks boolean
condition: true or false. There are various types of if statement in Java.
Java if Statement
The Java if statement tests the condition. It executes the if block if
condition is true.
Syntax:
if(condition){
//code to be executed
}

11/18/2024 Andargie Mekonnen 20


Decision and Repetition statement
Java If-else Statement example
/Java Program to demonstrate the use of if statement.
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
[Link]("Age is greater than 18");
}
}
}

11/18/2024 Andargie Mekonnen 21


Decision and Repetition statement
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}

11/18/2024 Andargie Mekonnen 22


Decision and Repetition statement
Example:
//A Java Program to demonstrate the use of if-else statement.
//It is a program of odd and even number.
public class IfElseExample {
public static void main(String[] args) {
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
[Link]("even number");
}else{
[Link]("odd number");
}
}
}

11/18/2024 Andargie Mekonnen 23


Decision and Repetition statement
Example:Using Ternary Operator
We can also use ternary operator (? :) to perform the task of if...else
statement. It is a shorthand way to check the condition. If the condition is
true, the result of ? is returned. But, if the condition is false, the result of : is
returned.
Example:
public class IfElseTernaryExample {
public static void main(String[] args) {
int number=13;
//Using ternary operator
String output=(number%2==0)?"even number":"odd number";
[Link](output);
}
}
11/18/2024 Andargie Mekonnen 24
Decision and Repetition statement
Java if-else-if ladder Statement :The if-else-if ladder statement executes one condition
from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false }
11/18/2024 Andargie Mekonnen 25
Decision and Repetition statement
Example: }
//Java Program to demonstrate the use of If else- else if(marks>=60 && marks<70){
if ladder. [Link]("C grade");
//It is a program of grading system for fail, D grade }
, C grade, B grade, A grade and A+.
else if(marks>=70 && marks<80){
public class IfElseIfExample { [Link]("B grade");
public static void main(String[] args) { }
int marks=65; else if(marks>=80 && marks<90){
[Link]("A grade");
if(marks<50){ }else if(marks>=90 && marks<100){
[Link]("fail"); [Link]("A+ grade");
} }else{
else if(marks>=50 && marks<60){ [Link]("Invalid!");
[Link]("D grade"); }
} }
}
11/18/2024 Andargie Mekonnen 26
Decision and Repetition statement
Java Nested if statement: represents the if block within another if block.
Here, the inner if block condition executes only when outer if block
condition is true.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}

11/18/2024 Andargie Mekonnen 27


Decision and Repetition statement
Example:
public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
[Link]("You are eligible to donate blood");
}
}
}}
11/18/2024 Andargie Mekonnen 28
Decision and Repetition statement
Java Switch Statement
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched; }

11/18/2024 Andargie Mekonnen 29


Decision and Repetition statement
Example:[Link] break;
public class SwitchExample { case 20: [Link]("20");
public static void main(String[] args) { break;
//Declaring a variable for switch expression case 30: [Link]("30");
break;
int number=20; //Default case statement
//Switch expression default:[Link]("Not in 10,
switch(number){ 20 or 30");
//Case statements }
case 10: [Link]("10"); }
}

11/18/2024 Andargie Mekonnen 30


Decision and Repetition statement
Java simple for loop [Link]
Syntax: //Java Program to demonstrate the
for(initialization; condition; increm example of for loop
ent/decrement){ //which prints table of 1
//statement or code to be executed public class ForExample {
public static void main(String[] ar
} gs) {
//Code of Java for loop
for(int i=1;i<=10;i++){
[Link](i);
}
}
}
11/18/2024 Andargie Mekonnen 31
Decision and Repetition statement
Java Nested for Loop: If we have a for loop inside the another loop, it is known as
nested for loop. The inner loop executes completely whenever outer loop executes.
Example:
public class NestedForExample {
public static void main(String[] args) {
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
[Link](i+" "+j);
}//end of i
}//end of j
}
}
11/18/2024 Andargie Mekonnen 32
Decision and Repetition statement
[Link]
public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
[Link]("* ");
}
[Link]();//new line
}
}
}

11/18/2024 Andargie Mekonnen 33


Decision and Repetition statement
[Link]
public class PyramidExample2 {
public static void main(String[] args) {
int term=6;
for(int i=1;i<=term;i++){
for(int j=term;j>=i;j--){
[Link]("* ");
}
[Link]();//new line
}
}
}

11/18/2024 Andargie Mekonnen 34


Decision and Repetition statement
Java for-each Loop
The for-each loop is used to traverse array or collection in Java. It is easier
to use than simple for loop because we don't need to increment value and use
subscript notation.
It works on the basis of elements and not the index. It returns element one
by one in the defined variable.
Syntax:
for(data_type variable : array_name){
//code to be executed
}

11/18/2024 Andargie Mekonnen 35


Decision and Repetition statement
[Link]
//Java For-each loop example which prints the
//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
[Link](i);
}
}
}
11/18/2024 Andargie Mekonnen 36
Decision and Repetition statement
Java Labeled For Loop
We can have a name of each Java for loop. To do so, we use label before the for loop. It is
useful while using the nested for loop as we can break/continue specific for loop.
Note: The break and continue keywords breaks or continues the innermost for loop
respectively.
Syntax:
labelname:
for(initialization; condition; increment/decrement){
//code to be executed
}

11/18/2024 Andargie Mekonnen 37


Decision and Repetition statement
Example: for(int i=1;i<=3;i++){
[Link] bb:
//A Java program to demonstrate the use of for(int j=1;j<=3;j++){
labeled for loop if(i==2&&j==2){
public class LabeledForExample { break aa;
public static void main(String[] args) { }
//Using Label for outer and for loop [Link](i+" "+j);
aa: }
}
}
}

11/18/2024 Andargie Mekonnen 38


Decision and Repetition statement
if you use break bb;, it will break inner loop only which is the default behaviour of any
loop.
[Link]
public class LabeledForExample2 {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb; }
[Link](i+" "+j); } } } }

11/18/2024 Andargie Mekonnen 39


Decision and Repetition statement
Java Infinitive for Loop
If you use two semicolons ;; in the for loop, it will be infinitive for loop.
Syntax:
for(;;){
//code to be executed
}

11/18/2024 Andargie Mekonnen 40


Decision and Repetition statement
[Link]
//Java program to demonstrate the use of infinite for loop
//which prints an statement
public class ForExample {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
[Link]("infinitive loop");
}
}
}

11/18/2024 Andargie Mekonnen 41


Decision and Repetition statement
Java While Loop
The Java while loop is used to iterate a part of the program repeatedly until
the specified Boolean condition is true. As soon as the Boolean condition
becomes false, the loop automatically stops.
The while loop is considered as a repeating if statement. If the number of
iteration is not fixed, it is recommended to use the while loop.
Syntax:
while (condition){
//code to be executed
I ncrement / decrement statement
}

11/18/2024 Andargie Mekonnen 42


Decision and Repetition statement
Example:
[Link]
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
[Link](i);
i++;
}
}
}

11/18/2024 Andargie Mekonnen 43


Decision and Repetition statement
Java Infinitive While Loop
If you pass true in the while loop, it will be infinitive while loop.
Syntax:
while(true){
//code to be executed
}

11/18/2024 Andargie Mekonnen 44


Decision and Repetition statement
Example:
[Link]
public class WhileExample2 {
public static void main(String[] args) {
// setting the infinite while loop by passing true to the conditio
while(true){
[Link]("infinitive while loop");
}
}
}

11/18/2024 Andargie Mekonnen 45


Decision and Repetition statement
Java do-while Loop
The Java do-while loop is used to iterate a part of the program repeatedly, until the
specified condition is true. If the number of iteration is not fixed and you must have to
execute the loop at least once, it is recommended to use a do-while loop.
Java do-while loop is called an exit control loop. Therefore, unlike while loop and for
loop, the do-while check the condition at the end of loop body. The Java do-while loop is
executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed / loop body
//update statement
}while (condition);

11/18/2024 Andargie Mekonnen 46


Decision and Repetition statement
Example:
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
[Link](i);
i++;
}while(i<=10);
}
}

11/18/2024 Andargie Mekonnen 47


Decision and Repetition statement
Java Infinitive do-while Loop
If you pass true in the do-while loop, it will be infinitive do-while loop.
Syntax:
do{
//code to be executed
}while(true);

11/18/2024 Andargie Mekonnen 48


Decision and Repetition statement
Example:
[Link]
public class DoWhileExample2 {
public static void main(String[] args) {
do{
[Link]("infinitive do while loop");
}while(true);
}
}

11/18/2024 Andargie Mekonnen 49


Decision and Repetition statement
Java Break Statement
When a break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.
The Java break statement is used to break loop or switch statement. It breaks
the current flow of the program at specified condition. In case of inner loop,
it breaks only inner loop.
We can use Java break statement in all types of loops such as for loop, while
loop and do-while loop.
Syntax:
jump-statement;
break;
11/18/2024 Andargie Mekonnen 50
Decision and Repetition statement
Example:
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
[Link](i);
}
}
}

11/18/2024 Andargie Mekonnen 51


Decision and Repetition statement
Java Continue Statement
The continue statement is used in loop control structure when you need to jump to the
next iteration of the loop immediately. It can be used with for loop or while loop.
The Java continue statement is used to continue the loop. It continues the current flow of
the program and skips the remaining code at the specified condition. In case of an inner
loop, it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and
do-while loop.
Syntax:
jump-statement;
continue;

11/18/2024 Andargie Mekonnen 52


Decision and Repetition statement
Example:
public class ContinueExample {
public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest statement
}
[Link](i);
}
}
}

11/18/2024 Andargie Mekonnen 53


Exception Handling
In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException,
etc.

The core advantage of exception handling is to maintain the normal flow


of the application. An exception normally disrupts the normal flow of the
application; that is why we need to handle exceptions.

11/18/2024 Andargie Mekonnen 54


Exception Handling
Suppose there are 10 statements in a Java program and an exception occurs at statement
5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
However, when we perform exception handling, the rest of the statements will be
executed. That is why we use exception handling in Java.
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
11/18/2024 Andargie Mekonnen 55
Exception Handling
The [Link] class is the root class of Java Exception hierarchy inherited by
two subclasses: Exception and Error. The hierarchy of Java Exception classes is given
below:

11/18/2024 Andargie Mekonnen 56


Types of Java Exceptions
according to Oracle, there are three types of exceptions namely:
Checked Exception
Unchecked Exception
Error

11/18/2024 Andargie Mekonnen 57


Types of Java Exceptions
 Checked Exception: The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions. For example,
IOException, SQLException, etc. Checked exceptions are checked at compile-time.

Unchecked Exception: The classes that inherit the RuntimeException are known as
unchecked exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.

Error: is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.
11/18/2024 Andargie Mekonnen 58
Java Exception Keywords
Keyword Description
try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must be
followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.


throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always
used with method signature.
11/18/2024 Andargie Mekonnen 59
Java Exception Keywords
Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception.
[Link]
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){[Link](e);}
//rest code of the program
[Link]("rest of the code...");
}
}

11/18/2024 Andargie Mekonnen 60


Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as
follows:

 A scenario where ArithmeticException occurs :If we divide any number by zero, there
occurs an ArithmeticException.

int a=50/0;//ArithmeticException

A scenario where NullPointerException occurs :If we have a null value in any variable,
performing any operation on the variable throws a NullPointerException.

11/18/2024 Andargie Mekonnen 61


Common Scenarios of Java Exceptions
 A scenario where NumberFormatException occurs: If the formatting of any variable or
number is mismatched, it may result into NumberFormatException. Suppose we have
a string variable that has characters; converting this variable into digit will cause
NumberFormatException.

String s="abc";

int i=[Link](s);//NumberFormatException

 A scenario where ArrayIndexOutOfBoundsException occurs When an array exceeds to it's


size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to occur
ArrayIndexOutOfBoundsException. Consider the following statements.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
11/18/2024 Andargie Mekonnen 62
Java try-catch block
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
If an exception occurs at the particular statement in the try block, the rest of the block
code will not execute. So, it is recommended not to keep the code in try block that will not
throw an exception.
Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}

11/18/2024 Andargie Mekonnen 63


Java try-catch block
Syntax of try-finally block
try{
//code that may throw an exception
}finally{}
Java catch block
Java catch block is used to handle the Exception by declaring the type of
exception within the parameter.
The declared exception must be the parent class exception ( i.e., Exception)
or the generated exception type. However, the good approach is to declare
the generated type of exception.
The catch block must be used after the try block only. You can use multiple
catch block with a single try block.
11/18/2024 Andargie Mekonnen 64
Java try-catch block
Example 2
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code");
} }
11/18/2024 Andargie Mekonnen 65
Java try-catch block
Example in this example, we also kept // if exception occurs, the remaining state
the code in a try block that will not throw ment will
an exception. [Link]("rest of the code");
public class TryCatchExample3 { }
public static void main(String[] args) { // handling the exception
try catch(ArithmeticException e)
{ {
int data=50/0; //may throw exception [Link](e);
}

}
}
11/18/2024 Andargie Mekonnen 66
Exception Handling
Here, we handle the exception using the // handling the exception by using Exception
parent class exception. class
Example: catch(Exception e)
public class TryCatchExample4 { {
[Link](e);
public static void main(String[] args) { }
try [Link]("rest of the code");
{ }
int data=50/0; //may throw exception
}
}

11/18/2024 Andargie Mekonnen 67


Exception Handling
Example :
public class TryCatchExample5 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
[Link]("Can't divided by zero"); } } }

11/18/2024 Andargie Mekonnen 68


Exception Handling
Example : along with try block, we also enclose exception code in a catch block.
public class TryCatchExample7 {
public static void main(String[] args) {
try
{
int data1=50/0; //may throw exception
}
catch(Exception e)
{
// generating the exception in catch block
int data2=50/0; //may throw exception
}
[Link]("rest of the code");
} }
11/18/2024 Andargie Mekonnen 69
Exception Handling
Example : we can handle the generated }
exception (Arithmetic Exception) with a
// try to handle the ArithmeticException using ArrayIn
different type of exception class
(ArrayIndexOutOfBoundsException). catch(ArrayIndexOutOfBoundsException e)

public class TryCatchExample8 { {

public static void main(String[] args) { [Link](e);

try }

{ [Link]("rest of the code");

int data=50/0; //may throw exception }

}
11/18/2024 Andargie Mekonnen 70
Exception Handling
Example:Let's see an example to handle another unchecked exception.
public class TryCatchExample9 {
public static void main(String[] args) {
try {
int arr[]= {1,3,5,7};
[Link](arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("rest of the code");
} }
11/18/2024 Andargie Mekonnen 71
Exception Handling
Example:Let's see an example to handle [Link]("saved");
checked exception. }
import [Link];
// providing the checked exception handler
import [Link];
catch (FileNotFoundException e) {
public class TryCatchExample10 {
[Link](e);
public static void main(String[] args) {
}
PrintWriter pw;
[Link]("File saved successfully"); }
try {
pw = new PrintWriter("[Link]"); //may throw except
ion }

11/18/2024 Andargie Mekonnen 72


Exception Handling
Java Catch Multiple Exceptions

Java Multi-catch block


A try block can be followed by one or more catch blocks. Each catch block must contain
a different exception handler. So, if you have to perform different tasks at the occurrence
of different exceptions, use java multi-catch block.

At a time only one exception occurs and at a time only one catch block is executed.

All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

11/18/2024 Andargie Mekonnen 73


Exception Handling
Flowchart of Multi-catch Block

11/18/2024 Andargie Mekonnen 74


Exception Handling
Example: Let's see a simple example of catch(ArrayIndexOutOfBoundsException e)
java multi-catch block.
public class MultipleCatchBlock1 { {
public static void main(String[] args) { [Link]("ArrayIndexOutOfBound
s Exceptio”);
try{
}
int a[]=new int[5];
catch(Exception e)
a[5]=30/0;
{
}
[Link]("Parent Exception occurs");
catch(ArithmeticException e) }
{ [Link]("rest of the code");
[Link]("Arithmetic Exceptio }
n occurs"); }
}
11/18/2024 Andargie Mekonnen 75
Exception Handling
Java Nested try block

In Java, using a try block inside another try block is permitted. It is called as nested try block.
Every statement that we enter a statement in try block, context of that exception is pushed onto the
stack.

For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while
the outer try block can handle the ArithemeticException (division by zero).

Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.

11/18/2024 Andargie Mekonnen 76


Exception Handling
 Syntax: catch(Exception e2)
//main try block {
try
//exception message
{
statement 1; }
statement 2; }
//try catch block within another try block catch(Exception e1)
try {
{ //exception message
statement 3;
}
statement 4;
//try catch block within nested try block }
try //catch block of parent (outer) try block
{ catch(Exception e3)
statement 5; {
statement 6;
//exception message
}
}
11/18/2024 Andargie Mekonnen
.... 77
Exception Handling
Example //assigning the value out of array bounds
public class NestedTryBlock{ a[5]=4;
public static void main(String args[]){ }
//outer try block //catch block of inner try block 2
try{ catch(ArrayIndexOutOfBoundsException e)
//inner try block 1
{
try{
[Link](e);
[Link]("going to divide by 0");
}
int b =39/0;
[Link]("other statement");
}
//catch block of inner try block 1 }
catch(ArithmeticException e) //catch block of outer try block
{ catch(Exception e)
[Link](e); {
} [Link]("handled the exception (outer c
atch)");
//inner try block 2
try{ }
int a[]=new int[5]; [Link]("normal flow.."); } }
11/18/2024 Andargie Mekonnen 78
Exception Handling
Java finally block

Java finally block is a block used to execute important code such as closing the
connection, etc.

Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception
occurs or not.

The finally block follows the try-catch block.

11/18/2024 Andargie Mekonnen 79


Exception Handling
Flowchart of finally block

11/18/2024 Andargie Mekonnen 80


Exception Handling
Note: If you don't handle the exception, before terminating the program, JVM executes
finally block (if any).

finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.

The important statements to be printed can be placed in the finally block.

11/18/2024 Andargie Mekonnen 81


Exception Handling
Case 1: When an exception does not catch(NullPointerException e){
occur
Let's see the below example where the [Link](e);
Java program does not throw any }
exception, and the finally block is
executed after the try block. //executed regardless of exception occu
[Link] rred or not
class TestFinallyBlock { finally {
public static void main(String args[]){
[Link]("finally block is al
try{ ways executed");
//below code do not throw any exception
int data=25/5; }
[Link](data); [Link]("rest of phe code..."
} );
//catch won't be executed }
}
11/18/2024 Andargie Mekonnen 82
Exception Handling
Case 2: When an exception occurr but not catch(NullPointerException e){
handled by the catch block
[Link](e);
public class TestFinallyBlock1{
}
public static void main(String args[]){
try {
[Link]("Inside the try block") //executes regardless of exception occure
; d or not
//below code throws divide by zero excep finally {
tion [Link]("finally block is alw
int data=25/0; ays executed");
[Link](data); }
}
//cannot handle Arithmetic type exception [Link]("rest of the code...");
//can only accept Null Pointer type exception }
}
11/18/2024 Andargie Mekonnen 83
Exception Handling
Case 3: When an exception occurs and is
handled by the catch block //handles the Arithmetic Exception / Divide b
Example: y zero exception
[Link] catch(ArithmeticException e){
public class TestFinallyBlock2{ [Link]("Exception handled");
public static void main(String args[]){ [Link](e);
try { }
[Link]("Inside try block"); //executes regardless of exception occured or
//below code throws divide by zero excepti not
on finally {
int data=25/0; [Link]("finally block is always
[Link](data); executed");
} }
[Link]("rest of the code...");
}
}
11/18/2024 Andargie Mekonnen 84
Exception Handling
Rule: For each try block there can be zero or more catch blocks, but only
one finally block.

Note: The finally block will not be executed if the program exits (either by
calling [Link]() or by causing a fatal error that causes the process to
abort).

11/18/2024 Andargie Mekonnen 85


Exception Handling
Java throw Exception

In Java, exceptions allows us to write good quality codes where the errors are checked at
the compile time instead of runtime and we can create custom exceptions making the code
recovery and debugging easier.

The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has some message
with it that provides the error description. These exceptions may be related to user inputs,
server, etc.

11/18/2024 Andargie Mekonnen 86


Exception Handling
We can throw either checked or unchecked exceptions in Java by throw keyword. It is
mainly used to throw a custom exception.

We can also define our own set of conditions and throw an exception explicitly using
throw keyword. For example, we can throw ArithmeticException if we divide a number
by another number. Here, we just need to set the condition and throw exception using
throw keyword.

The syntax of the Java throw keyword is given below.

throw new exception_class("error message");

Exxample : throw new IOException("sorry device error");


11/18/2024 Andargie Mekonnen 87
Exception Handling
Where the Instance must be of type Throwable or subclass of Throwable.

For example, Exception is the sub class of Throwable and the user-defined exceptions
usually extend the Exception class.

Example 1: Throwing Unchecked Exception


public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote

11/18/2024 Andargie Mekonnen 88


Exception Handling
throw new ArithmeticException("Person is not eligible to vote");
}
else {
[Link]("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
[Link]("rest of the code...");
}
}

11/18/2024 Andargie Mekonnen 89


Exception Handling
The above code throw an unchecked exception. Similarly, we can also throw unchecked
and user defined exceptions.

Note: If we throw unchecked exception from a method, it is must to handle the exception
or declare in throws clause.

If we throw a checked exception using throw keyword, it is must to handle the exception
using catch block or the method must declare it using throws declaration.

11/18/2024 Andargie Mekonnen 90


Exception Handling
Example 2: Throwing Checked Exception //main method
import [Link].*; public static void main(String args[]){
public class TestThrow2 { try
//function to check if person is eligible to v {
ote or not
method();
public static void method() throws FileNo
tFoundException { }
FileReader file = new FileReader("C:\\U catch (FileNotFoundException e)
sers\\Anurati\\Desktop\\[Link]"); {
BufferedReader fileInput = new Buffere [Link]();
dReader(file);
}
throw new FileNotFoundException();
[Link]("rest of the code...");
}
}
}
11/18/2024 Andargie Mekonnen 91
Exception Handling
Example 3: Throwing User-defined Exception {
exception is everything else under the Throwable public static void main(String args[])
[Link] {
// class represents user-defined exception try
class UserDefinedException extends Exception {
{ // throw an object of user defined exception
public UserDefinedException(String str) throw new UserDefinedException("This is user
{ -defined exception");
// Calling constructor of parent Exception }
super(str); catch (UserDefinedException ude)
} {
} [Link]("Caught the exception");
// Class that uses above MyException // Print the message from MyException object
public class TestThrow3
11/18/2024 Andargie Mekonnen [Link]([Link]()); }92 } }
Exception Handling
Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information to the programmer that
there may occur an exception. So, it is better for the programmer to provide the exception handling code so
that the normal flow of the program can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers' fault that he is not checking the code before it
being used.

Syntax of Java throws

return_type method_name() throws exception_class_name{

//method code

11/18/2024 Andargie Mekonnen 93


Exception Handling
Which exception should be declared?

Ans: Checked exception only, because:

unchecked exception: under our control so we can correct our code.

error: beyond our control. For example, we are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.
11/18/2024 Andargie Mekonnen 94
Exception Handling
Java throws Example try{
Let's see the example of Java throws clause
which describes that checked exceptions n();
can be propagated by throws keyword. }catch(Exception e){[Link]
[Link] ("exception handled");}
import [Link];
class Testthrows1{
}
void m()throws IOException{ public static void main(String args[]){
throw new IOException("device error"); Testthrows1 obj=new Testthrows1();
//checked exception
} obj.p();
void n()throws IOException{ [Link]("normal flow...");
m(); }
}
}
void p(){
11/18/2024 Andargie Mekonnen 95
Exception Handling
Rule: If we are calling a method that declares an exception, we must either caught or
declare the exception.

There are two cases:

Case 1: We have caught the exception i.e. we have handled the exception using try/catch
block.

Case 2: We have declared the exception i.e. specified throws keyword with the method.

11/18/2024 Andargie Mekonnen 96


Exception Handling
Handle Exception Using try-catch block
import [Link].*; try{
class M{ M m=new M();
void method()throws IOException{ [Link]();
throw new IOException("device error"); }catch(Exception e){[Link]("
} exception handled");}
} [Link]("normal flow...");
public class Testthrows2{ }
public static void main(String args[]){ }

11/18/2024 Andargie Mekonnen 97


11/18/2024 Andargie Mekonnen 98

You might also like