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

Java First Unit

Java is a programming language and platform developed by Sun Microsystems. It is a high-level, robust, object-oriented and secure language. The Java Virtual Machine executes Java bytecode, allowing Java programs to run on any platform. Key features include being platform-independent, object-oriented, simple, robust, secure, distributed, multithreaded and portable.

Uploaded by

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

Java First Unit

Java is a programming language and platform developed by Sun Microsystems. It is a high-level, robust, object-oriented and secure language. The Java Virtual Machine executes Java bytecode, allowing Java programs to run on any platform. Key features include being platform-independent, object-oriented, simple, robust, secure, distributed, multithreaded and portable.

Uploaded by

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

Unit I

Java is a programming language and a platform. Java is a high level, robust, object-oriented and
secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak
was already a registered company, so James Gosling and his team changed the name from Oak
to Java.
Platform: Any hardware or software environment in which a program runs, is known as a
platform. Since Java has a runtime environment (JRE) and API, it is called a platform.

Primary/Main Features of Java

Platform Independent: Compiler converts source code to bytecode and then the JVM executes
the bytecode generated by the compiler. This bytecode can run on any platform be it Windows,
Linux, or macOS which means if we compile a program on Windows, then we can run it on
Linux and vice versa. Each operating system has a different JVM, but the output produced by
all the OS is the same after the execution of the bytecode. That is why we call java a platform-
independent language.
Object-Oriented Programming Language: Organizing the program in the terms of a
collection of objects is a way of object-oriented programming, each of which represents an
instance of the class.
The four main concepts of Object-Oriented programming are:
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism
Simple: Java is one of the simple languages as it does not have complex features like pointers,
operator overloading, multiple inheritances, and Explicit memory allocation.
Robust: Java language is robust which means reliable. It is developed in such a way that it
puts a lot of effort into checking errors as early as possible,that is why the java compiler is able
to detect even those errors that are not easy to detect by another programming language. The
main features of java that make it robust are garbage collection, Exception Handling, and
memory allocation.
Secure: In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it shows
ArrayIndexOutOfBound Exception if we try to do so. That’s why several security flaws like
stack corruption or buffer overflow are impossible to exploit in Java. Also, java programs run in
an environment that is independent of the os(operating system) environment which makes java
programs more secure.
Distributed: We can create distributed applications using the java programming language.
Remote Method Invocation and Enterprise Java Beans are used for creating distributed
applications in java. The java programs can be easily distributed on one or more systems that
are connected to each other through an internet connection.
Multithreading: Java supports multithreading. It is a Java feature that allows concurrent
execution of two or more parts of a program for maximum utilization of the CPU.
Portable: As we know, java code written on one machine can be run on another machine. The
platform-independent feature of java in which its platform- independent bytecode can be taken
to any platform for execution makes java portable.
High Performance: Java architecture is defined in such a way that it reduces overhead during
the runtime and at sometimes java uses Just In Time (JIT) compiler where the compiler
compiles code on-demand basics where it only compiles those methods that are called making
applications to execute faster.

Write Once Run Anywhere: As discussed above java application generates a ‘.class’ file that
corresponds to our applications (program) but contains code in binary format. It provides ease t
architecture-neutral ease as bytecode is not dependent on any machine architecture. It is the
primary reason java is used in the enterprising IT industry globally worldwide.

Power of compilation and interpretation: Most languages are designed with the purpose of
either they are compiled language or they are interpreted language. But java integrates arising
enormous power as Java compiler compiles the source code to bytecode and JVM executes this
bytecode to machine OS-dependent executable code.

Java Terminology

Java Virtual Machine(JVM): This is generally referred to as JVM. There are three execution
phases of a program. They are written, compile and run the program.
Writing a program is done by a java programmer.
The compilation is done by the JAVAC compiler which is a primary Java compiler included in
the Java development kit (JDK). It takes the Java program as input and generates bytecode as
output.
In the Running phase of a program, JVM executes the bytecode generated by the compiler.
JVM Architecture

