Advance Java Unit -1

 Unit -1 

Why Java is important for Internet 

In a network, two very broad categories of objects are transmitted between the server and your  personal computer: passive information and dynamic, active programs. For example, when you read  your e-mail, you are viewing passive data. Even when you download a program, the program's code  is still only passive data until you execute it. However, a second type of object can be transmitted to  your computer: a dynamic, self-executing program 

Java Applets and Applications 

An application is a program that runs on your computer.it is Java's ability to create applets that  makes it important.An applet is an application designed to be transmitted over the Internet and  executed by 

a Java-compatible Web browser 

Security 

Prior to Java, most users did not download executable programs frequently, and those who did  scanned them for viruses prior to execution. 

When you use a Java-compatible Web browser, you can safely download Java applets without fear  of viral infection or malicious intent. Java achieves this protection by Confining a Java program to the  Java execution environment and not allowing it access to other parts of the computer. 

Portability 

many types of computers and operating systems are connected to the Internet. For programs to be dynamically downloaded to all the various types of platforms connected to the Internet, some means of generating portable executable code is needed. 

Byte Code java’s magic for solve above to problems(security and portability): 

The output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a highly  optimized set of instructions designed to be executed by the Java run-time system, which is called  the Java Virtual Machine (JVM). That is, in its standard form, the JVM is an interpreter for  bytecode only the JVM needs to be implemented for each platform. Once the run-time package  exists for a given system, any Java program can run on it. Remember, although the details of the  JVM will differ from 

platform to platform, all interpret the same Java bytecode. 

The Java words 

Although the fundamental forces that necessitated the invention of Java are portability and security, other factors also played an important role

Simple: Java was designed to be easy for the professional programmer to learn and use effectively Object-oriented 

Robust : memory management mistakes and mishandled exceptional conditions 

Multithreaded : Java supports multithreaded programming, which allows you to write programs that  do many things simultaneously 

Architecture-neutral : there was no garantee today programs run and tomorrow also run in same  manner. Java achieved. 

• Interpreted & High performance : Java enables the creation of cross-platform programs by  compiling into an intermediate representation called Java bytecode. This code can be interpreted 

on any system that provides a Java Virtual Machine 

java was designed to perform well on very low-power CPUs. 

Distributed: Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols. 

Dynamic: Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time. 

process-oriented model : a program can be conceptually organized around its code then code is  acting on data, 

Object-oriented programming : a program can be conceptually organized around its data. 

Java Magic: Byte Code 

The means that allows Java to solve both the security and the portability problems is that the output  of a Java compiler is not executable code but it is the Bytecode. Bytecode is a highly optimized set of  instructions designed to be executed by the Java run-time system, which is called the lava Virtual  Machine (JVM). JVM is an interpreter for bytecode. The fact that a Java program is executed by JVM helps solve the major problems associated with downloading programs over the Internet.  Translating a Java program into bytecode helps makes it much easier to run a program in a wide  variety of environments. This is because only the JVM needs to be implemented for each platform. 

Once the run-time package exists for a given system, any Java program can run on it. If a Java  program is compiled to its subject code, then different versions of the same program would exist for  each type of CPU connected to the Internet. This is not a practical solution. Thus, the understanding  of bytecode is the most effective way to create strictly portable programs. Now, if a Java program is  interpreted, it also helps to make it secure. Since the execution of every Java program is under the  control of the JVM, the JVM can contain the program, and prevent it from generating side effects 

outside of the system. The use of by tee ode enables the Java run-time system to execute programs  much faster. 

Sun provides a facility called lust In Time (JIT) compiler for bytecode. It is not possible to compile an  entire Java program into executable code all at once, because Java performs various run-time checks  that can be done only at run time. JIT compiles the code 3.S and when needed. 

Java Buzzwords 

Buzzwords of Java 

The inventors of Java wanted to design a language which could offer solutions to some of the  problems encountered in modern programming. They wanted the language to be not only reliable,  portable and distributed but also simple, compact and interactive. The authors of Java have written  an influential White Paper that explains the features of java by all of the following buzzwords: 

Simple 

Object Oriented 

Platform Independent 

Distributed 

Robust 

Secure 

Architecture Neutral 

Portable

Interpreted 

High Performance 

Multithreaded 

Dynamic 

Simple 