2. Bytecode in the Development Process: As discussed, the Javac compiler of JDK compiles
the java source code into bytecode so that it can be executed by JVM. It is saved as .class file by
the compiler. To view the bytecode, a disassembler like javap can be used.
3. Java Development Kit(JDK): While we were using the term JDK when we learn about
bytecode and JVM. So, as the name suggests, it is a complete Java development kit that
includes everything including compiler, Java Runtime Environment (JRE), java debuggers, java
docs, etc. For the program to execute in java, we need to install JDK on our computer in order to
create, compile and run the java program.
4. Java Runtime Environment (JRE): JDK includes JRE. JRE installation on our computers
allows the java program to run, however, we cannot compile it. JRE includes a browser, JVM,
applet support, and plugins. For running the java program, a computer needs JRE.
5. Garbage Collector: In Java, programmers can’t delete the objects. To delete or recollect that
memory JVM has a program called Garbage Collector. Garbage Collectors can recollect the
objects that are not referenced. So Java makes the life of a programmer easy by handling
memory management. However, programmers should be careful about their code whether they
are using objects that have been used for a long time. Because Garbage cannot recover the
memory of objects being referenced.
6. ClassPath: The classpath is the file path where the java runtime and Java compiler look for
.class files to load. By default, JDK provides many libraries. If you want to include external
libraries they should be added to the classpath.
Java Data Types
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: such as boolean, char, int, short, byte, long, float, and double
Non-Primitive Data Type or Object Data type: such as String, Array, etc.

Primitive Data Types in Java


Primitive data are only single values and have no special capabilities. There are 8 primitive
data types.
Type Description Default Siz e Example Range of values
Literals
boolean true or false false 1 true, false true, false
bit
byte twos- 0 8 (none) -128 to 127
complement bits
integer
char Unicode \u0000 16 ‘a’, ‘\u0041’, characters representation of
character bits ‘\101’, ‘\\’, ‘\’, ASCII values
‘\n’, ‘?’ 0 to 255

short twos- 0 16 (none) -32,768 to 32,767


complement bits
integer
int twos- 0 32 -2,-1,0,1,2 -2,147,483,648
complement bits to 2,147,483,647
intger

long twos- 0 64 -2L,- - 9,223,372,036,854,775,80


complement bits 1L,0L,1L,2L 8
integer to 9,223,372,036,854,775,80
7

float IEEE 754 0.0 32 1.23e100f , - upto 7 decimal digits


floating point bits 1.23e-100f ,
.3f ,3.14F
double IEEE 754 0.0 64 1.23456e300 d upto 16 decimal digits
floating point bits , -123456e-
300d , 1e1d
// Java Program to Demonstrate Primitive Data Type

// Class
class DataTypes {

// Main driver method


public static void main(String args[])
{

// Creating and initializing custom character char a = 'G';

// Integer data type is generally


// used for numeric values int i = 89;

// use byte and short


// if memory is a constraint byte b = 4;

// this will give error as number is


// larger than byte range
// byte b1 = 7888888955;

short s = 56;

// this will give error as number is


// larger than short range
// short s1 = 87878787878;

// by default fraction value


// is double in java double d = 4.355453532;
// for float use 'f' as suffix as standard float f = 4.7333434f;

// need to hold big range of numbers then we need


// this data type long l = 12121;

System.out.println("char: " + a); System.out.println("integer: " + i); System.out.println("byte: "


+ b); System.out.println("short: " + s); System.out.println("float: " + f);
System.out.println("double: " + d); System.out.println("long: " + l);
}
}
Java Control Statements
Java provides three types of control flow statements.

Decision Making statements


• if statements
• switch statement
Loop statements
• do while loop
• while loop
• for loop
• for-each loop

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.
 if statement
 if-else statement
 if-else-if ladder
 nested if statement

 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
}

EXAMPLE
//Java Program to demonstate 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){
System.out.print("Age is greater than 18");
}
}
}
 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
}
Example: Program to check a given year is leap or not.

//A year is leap, if it is divisible by 4 and 400. But, not by 100.

public class LeapYearExample {


public static void main(String[] args) {
int year=2023;
if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){ System.out.println("LEAP
YEAR");
}
else{
System.out.println("COMMON YEAR");
}
}
}
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
}
Example:

//Java Program to demonstrate the use of If else-if ladder.


//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;

if(marks<50){ System.out.println("fail");
}
else if(marks>=50 && marks<60){ System.out.println("D grade");
}
else if(marks>=60 && marks<70){ System.out.println("C grade");
}
else if(marks>=70 && marks<80){ System.out.println("B grade");
}
else if(marks>=80 && marks<90){ System.out.println("A grade");
}else if(marks>=90 && marks<100){ System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
 Java Nested if statement
The 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
}
}