Java is an object-oriented programming language with syntax and keywords almost identical to C++.  When developing Java, its creators took all of the good features of the existing object-oriented  programming languages such as C++, Ada, and Smalltalk, and removed most of their flaws and  peculiarities. There are a lot of aspects of the Java language that are consistent and make sense,  thereby making it easier to learn. 

If you are familiar with C++ you would know about clumsy features of C++: header files, pointer  arithmetic (or even pointer syntax), structures, unions, operator overloading, virtual base classes,  and so on. All these clumsy features are cleaned-up in java making it easier to learn. 

Object Oriented 

What is object oriented programming (OOP) language? 

Any programming language if supports Encapsulation, Abstraction, Inheritance, Polymorphism then  that language is an object oriented programming language. E.g. java, C++ 

Define OOP concepts? 

If you have just started learning java, definitely it is very hard to understand the Object oriented  programming (OOP) concepts. Once you learn java completely then you will understand these  concepts. Many java professional who are using these concepts in their daily life will fail to define  OOP (Object Oriented Programing) concepts. Below are the definitions of OOP concepts which will  surely help you when you are attending the java interviews. 

Encapsulation: It is the Process of binding the data and methods together into a single unit.  Example: Binding private variables with setter and getter methods. 

Abstraction: Showing Essential properties and methods of an object by hiding internal things is  called as Abstraction. Abstraction is possible if and only if there is encapsulation. Example: Java is an  abstraction layer over binary language. Hibernate is an abstraction layer over JDBC 

Inheritance: Inheriting the properties and methods of one class (super class) into another class (sub  class) using IS a relationship. Example: Ferrari class inherits the features of Car class. Puppy class  inherit the features of Dog class, Dog class inherit the features of Animal class 

Polymorphism: One form behaving differently in different situations is called polymorphism. Animal  class behaving differently for different objects like Dog, Cat etc... 

Platform independent

Java can run in any system line windows, Linux, mac etc. You no need to write separate program for  individual platform/OS. Program written in Windows platform can run in Linux platform. Output of  java compiler (javac.exe in windows) is a bytecode (.calss file), but not native machine code. This  bytecode is interpreted by virtual machine (not by real computer) as real computer interprets .exe  files in C/C++. Such a virtual machine is called as Java Virtual Machine (JVM). 

Translating java program into Byte code makes it much easier to run a program in wide variety of  platforms/Environments, because only JVM need to be implemented. Once bytecode is ready, we  can run it in windows, Linux, calculator, mobile, watch etc.., but one thing is all environments require  just JVM. Details of JVM differ from environment to environment. (Platform to Platform) 

Distributed 

A technology is said to be distributed if it's business objects are geographically dispersed into  different locations and still communicating one another.  

Networking capabilities of java are strong and easy to use. 

Onerous tasks like opening a socket connection are simple in Java. 

An elegant mechanism, called servlets, makes server-side processing in Java extremely  efficient. Many popular web servers support servlets. 

Robust 

Programming language is robust when it is reliable and strong. Below capabilities make java robust: 

Java has a garbage collector which will automatically clean up unused objects and memory.  No need to chase memory corruption. 

In java you do not use pointers to access strings, arrays, objects, even files. Nor do you need  to worry about memory allocation for them. 

Java has exception handling mechanism which is very useful in handling both compile and  run time errors. Without handling errors and exceptions, entire application would fail. With 

exception handling it just stops the current flows even that are when failed, but rest all flows  still runs. 

Secure 

Java team has said that they will have a “zero tolerance” for security bugs and will immediately go to  work on fixing any bugs found. Java program will be first compiled to byte code. This byte code will  then be interpreted by Java Virtual Machine (JVM). JVM makes java secure with below factors:  

JVM will not overrun the runtime stack. 

JVM will not corrupt memory outside its own process space. 

JVM will not read or write to local files when invoked through a security-conscious class  loader. 

Architecture Neutral 

The compiler generates architecture-neutral bytecode instructions which have nothing to do with  particular computer architecture. These bytecode instructions can be run by only JVM. JVM is not  same for platforms and architectures. Java will provide you different JVMs for different platforms  and architectures. So you just have to install different JVMs. A bytecode once ready can be run by  any JVM. 

A program written in 32 bit operating system can be run by JVM in 64 bit operating system. Portable 

In C/C++ data size varies from platform to platform. For example integer can be a 16-bit integer, a  32-bit integer, or any other size that the compiler vendor likes. In java has a fixed size for data that  eliminates a major porting headache. Binary data is stored and transmitted in a fixed format,  eliminating the “big endian/little endian” confusion. Strings are saved in a standard Unicode  format. Java does this by JVM. Java facilitates you to carry the Java bytecode to any platform. It  doesn't require write different program for different platforms line windows, Linux etc… 

Interpreted 

Java Virtual Machine (JVM) is the java interpreter. The interpreter can execute Java bytecodes  directly on any machine to which the interpreter has been ported. Since installing JVM is a  lightweight process, the development process can be much more rapid and exploratory. 

High Performance 

When Java was still a new language, it was criticized for being slow: Since Java bytecode was  executed by an interpreter, it seemed that Java bytecode programs could never run as quickly as  programs compiled into native machine language (that is, the actual machine language of the  computer on which the program is running). However, this problem has been largely overcome by  the use of just-in-time compilers (JIT) for executing Java bytecode.

JIT is a part of JVM. A just-in-time compiler translates Java bytecode into native machine language. It  does this while it is executing the program. Just as for a normal interpreter, the input to a just-in time compiler is a Java bytecode program, and its task is to execute that program. 

It is important to understand that it is not practical to compile an entire Java program into  executable code all at once, because Java performs various run-time checks that can be done only at  run time. Instead, a JIT compiler compiles code as it is needed, during execution. Furthermore, not  all sequences of bytecode are compiled—only those that will benefit from compilation. The  remaining code is simply interpreted. The translated parts of the program can then be executed  much more quickly than they could be interpreted. Since a given part of a program is often executed  many times as the program runs, a just-in-time compiler can significantly speed up the overall  execution time. 

Even though dynamic compilation is applied to bytecode, the portability and safety features still  apply, because the JVM is still in charge of the execution environment. 

Multithreaded 

A thread is defined as a separate path of execution inside any process. It is done to use CPU idle  time. A process consists of the memory space allocated by the operating system that can contain  one or more threads. A thread cannot exist on its own; it must be a part of a process. Whenever a  thread is created within a program it will not occupy any separate space. It will share the same  memory space of the program. It will also not consume more resources. 

Thread implementations on the major platforms differ widely, but Java makes no effort to be  platform independent in this regard. Only the code for calling multithreading remains the same  across machines; Java offloads the implementation of multithreading to the underlying operating  system or a thread library. 

Dynamic 

In a number of ways, Java is a more dynamic language than C or C++. It was designed to adapt to an  evolving environment. Libraries can freely add new methods and instance variables without any  effect on their clients. In Java, finding out run time type information is straightforward. This is an  important feature in those situations where code needs to be added to a running program 

Simple program of java 

The requirement for Java Hello World Example

For executing any Java program, the following software or application must be properly installed. o Install the JDK if you don't have installed it, download the JDK and install it. o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java o Create the Java program 

o Compile and run the Java program 

Creating Hello World Example 

Let's create the hello java program: 

1. class Simple{  

2. public static void main(String args[]){  

3. System.out.println("Hello Java");  

4. }  

5. }  

Save the above file as Simple.java. 


To compile: 

To execute: 



Output: 

Hello Java 

Super Keyword in Java 

javac Simple.java java Simple 

The super keyword in Java is a reference variable which is used to refer immediate parent class  object. 

Whenever you create the instance of subclass, an instance of parent class is created implicitly which  is referred by super reference variable. 

Usage of Java super Keyword 

1. super can be used to refer immediate parent class instance variable. 

2. super can be used to invoke immediate parent class method.

3. super() can be used to invoke immediate parent class constructor. 

1) super is used to refer immediate parent class instance variable. 

We can use super keyword to access the data member or field of parent class. It is used if parent  class and child class have same fields. 

1. class Animal{  

2. String color="white";  

3. }  

4. class Dog extends Animal{  

5. String color="black";  

6. void printColor(){  

7. System.out.println(color);//prints color of Dog class  

8. System.out.println(super.color);//prints color of Animal class  

9. }  

10. }  

11. class TestSuper1{  

12. public static void main(String args[]){  

13. Dog d=new Dog();  

14. d.printColor();  

15. }}  