Example:

//Java Program to demonstrate the use of Nested If Statement.


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){
System.out.println("You are eligible to donate blood");
}
}
}}

 Java Switch Statement


The Java switch statement executes one statement from multiple conditions. It is like if-else-
if ladder 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;
}
Example: SwitchExample.java
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");

}
}
}

 Java Switch Statement is fall-through


The Java switch statement is fall-through. It means it executes all statements after the first
match if a break statement is not present.
Example: SwitchExample2.java
//Java Switch Example where we are omitting the
//break statement
public class SwitchExample2 {
public static void main(String[] args) {
int number=20;
//switch expression with int value
switch(number){
//switch cases without break statements
case 10: System.out.println("10");
case 20: System.out.println("20");
case 30: System.out.println("30");
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Loops in Java
The Java for loop is used to iterate a part of the program several times. If the number of iteration
is fixed, it is recommended to use for loop.
There are three types of for loops in Java.
for Loop
A for loop is a repetition control structure that allows us to efficiently write a loop that needs to
be executed a specific number of times.

Syntax:

for(initialization; condition; increment/decrement){


//statement or code to be executed
}
Pyramid Example 1:Program to print Pyramid.
PyramidExample.java public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){ System.out.print("* ");
}

System.out.println();//new line
}
}
}
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
Increment / decrement statement
}

Example While Loop: Program to print the table of 2.

public class WhileExample {


public static void main(String[] args) { int num=2; //print table of number 2
int i=1; while(i<=10){
System.out.println(i*num); i++;
}
}
}
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);
Example:
In the below example, we print integer values from 1 to 10. Unlike the for loop, we separately
need to initialize and increment the variable used in the condition (here, i). Otherwise, the loop
will execute infinitely.
DoWhileExample.java public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i); i++;
}while(i<=10);
}
}
Java Arrays
Java array is an object which contains elements of a similar data type. Additionally, The elements
of an array are stored in a contiguous memory location. It is a data structure where we store
similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class,
and implements the Serializable as well as Cloneable interfaces. We can store primitive values
or objects in an array in Java.

Types of Array in java Single Dimensional Array in Java


Syntax to Declare an Array in Java

dataType[] arr; (or)


dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java

arrayRefVar=new datatype[size];
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]);
}}
Multidimensional Array in Java
Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or)


dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java int[][] arr=new int[3][3];//3 row and 3
column
Example of Multidimensional Java Array
//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array for(int i=0;i<3;i++){ for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}

Vector Class in Java


The Vector class implements a growable array of objects. Vectors fall in legacy classes, but
now it is fully compatible with collections. It is found
in java.util package and implement the List interface, so we can use all the methods of the List
interface as shown below as follows:
Vector implements a dynamic array which means it can grow or shrink as required. Like an
array, it contains components that can be accessed using an integer index.
They are very similar to ArrayList, but Vector is synchronized and has some legacy methods
that the collection framework does not contain.
It also maintains an insertion order like an ArrayList. Still, it is rarely used in a non-thread
environment as it is synchronized, and due to this, it gives a poor performance in adding,
searching, deleting, and updating its elements.
The Iterators returned by the Vector class are fail-fast. In the case of concurrent modification, it
fails and throws
the ConcurrentModificationException.

Syntax:

public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess,


Cloneable, Serializable
Here, E is the type of element.
Example
// Java Program to Demonstrate Working of Vector
// Via Creating and Using It

// Importing required classes import java.io.*;


import java.util.*;

// Main class class Vector {


// Main driver method
public static void main(String[] args)
{
// Size of the Vector int n = 5;
// Declaring the Vector with
// initial size n
Vector<Integer> v = new Vector<Integer>(n);

// Appending new elements at


// the end of the vector for (int i = 1; i <= n; i++)
v.add(i);

// Printing elements System.out.println(v);


// Remove element at index 3 v.remove(3);
// Displaying the vector
// after deletion System.out.println(v);
// iterating over vector elements
// using for loop
for (int i = 0; i < v.size(); i++)

// Printing elements one by one System.out.print(v.get(i) + " ");


}
}

Java Classes
A class in Java is a set of objects which shares common characteristics/ behavior and common
properties/ attributes. It is a user-defined blueprint or prototype from which objects are created.
For example, Student is a class while a particular student named Ravi is an object.
Properties of Java Classes
 Class is not a real-world entity. It is just a template or blueprint or prototype from which