Output: 

black 

white 

In the above example, Animal and Dog both classes have a common property color. If we print color  property, it will print the color of current class by default. To access the parent property, we need to  use super keyword. 

2) super can be used to invoke parent class method 

The super keyword can also be used to invoke parent class method. It should be used if subclass  contains the same method as parent class. In other words, it is used if method is overridden.

1. class Animal{ 

2. void eat(){System.out.println("eating...");}  

3. }  

4. class Dog extends Animal{  

5. void eat(){System.out.println("eating bread...");}  

6. void bark(){System.out.println("barking...");}  

7. void work(){  

8. super.eat();  

9. bark();  

10. }  

11. }  

12. class TestSuper2{  

13. public static void main(String args[]){  

14. Dog d=new Dog();  

15. d.work();  

16. }}  

Output: 

eating... 

barking... 

In the above example Animal and Dog both classes have eat() method if we call eat() method from  Dog class, it will call the eat() method of Dog class by default because priority is given to local. 

To call the parent class method, we need to use super keyword. 

3) super is used to invoke parent class constructor. 

The super keyword can also be used to invoke the parent class constructor. Let's see a simple  example: 

1. class Animal{  

2. Animal(){System.out.println("animal is created");}  

3. } 

4. class Dog extends Animal{  

5. Dog(){  

6. super();  

7. System.out.println("dog is created");  

8. }  

9. }  

10. class TestSuper3{  

11. public static void main(String args[]){  

12. Dog d=new Dog();  

13. }}  

Output: 

animal is created 

dog is created 

Note: super() is added in each class constructor automatically by compiler if there is no super() or  this(). 

As we know well that default constructor is provided by compiler automatically if there is no  constructor. But, it also adds super() as the first statement.

Dynamic method dispatch 

Dynamic method dispatch is the mechanism in which a call to an overridden method is resolved at  run time instead of compile time. This is an important concept because of how Java implements run time polymorphism. 

Java uses the principle of ‘a superclass reference variable can refer to a subclass object’ to resolve  calls to overridden methods at run time. When a superclass reference is used to call an overridden  method, Java determines which version of the method to execute based on the type of the object  being referred to at the time call. 

In other words, it is the type of object being referred to that determines which version of an  overridden method will be executed. 

Advantages of dynamic method dispatch 

1. It allows Java to support overriding of methods, which are important for run-time  polymorphism. 

2. It allows a class to define methods that will be shared by all its derived classes, while also  allowing these sub-classes to define their specific implementation of a few or all of those  methods. 

3. It allows subclasses to incorporate their own methods and define their implementation. 

Code 

Here is an example illustrating dynamic method dispatch: 

// Implementing Dynamic Method Dispatch 

class Apple  

{  

void display()  

{  

System.out.println("Inside Apple's display method");  

}  

}  

class Banana extends Apple 

{  

void display() // overriding display() 

{  

System.out.println("Inside Banana's display method");  }  

}  

class Cherry extends Apple  

{  

void display() // overriding display() 

{  

System.out.println("Inside Cherry's display method");  }  

}  

class Fruits_Dispatch  

{  

public static void main(String args[])  

{  

Apple a = new Apple(); // object of Apple 

Banana b = new Banana(); // object of Banana Cherry c = new Cherry(); // object of Cherry  

Apple ref; // taking a reference of Apple 

ref = a; // r refers to a object in Apple 

ref.display(); // calling Apple's version of display()

ref = b; // r refers to a object in Banana 

ref.display(); // calling Banana's version of display() 

ref = c; // r refers to a object in Cherry 

ref.display(); // calling Cherry's version of display() 

}  

}  

Output 

1.9s 

Inside Apple's display method 

Inside Banana's display method 

Inside Cherry's display method 

This program creates one superclass (i.e., class Apple) and two subclasses of it (i.e., Banana class and  Cherry class). Subclasses Banana and Cherry override the display() method declared in Apple. Inside  the main() method in class Fruits_Dispatch, objects of type Apple, Banana, and Cherry are declared.  A reference of type Apple, called ref, is declared. 

The program then assigns a reference to each type of object to ref and uses the reference to  invoke display(). 

The version of display() executed is determined by the type of the object being referred to at the  time of the call. 

Final class and Methods 

Final Methods 

When a method is declared with final keyword, it is called a final method. A final method cannot  be overridden. The Object class does this—a number of its methods are final. We must declare  methods with the final keyword for which we are required to follow the same implementation  throughout all the derived classes. 

Illustration: Final keyword with a method 

class A 

 final void m1()  

 { 

 System.out.println("This is a final method."); 

 } 

class B extends A  

 void m1() 

 {  

 // Compile-error! We can not override 

 System.out.println("Illegal!"); 

 } 

final classes 

When a class is declared with final keyword, it is called a final class. A final class cannot be  extended(inherited). 

There are two uses of a final class: 

Usage 1: One is definitely to prevent inheritance, as final classes cannot be extended. For example,  all Wrapper Classes like Integer, Float, etc. are final classes. We can not extend them. 

final class A 

 // methods and fields 

// The following class is illegal 

class B extends A 

{  

 // COMPILE-ERROR! Can't subclass A 

Usage 2: The other use of final with classes is to create an immutable class like the  predefined String class. One can not make a class immutable without making it final. 

Java Package 

A java package is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Here, we will have the detailed learning of creating and using user-defined packages. Advantage of Java Package 

1) Java package is used to categorize the classes and interfaces so that they can be easily  maintained. 

2) Java package provides access protection. 

3) Java package removes naming collision.

Simple example of java package 

The package keyword is used to create a package in java. 1. //save as Simple.java  

2. package mypack;  

3. public class Simple{  

4. public static void main(String args[]){  

5. System.out.println("Welcome to package");  

6. }  

7. }  

How to compile java package 

If you are not using any IDE, you need to follow the syntax given below: 1. javac -d directory javafilename  

For example

1. javac -d . Simple.java  

How to run java package program 

You need to use fully qualified name e.g. mypack.Simple etc to run the class. 

To Compile: javac -d . Simple.java 

To Run: java mypack.Simple 

Output:Welcome to package 

The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The .  represents the current folder. 

Java Access Protection 

In previous chapters, you learned about the various aspects of Java's access control mechanism and  its access modifiers. For example, you already known that access to a private member of a class is  granted only to the other members of that class. 

Packages adds another dimension to the access control. As you will see, Java provides many levels of  protection to allow fine-grained control over visibility of the variables and methods within classes,  subclasses, and packages. 

Classes and packages are means of encapsulating and containing the name space and scope of the  variables and methods. 

Packages behaves as containers for classes and other subordinate packages. 

Classes act as containers for data and code. 

Class Members Visibility 

The Java's smallest unit of abstraction is class. Because of the interplay between the classes and  packages, Java addresses the following four categories of visibility for class members : 

Subclasses in same package 

Non-subclasses in same package 

Subclasses in different packages 

Classes that are neither in same package nor in subclasses 

The three access modifiers are : 

public

private 

protected 

provides a variety of ways to produce many levels of access required by these categories. The  upcoming table sums up the interaction 

While the access control mechanism of Java may seem complicated, we can simplify it as follows. Anything declared as public can be accessed from anywhere. 

Anything declared as private can't be seen outside of its class. 

Class Member Access 

When a member doesn't have an explicit access specification, then it is visible to the subclasses as  well as to the other classes in the same package. This is the default access. And If you want to allow  an element to be seen outside your current package, but only to the classes that subclass your class  directly, then declare that element protected. 

This table applies only to the members of classes. A non-nested class has only two possible access  levels i.e., default and public

When a class is declared as public, then it is accessible by any other code. If a class has default  access, then it can only be accessed by the other code within its same package. When a class is  public, it must be only the public class declared in the file that must have the same name as the  class. 

Java Access Protection Example 

Here the upcoming example allows all the combinations of access control modifiers. This example  has two packages and five classes. 

Always remember that the classes for the two different packages need to be stored in directories  after their respective packages (in this case pkg1 and pkg2). 

The source for the first package defines the three classes i.e., Protection, Derived,  and SamePackage. The first class defines the four variables of type int in each of the legal protection  modes. The variable n declared with the default protection, the variables n_priv,  n_prot, and n_publ is private, protected, and public respectively. 

Each subsequent class in the following example will try to access the variables in an instance of this  class. The lines that will not compile due to the access restrictions are commented out. Before each  of these lines is a comment that listing the places from which this level of protection would allow  access. 