objects are created.
 Class does not occupy memory.
 Class is a group of variables of different data types and a group of methods.
A Class in Java can contain:
• Data member
• Method
• Constructor
• Nested Class
• Interface

Class Declaration in Java


access_modifier class <class_name>
{
data member; method; constructor; nested class; interface;
}
Components of Java Classes
In general, class declarations can include these components, in order:
Modifiers: A class can be public or has default access (Refer this for details).
Class keyword: class keyword is used to create a class.
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, { }.

Java Objects
An object in Java is a basic unit of Object-Oriented Programming and represents real-life
entities. Objects are the instances of a class that are created to use the attributes and methods of
a class. A typical Java program creates many objects, which as you know, interact by invoking
methods. An object consists of :
State: It is represented by 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
with other objects.
Identity: It gives a unique name to an object and enables one object to interact with other
objects.

Example to demonstrate class and object


//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Inheritance

Inheritance can be defined as the process where one class acquires the properties (methods and
fields) of another. With the use of inheritance the information is made manageable in a
hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.

class Subclass-name extends Superclass-name


{
//methods and fields
}
Example: Sample Program to demonstrate inheritance
class Calculation { int z;

public void addition(int x, int y) { z = x + y;


System.out.println("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y) { z = x - y;


System.out.println("The difference between the given numbers:"+z);
}
}

public class My_Calculation extends Calculation { public void multiplication(int x, int y) {


z = x * y;
System.out.println("The product of the given numbers:"+z);

public static void main(String args[]) { int a = 20, b = 10;


My_Calculation demo = new My_Calculation(); demo.addition(a, b);
demo.Subtraction(a, b); demo.multiplication(a, b);
}
}
Types of Inheritance

Packages
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations ) providing access protection and namespace management.

Types of packages:
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the
commonly used built-in packages are:
java.lang: Contains language support classes(e.g classed which defines primitive data types,
math operations). This package is automatically imported.
java.io: Contains classed for supporting input / output operations.
java.util: Contains utility classes which implement data structures like Linked List, Dictionary
and support ; for Date / Time operations.
java.applet: Contains classes for creating Applets.
java.awt: Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).
java.net: Contain classes for supporting networking operations.

User-defined packages
These are the packages that are defined by the user. First we create a
directory myPackage (name should be same as the name of the package). Then create the
MyClass inside the directory with the first statement being
the package names.
// Name of the package must be same as the directory
// under which this file is saved
package mypack;
public class MyPackageClass
{
public void p()
{
System.out.println("This is my package!");
}

public static void main(String[] args) {

MyPackageClass pt=new MyPackageClass();


pt.p();
System.out.println("Program terminated");
}
}

To compile the Java programs with package statements, you have to use -d option as shown
below.
javac -d Destination_folder file_name.java
Example to import the user defined package
import mypack.MyPackageClass;
public class app2 {
public static void main(String[] args) {
System.out.println("This statement is for app2");
MyPackageClass m=new MyPackageClass();
m.p();
}

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors
so that the normal flow of the application can be maintained.
What is Exception in Java?
Dictionary Meaning: Exception is an abnormal condition.
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 in Java is one of the effective means to handle runtime errors so that the
regular flow of the application can be preserved. Java Exception Handling is a mechanism to
handle runtime errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Major reasons why an exception Occurs
 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out-of-disk memory)
 Code errors
 Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer, and we should not try to handle errors.

Difference between Error and Exception

Error: An Error indicates a serious problem that a reasonable application should not try to
catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
Exception Hierarchy
Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java also
allows users to define their own exceptions.

Exceptions can be categorized in two ways:


 Built-in Exceptions
Checked Exception
Unchecked Exception
 User-Defined Exceptions

 Built-in Exceptions
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions
are suitable to explain certain error situations.
1. Checked Exceptions: Checked exceptions are called compile-time exceptions because
these exceptions are checked at compile-time by the compiler.
2. Unchecked Exceptions: The unchecked exceptions are just opposite to the checked
exceptions. The compiler will not check these exceptions at compile time. In simple
words, if a program throws an unchecked exception, and even if we didn’t handle or
declare it, the program would not give a compilation error.
 User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such
cases, users can also create exceptions, which are called ‘user- defined Exceptions’.

The advantages of Exception Handling in Java are as follows:


 Provision to Complete Program Execution
 Easy Identification of Program Code and Error-Handling Code
 Propagation of Errors
 Meaningful Error Reporting
 Identifying Error Types

Example program
public class JavaExceptionExample{ public static void main(String args[]){ try{
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);} System.out.println("rest of the code...");
}
}

Java Exception Keywords

Exception Handling in java is managed via five keywords: try, catch, throw, throws, and finally.
Here are 5 keywords that are used in handling exceptions in Java

Keyword Description

try This keyword is used to specify a block and this block must be followed by either
catch or finally. That is, we can’t use try block alone.

catch This keyword must be preceded by a try block to handle the exception and can be
followed by a final block later.

finally This keyword is used to execute the program, whether an exception is handled or
not.
throw This keyword is used to throw an exception.

throws This keyword is used to declare exceptions.


Catching Exceptions
A method catches an exception using a combination of
the try and catch keywords. A try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected code

Try {
//code that may throw an exception
}
catch(Exception_class_Name ref){}

A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If
the type of exception that occurred is listed in a catch block, the exception is passed to the catch
block much as an argument is passed into a method parameter.
Example
In following example, an array is declared with 2 elements. Then the code tries to access the 3rd
element of the array which throws an exception.
Multiple Catch Blocks
A try block can be followed by multiple catch blocks.

Try {
//code that may throw an exception
}
catch(Exception_class_Name ref1){
}catch(Exception_class_Name ref2){
} catch(Exception_class_Name ref2){}

Example Program public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5]; a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

The Finally Block


The finally block follows a try block or a catch block. A finally block of code always
executes, irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute,
no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax

Try {
//code that may throw an exception
}
catch(Exception_class_Name ref1){
}catch(Exception_class_Name ref2){
} catch(Exception_class_Name ref2){
}finally{
// This finally block always executes
}
Introduction to thread
Process and Thread two basic units of java program execution

Process: A process is a self contained execution environment and it can be seen as a program or
application

Thread: Multithreading is a Java feature that allows concurrent execution of two or more parts
of a program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.

Threads can be created by using two mechanisms :


 Extending the Thread class
 Implementing the Runnable Interface

 Thread creation by extending the Thread class


We create a class that extends the java.lang.Thread class. This class overrides the run() method
available in the Thread class. A thread begins its life inside run() method. We create an object
of our new class and call start() method to start the execution of a thread. Start() invokes the
run() method on the Thread object.

 Thread creation by implementing the Runnable Interface


We create a new class which implements java.lang.Runnable interface and override run()
method. Then we instantiate a Thread object and call start() method on this object.
Life Cycle of a Thread
A thread goes through various stages in its life cycle. For example, a thread is
born, started, runs, and then dies. A thread n Java at any point of time exists in any one of the
following states. A thread lies only in one of the shown states at any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State
1. New Thread: When a new thread is created, it is in the new state. The thread has not yet
started to run when the thread is in this state. When a thread lies in the new state, its code
is yet to be run and hasn’t started to execute.
2. Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a
thread might actually be running or it might be ready to run at any instant of time. It is the
responsibility of the thread scheduler to give the thread, time to run.
A multi-threaded program allocates a fixed amount of time to each individual thread. Each and
every thread runs for a short while and then pauses and relinquishes the CPU to another thread
so that other threads can get a chance to run. When this happens, all such threads that are ready
to run, waiting for the CPU and the currently running thread lie in a runnable state.
3. Blocked: The thread will be in blocked state when it is trying to acquire a lock but
currently the lock is acquired by the other thread. The thread will move from the blocked
state to runnable state when it acquires the lock.
4. Waiting state: The thread will be in waiting state when it calls wait() method or join()
method. It will move to the runnable state when other thread will notify or that thread
will be terminated.
5. Timed Waiting: A thread lies in a timed waiting state when it calls a method with a
time-out parameter. A thread lies in this state until the timeout is completed or until a
notification is received. For example, when a thread calls sleep or a conditional wait, it is
moved to a timed waiting state.
6. Terminated State: A thread terminates because of either of the following reasons:
Because it exits normally. This happens when the code of the thread has been entirely executed
by the program.
Because there occurred some unusual erroneous event, like a segmentation fault or an
unhandled exception.

You might also like