The second class named Derived, is a subclass of Protection in the same package, pkg1. This  grants Derived access to every variable in the class Protection except for n_priv, the private one.  The third class named SamePackage, is not a subclass of the class Protection, but is in the same  package and also has access to all but not n_priv

This is Protection.java file:

package pkg1; 

public class Protection 

 int n = 1; 

 private int n_priv = 2; 

 protected int n_prot = 3; 

 public int n_publ = 4; 

  

 public Protection() 

 { 

 System.out.println("base constructor"); 

 System.out.println("n = " + n); 

 System.out.println("n_priv = " + n_priv); 

 System.out.println("n_prot = " + n_prot); 

 System.out.println("n_publ = " + n_publ); 

 } 

An interface in Java is a blueprint of a class. It has static constants and abstract methods. 

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in  the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in  Java

In other words, you can say that interfaces can have abstract methods and variables. It cannot have  a method body. 

Java Interface also represents the IS-A relationship

It cannot be instantiated just like the abstract class. 

Since Java 8, we can have default and static methods in an interface. 

Since Java 9, we can have private methods in an interface. 

Why use Java interface?

There are mainly three reasons to use interface. They are given below. 

o It is used to achieve abstraction. 

o By interface, we can support the functionality of multiple inheritance. 

o It can be used to achieve loose coupling. 

How to declare an interface? 

An interface is declared by using the interface keyword. It provides total abstraction; means all the  methods in an interface are declared with the empty body, and all the fields are public, static and  final by default. A class that implements an interface must implement all the methods declared in  the interface. 

Syntax: 

interface <interface_name>{  

  

 // declare constant fields  

 // declare methods that abstract  

 // by default.  

}  

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. 

In this tutorial, we will learn about Java exceptions, it's types, and the difference between checked  and unchecked exceptions. 

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. 

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,  IOException, SQLException, RemoteException, etc. 

Advantage of Exception Handling 

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. Let's consider a scenario: 

1. statement 1;  

2. statement 2;  

3. statement 3;  

4. statement 4;  

5. statement 5;//exception occurs  

6. statement 6;  

7. statement 7;  

8. statement 8;  

9. statement 9;  

10. statement 10;  

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

Hierarchy of Java Exception classes 

The java.lang.Throwable 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:

Types of Java Exceptions 

There are mainly two types of exceptions: checked and unchecked. An error is  considered as the unchecked exception. However, according to Oracle, there are  three types of exceptions namely: 

1. Checked Exception 

2. Unchecked Exception 

3. Error 

Working with finally clause 

In the previous tutorials I have covered try-catch block and nested try block. In this guide, we will see  finally block which is used along with try-catch.

A finally block contains all the crucial statements that must be executed whether exception occurs  or not. The statements present in this block will always execute regardless of whether exception  occurs in try block or not such as closing a connection, stream etc. 

Syntax of Finally block 

try { 

 //Statements that may cause an exception 

catch { 

 //Handling exception 

finally { 

 //Statements to be executed 

A Simple Example of finally block 

Here you can see that the exception occurred in try block which has been handled in catch block,  after that finally block got executed. 

class Example 

 public static void main(String args[]) { 

 try{  

int num=121/0;  

System.out.println(num);  

 }  

 catch(ArithmeticException e){ 

 System.out.println("Number should not be divided by zero"); 

 }  

 /* Finally block will always execute 

 * even if there is no exception in try block 

 */

 finally{ 

System.out.println("This is finally block"); 

 }  

 System.out.println("Out of try-catch-finally");  

 }  

Output: 

Number should not be divided by zero 

This is finally block 

Out of try-catch-finally 

Few Important points regarding finally block 

1. A finally block must be associated with a try block, you cannot use finally without a try block. You  should place those statements in this block that must be executed always. 

2. Finally block is optional, as we have seen in previous tutorials that a try-catch block is sufficient  for exception handling, however if you place a finally block then it will always run after the execution  of try block. 

3. In normal case when there is no exception in try block then the finally block is executed after try  block. However if an exception occurs then the catch block is executed before finally block. 

4. An exception in the finally block, behaves exactly like any other exception. 

5. The statements present in the finally block execute even if the try block contains control transfer  statements like return, break or continue


No comments:

Post a Comment