0% found this document useful (0 votes)
13 views46 pages

Java Notes

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)
13 views46 pages

Java Notes

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
You are on page 1/ 46

Introduction:- it is a class based object oriented programing language i.e.

designed to have few


implementation dependency as possible. It is intended to let the user write one and run many times.
It was first released in 1995 and is widely used for developing application for desktop, web and
mobile devices. It is known for its simplicity, robustness, and security feature making it a popular
choice for enter price level application.

It was developed by James gosling at microsystem in 1995 and later acquire by corporation . it is a
simple programming language which makes writing, compiling and rebugging easy. It helps to create
reusable code-end modular programs. It is a class based OOP language java application are compile
byte code that can run on any java virtual machine (JVM)

Key features of java:-

1. Platform independent:- compile converts the source code to byte code and then JVM
execute the byte code generating by the compiler. This byte code can run on any platform be
it window, LINUX and mac, OS. That means if we compile a program on windows. We can run
it on mac OS or vice-versa. Each OS has different JVM but the output produce by all the OS is
the same after the execution of the byte code, that’s why it called platform independent.
2. OOP:- it is an OOP language promoting obj & classes organizing the program in the terms of
collection of obj is a way of OOP each of which request & interfaces of class . The main
concept of OOP one abstraction encapsulation, inheritance & polymorphism.
3. Simplicity :- Java’s syntax is simple easy to learn specially for those who familiar with c &
CPP. IT eliminate complex features like pointer & pointers & multiple inheritance making its
learn to write debug & maintain code.
4. Rebustness:- it is robust which means reliable it is developed in such as way that it parts a lot
of efforts into checking errors as early as possible that’s why the java compile is able to dated
even those errors that are not easily to detect by another language . The main feature of java
that makes collection exception handling & m/y allocation.
Security:- In java we don’t have pointers so we can’t access out of bend array i.e. it shows
array index out of bound exception. It we try to do so that’s why several security flows like
step corruption or bytes overflow are impossible like stack corruption are impossible to
explain in java also program run in an environment that is independent of the environment
that is independent of the OS which makes java more server .
Distributive:- we can create distributed application using the java programing language.
Remote invocation method & enter price java beans are used for creating distributive
application in java. The java programs can be easily distributed on 1 or more system that are
connected to each other through internet connection.
Multi threading:- it support multithreading enabling the content of multiple part of program.
This features is particularly useful for application that requires high performance such as
games and real times simulators.
High performance :- Java architecture is define in such a way that retain overhead during the
runtime & at some kinds java uses (just in time (JIT)) compiler, when compiler code on
demand basis when It only compiles there method that are called making application to
execute faster .
JDK

Source code Compiler Bytecode Execution Native


language

JVM Exit

Java virtual machine :- The JVM is an integral part of the java platform responsible for executing java
byte code.

It ensures that the output of java program is consistence across different platforms.

1. Program writing is done by the programmer.


2. The compilation is done by the java compiler java which is included in JDK. It takes the java
program as input & generate byte code as output.
3. Byte code:- This is the intermediate representation of java code generated by the java
compiler it is platform independent & can be executed by the JVM.
4. JDK:- While we were using the term JDK we find it as a kit that includes everything including
compiler java runtime envorment (JRE) , java debuggers, java docs etc.

Java debuggers define as a command line tool used by developers to debug java code efficiently. It
allows developers to ser break points, ----------------variable &step through the code, it can attach it
self to a running java process & support both local & remate debugging it is a user friendly command
line interface.

Java runtime envoriment :- it about the java program to run however we can’t compile it using only
JRE . JRE include a browser. JVM , applet support & plugins for running the java program.

Garbage collection:- In java programmers can’t delete the obj to delete or recollect that obj/ specific
M/Y (which is allocated previously) JVM has a program called garbage collection. It can be collect the
obj that are not referenced so java makes the life of a program easy by handling M/Y management.

However programmer should be careful about there code weather there are using obj that have
been used for long time b/c garbage can’t recover the M/Y of obj being referenced.

Class path:- it is the file path where java runtime and java compiler look for class file to load by
default JDK provides many library if you want to include external library they should be added to the
class path .

In other words we can say that basically everything in java represent in class as an obj including the
main function.

Performance:- java can be slower compile to the other programing language such as c ++ due to it
use a virtual machine and automatic M/Y management

Data types in java:-


Data types

Primitive Non-primitive

Int string

Float Float

Char class

Byte

Long

Boolean

Java control statement :- java compiler executer the code from top to bottom approach the
statement of java are executed according the order in which they appear.

However java provides statement that can be used to control the flow of java code such statement
are called control flow statements.

There are three types of control statement in java :-

1 .Decision making statement :-

A:- if statement

B:- switch statement

2, Loop statements:-

A:- for loop

B:- do while

C:-while

D:-for each

3. jump statement

A:- break

B:- continue

If statements:- in java the if statement is used to evaluate a condition The content of the program is
diverted depending upon the specific condition. The condition of the if statement gives a Boolean
value either true or false in java there are four types of if statement:…

1. Simple if
2. If else
3. If else if
4. Nested if
# Public class Aditya {

Public static void main (string [] argus)

Int a = 10;

If (a % 2 == 0)

System. Out. Print(“Even”)’;

Else if (a == 0)

System. Out . print (“Zero”);

Else

System. Out. Print (“odd”);

Import java. Util. scanner i

Public class conditional {


public static void main (string [] argu)

Scanner sc =new scanner (system.in);

System. Out. Print (“a= “);

Int a = sc. Next int ();

System. Out. Print (“b=”)’;

Int b = sc. Next int ();

System. Out. Print (“e=”);


Int c= sc. Next int () ;

Page no 13 start

Switch :- This is similar to if else if statements. It contains multiple blocks of code called cases and a
single case is executed based on the variable which is being switched. It is easier to use then the
other if statements there are some rule we need to take are while using switch statements in java

1. The case variable can be int, short, byte, char or num.


2. Cases can not be dublicated.
3. Default statement can executed when any of the case doesn’t match the value of expression
that’s optional
4. Break statement terminates the switch block when the condition is saticfied its optional that
is if not use than the next case is executed.
5. While using switch statement we must notice the case expression will be of the same type a
variable.

Loop:-

Public class loops {

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 (“ “);

Output:-

*
**
***
****
*****

#For loop :- it provides and enhanced for loop to traverse. The data structure like array or
collection. In this loop we don’t need to update the loop variable.

Syntax:-
For(datatype variable:array name)

Statement;

It works on tree, graph and array(d.s).

Public class calculation {

Public static void main(string arr[])

String[]name{“1”,”2”,”3”,”4”};

System.out.print(“print the content/n”);

For(string name: names)

System.out.print(names);

}}}

Page no 18

Operators in java :- Operator constitute the basic building blocks to any programing language java to
provide many type of operator which can be use according to the need to program various
calculation and function be it logical arithmetic and relational.

Types of java operator :-

1. Arithmetic
2. Unary
3. Assignment
4. Relational
5. Logical
6. Ternary
7. Bitwise
8. Shift
String in java :-

1. Generally string is a sequence of character.


2. In java string is basically an object that represents sequence of char values.
3. An array of character works save as java string .

4. String class provides a lot of method of to perform operation on string such as compare ( )
equals, split , length , replace compare to , intern , substring , etc.

5. The java lang string class implements comparable relies able and char sequence interface.

How to create string objects:- There are two ways to create string object

By string literal

By new key word .

I. Literals are define as the siynthatic representation of Boolean , char numeric as string data

String literal:- in java are created by using (“ “ )

String s= “ Abhishek “;

1) Each time you create S L the JVM check s the string “constant tool “ first ..
2) If the string is already exist in the tool a reference to the fooled instance is interned .
3) If the string does not exit in the pool a new string is created and placed in the tool .

Ex:- string s1 = “hello”;

String s2 = “hello”;

Diagram

Note:- It does not crate a new instance.

1) String obj are stored in memory and known as string constant pool.
2) Java uses the concept of string literal to main to java more memory efficient because already
in the string constant pool .

By new key word:-


• It create two obj and one reference variable .String s= new string (“welcome “);
• Here JVM create a new string obj in normal heap memory (non – pool ) a literal
‘welcome’ is places in SCP .
• The variable S will refer to the object in the heap memory.
Ex:-

Public class string_ example {


public static void main (string [] argus )

String s1 = “java”

Char [] ch = { ‘s’, ‘t’, ‘r’, ‘I’, ‘n’, ‘g’};

String s2 = new string (ch) ;

String s3 = new string (“example”);

Sout (s1);

Sout (s2);

Sout (s3);

}
}

Imutable string:-

• In java string obj are imutable.


• Unmodifiable or unchangeable that simple means one’s string obj is created, its data or
state cannot be changed but a new string object is crated .

Class test_string

Public static void main (strig[] args)

String = “Abhishek”;

s.concat (“tyagi”);

cout (s);

Note:- java uses the concapt of string literals that’s why object in java are imutable.

Suppose there are 5 reference variable and all refered to one object and if that one reference
variable changed the value of object then it will affected to all the reference variable .

# Write a program to replace space with underscore :-

Public class underscore

{
public static void main (string [] args)
{

String str = “be yourself”;

Str = str. Relplace ( “ “ . “-“);

System. Out . println (str):

}}

Output:=

Be-yourself

String comparison :-

String in java on the basis of content and reference ,

-→ It is uses in authentic, equal () function sorting (by compare to function ) reference matching
( by equal () operator).

String compile by equal () method :-

➔ String equal () method compare the original content of string.


➔ It compares value of string or equality.
➔ String class provides two method:
→public Boolean equal (object ) → it compare this string to specified object
→public Boolean equal ignore case (string ) →

Class testing comparison

Public static void main (string argus [])

{
string s1 = “hello”;

String s2 = “hello”;

String s3 = new string (“hello”);

String s4 = “world”;

Sout(s1.equal (s2));

Sout(s2.equal (s3));

Sout(s3.equal (s4));

String concatenation :- In java string concatenation form a new string that is the combination of
multiple string and as we already know that concatenation means a series of interconnected obj/
series. There area two case to concat string in java.

1) By + operator
2) By concat() method

1) Public class Abhishek ;

Public static void main (string []args)

String s1 = “Abhishek”;

String s2= “tyagi”;

String s3 = s1 + s2 ;

Sout ( s3 );

}
}

2) Public class Abhishek


{
public static void main (string argus[])
{
String s1= “Abhishek”;
String s2 = “ Tyagi”;
String s3 = s1.concat (s2);
Sout (s3);
}
}

Java classes and objects:-= An entity that has state and behavior is non as object . it can be physical
or logical. An object has following characterstics :-

1) State:- It requested the data of an object that called reconsider the value of object created
in a system .
2) Behavior :- IT represent the behavior or we can say that it is used to represent the
functionally of an object such that deposit, withdraw etc.
3) Object definition:- An object is a real world entity . An object is an instance of a class .
4) Class :- This is a group of object which has common property. It is a template or btw print
from which object are not be physical . A class in java can contain physical . A class in java can
contain .
→Field
→construction.
→nested class
→methods.
→blocks
→interfaces.
Class (class name)

Field;

Method;

Instance variable :- A var which is create inside the class but outside the method is known as instance
variable. It does not get memory at compile time, It get m/y at runt time when an object an instance
is created that why it is known as an IV.

Note:- IN java a method is like a function which is use to expose the behavior of object the
advantages of method is code responsibility and code optimization.

The new Keyword:- is used to allocate memory at runtime and all objects get memory in heap
memory area .

Class student {

Int id;

String name;

Public static void main (string []argus)

Student s1.new student ();

Sout (s1.id );

Sout (s1.name );

Way to initialization objects:-

There are three way to initialize object.

1) By reference variable
2) By method
3) By construction

Class student

Int id ;

String name;

Public static void main (string[] argus)

{
Student s1 = new student ();

Student s2 = new student ();

S2.id = 102; s1.id = “101”;

S2.name = “XYZ”; s1.name=”ABC”;

Sout (“s1.id” + “s1.name”);

Sout (“s2.id” + “s2.name”);

Constructor :- In java a constructor is a block is similar to the method. It is called when an object
of a class is created . At the time of callins constructor many of a object is allocated in the
memory.

It is a special types of method which is use to initialized the object every time an object is
created using “new” at last one constructor is called.

It is called a default constructor if then is no constructor available / declared in the class. In such
cases java compiler provides a default constructor by default . There are two types of constructor
in the java .

1) Default constructor
2) Parameterized
1) Default constructor :- It is called constructor because it construct the value at the time of
object creation.

There are some rules for creating java constructors.

Constructor name must be the same as class name.

A constructor must have no explicit return type.

A java constructor did not be abstract, static final and syncnonise we can use access modifies
while declaring a constructor . it controls object creation.

In other words we can say that we can have private , protected public or default constructor in
java.

Default constructor

Class stud

{
int id;

2) Parameterized constructor :- A constructor which has a specific number of parameterized is


called parameterized constructor . it is used to provides different values distinct object.

Class stud {

Int id ;
String name;

Stud ( int I , string n )

Id = I;

Name = n;

Void display ()

Sout(“id “ + “name” );

Public static void main ( string [] argus)

Stud s1 = new stud (“101”, “ABCD”);

Stud s2 = new stud (“102”, “XYZ”);

S1.display ();

S2.display ();

Data abstaraction:- A database system is a collection of interrelated data and a set of program that
allows user to access and modify these data. In major purpose of DBS is to provide the user only that
much information that is required by them. This means that the system does not disclose all the
details of does not disclose all the details of data .

Rather It bides certain details of how the data is stored and maintain.

• Physical label:- It is the lowest level of abstraction and describe how the data actual stored
on storage media. It describe complex low level data structure in details.
• Logical label:- It is next higher level of abstraction and describe what data are stored in the
database and what relationship exist among those data. Thus it describe the entire database
in terms of a small number relatively simple structure.
• Vies level:- IT is the highest level of abstraction and it concerned with the main in which the
data are mute by individual user, most of the user of database. Instead the need of apart of
database relevant to that. To simplify the user interaction this level is defined. Thus, the
system provide many view for the same database.
Constructor overloading:- it is a technique of having more than one constructor with different
parameterized list . They are arrange in a way that each constructor performs different task. They are
different by the compiler, by the number of parameterized in the list of there types;

Class stud

Int id ;

String name ;

Int roll_no;

Student ( int x , string n, int y)

Id = x;

Name = n;

Roll_no = y;

Student( int x, string n )

{
id = n;

Name = n;

Void display ()

Sout (“id” + “name” + “roll_no”);

Public static void main (string []args)

Student s1 = new student ( “101”, “XYZ”, “1009”);

Student s2 = new student (“102”, “ABC”);

S1.display ();

S2.display ();

}
Different between constructor and method :

Constructor :

1) A constructor is used to initialize the state of an object.


2) A constructor must not have return type.
3) It invoked implicitly .
4) The java compile provides a default constructor if you don’t have any constructor in a class .
5) The constructor name must be same as the class name

Method :-

1) It is used to expose the behavior of an object.


2) A method must have a return type .
3) It invoked explicitly .
4) A method is not provided by the compiler in any class.
5) The method name may or may not be same as class name.

Copy constructor :- there is no separate copy constructor in java however we can copy the values
from one object to another like c , C++.

There are many way to copy the values from one object to another like cc in c++.

There are many way to copy the values of one object into another .

1) By constructor
2) By assigning a value of one obj to another .
3) By clone () method of obj class.

Class student

Int id ;

String name;

Student (int I, string n )

Id = I; name=n;

Student (student s)

Id = s.id;

Name = s.name;

Void display ()
{

Sout( “id” + “name” );

Public static void main (string []args)

Student s1 = new student (“101”, “A”);

Student s2 = new student (s1);

S1.display();

S2.dispaly();

}}

Output:- 101, A

101, A

Inheritence :- It is mechanism in which are object acquire the properties and behaviour of parent
object.

→Advantage of inheritance is that, when it inherit from an existing class. You can reuse method
and feeds of the parent clan moreover you can add new method, and feeds in your current class.

➔ It represent the parent child relationship .


➔ We use it for :-
• Code reusability
• Method overwriting (run time polymorphism).

# Rules for inheritance:-

1) Multiple inheritance is not allowed in java .


2) Constructor cannot be inherited .
3) Private member cannot be inherited.
4) Cyclic inheritance is not allowed in java.
5) We assign parent reference to child object.

#Terms used in inheritance :-

→Sub class:- It is a class which inherit the other class. It is also called a derived /extended/ child
class.

→superclass:- it is the class from where a subclass inherit the feature. It is also called base [print
class].

→reusability :- it is a mechanism which facilitate you to reuse the fields of an exisiting class when
you create a new class .

Class subclass_name extends super_class

{
Fields //(data type)

Method // function

The extends keyword indicates that you are making a new class that derived from an existing class .

• Difference between c++ and Java

C++ Java
1. It is platform dependent. 1. it is platform independent .
2. It is namely used for the system 2. it is mainly need. For application
programing programing and is willy used in enterprices.
3. It supports the ‘goto’ statement. 3. it doesn’t support ‘goto’ statement
4. It support multiple inheritance . 4. it doesn’t support multiple inheritance
through class but it can be achived by using
interfaces in java.
5. it supports operator overloading 5. It doesn’t support operator overloading
6. it supports both ‘call by value’ or ‘call by 6. it supports call by value only
reference’.
7. it is an object oriented language however in 7. it is also an object oriented language
c++ a single hierarchy is not provide however everything in java is an object except
the fundamental types,it is a single heirachy as
everything derived from java. language

#Java language:- A set of syntax symmetric and keywords that can be compiled into an executable
form called bytecode. The bytecode are then interpreted by a virtual java machine (JVM). Some
features of java includes object- oriented programing , automatic memory management .

#Java platform:- A collection of technology that allows for the development of application for
different execution environment.

There are four java platform i.e.

1) Java platform
2) Standard edition (java se)
3) Java platform enter prices edition (java EE)
4) Java platform micro edition (java HE)

#Types of Inheritance:- On the basis of class there can be 3 types of inheritance

i) Single
ii) Multilevel
iii) Hierarchical

In java programing multiple and hybrid is supported through interface only.

Example of single inheritance :-

When a class inherit other class , it is known as single inheritance


Class mathta

Double pi=3.14;

Double area of c (double r)

Return pi*r*r;

}}

Class

Note:- Multiple inheritance is not supported in java to reduce the complexity and simplify the
language .

Consider a scenario when a,b,c are three classes .The class inherit A and B classes. If A and B have
the same method and you called it from child class object, there will be ambiguity to call the method
of a or b class.

Since, compile time error are better than run time error, java compile time error, if you inherit two
classes.

So , whether you have same method or different there will be compile time error .

#Aggregation Java:- if class has an entity reference , it is known as aggregation , we use aggregation
for code reusability .

Syntax:-

Class employe

Int id;

String name;

Address, address;

------------------

#when to use aggregation:-

i) Inheritance should be used only if the relationship Isa maintain throughout the lifetime
of the object involved , otherwise aggregation is the best choice.

#Method overloading:-
i) If a class has multiple method having same name but different parameters is known as
method overloading .
ii) Suppose you have to perform addition of given numbers but there can be any number of
given numbers but there can be any numbers of given arguments if you write the
method such as A (int, int) for 2 parameters B (int, int, int) for 3 parameters then it may
be difficult for you as well as other parameter to understand the behaviour of the
method because its name different .
iii) The advantage of method overloading is that it increase the read ability of the program .
iv) There are two ways to overloading the method in java.
• By changing number of arguments .
• By changing datatypes.

Note:- Method overloading in java is not possible by changing the returns type of the method .

# Method overloading:-

i) If subclasses has the same method as declared in the parent class , it is known as
method overriding .
ii) It is used to provide the specific implementation of a method which is already provided
by its superclass.
iii) It is used for overtime polymorphism
iv) There are some rules to be followed by using java method overriding .
• The method must have the same name as in the parent class.
• The method must have the same parameter as in the class.
• There must be an ISA relationship .

Difference between JDK 1.0 and JDK 1.01:-

I) Event handling model:-


JDK 1.0:- used to the event- delegation model which was use efficient as all events were
sent to every component .
JDK 1.01:- introduced a new event- handling model that was more flexible and easier to
manage, using event listeness.
ii) Inner class:-
JDK 1.0:- Did not support inner classes .
JDK 1.1:- Introduced inner classes, allowing classes to be defined within other classes to
be defined within other classes.
iii) Reflection API:-
JDK 1.0:- No reflection API was available.
JDK 1.01:- Introduced the reflection API, allowing program to input and manipulate
objection methods and fields of runtime .
iv) Java Beans:-
JDK 1.0:- Java beans was not a part of framework .
JDK 1.01:- Introduced the java beans components model, which is a framework for
creating reusable software components.
v) Internationalization:-
JDK 1.0:- Limited support
JDK 1.01:- Introduced new classes and interfaces to better support internationalization
(IIBM) including local, resources bundle , character encoding conversion.

# Java package:-

➔ A Package is a group of similar types of classes, interfaces and sub packages.


➔ Package can be categonized in two forms i.e, built in package and user defined .
There are many built -in package such as long, java x , net , util , SQL etc.

Java

Long Util AOT

System.class String class Array list class Map.class Button.class

➔ The package keyword is used to create package in java.

#package addition ;

Public class sum {

Public static void main (string [] arg)

Int a =10; int b=20;

}}
# package addition 2;

Import addition 1.*;

Public class sum

Public static void main (string[] arg)

System.out.println(a+b);

}}

#Advantage of packages:- IT is used to categorized classes and interfaces so that they can by
easily maintain . it provides access direction , it removes name collection.

• Reusability
• High security
• Memory management
• Easy to locate related classes
• There are ways to access the package form outside the package.
I) Import package .*
II) Import package. Class name
III) Fully qualified name

# Using package name. class name:-

Package pack;

Public class A

Public static void message {

System.out.println (“Hello”);

}}

Package mypack;

Import pack.A ;

Class b{

Public static void main (string[] arg)

A obj = new A () ;

Obj.message;}}
# using fully qualified name:-

If you use fully qualified name then only declared class of this package will be access able now In this
way we don’t need to import. But we need to use fully qualified name every time when you are
accessing . The class are interface . it is generally used when two package have same class name i.e.
jave.util , java. Sql .

Package can contain ‘date’ class.

# Sub package in java:- Package inside the package is called subpackage it is used to categonized the
package further in such the way that we don’t need to create a number of package to define the
code.

# user input in java:- To input from the user in java the scanner class is used.

The scanner class is a built_in class of java.util package java scanner class provide many built in
method to take different types of user inputs form user there are same steps to be follow to we
scanner class for the user input in java

Step1:- import scanner class:- firstly the user need to import the scanner class to use its method

Import java. Util . scanner


Step 2:- create scanner object:- After importing the scanner class you need to create its object to use
its method . To create an object of scanner class invoke scanner () constructor .

Scanner obj = new scanner (system.in);


Step 3:- Take user input:- Scanner class provide a variety of method which are useful to take user
input of different type.

Example :- If the user want to input an int, value, use next int(_) method.

Int age = obj.next int();


Java runtime environment (JRE):- The JRE is a software language that run top of a computer
operating system software and provides the class ____________ and other resources that a specific
java program requires to run.

The JRE is one of the B interrelated components for developing and running java programs. The other
components are JDK  JVM.

• The JDK is a set of levels for developing java application . Developers choose JDK by java
version and by package edition JAVA enterprises edition (JAVA EE) , java special edition (JAVA
SE ). Every JDK always includes a compatable JRE because the java program is a part of a
process of developing a java program .
• The java runs time java application , every JRE includes a default JRE but developers can
choose another that means the specific resources needs for their application .
The JRE combine java code by using the JDK with the necessary library requires to run it on a
JVM’s then create an instance of the jvm that runs the resulting program . JVM are available
for multiple operating system and program crated with the JRE . in this way the java runtime
environment is what enables a java program to run in any operator system without
modification .
• Working of JRE :- the JDK and JRE interact with one another to create a rustainble the
runtime environment that enables the seamless execution of java based application in
vitually any os. The attribute makeup the JRE runtime architecture are:-
i) Class loader:- IT dynamically loads all clanes which are necessary to run a java
program , since java classes are only loaded into memory when they are required the
JRE uses class loader to automatic this process on diamond .
ii) Byte code verifier :- It ensure the format and accurancy of java code before it passes
to the interpreter. It code system integrity or access rights then the class will be
consider corrupted and wants to be loaded .
iii) Interpreter :- After the byte code successfully loads the java interpreter creates an
instance of JVM that allows the java program to be run natively on the under time
machine.

What does JRE consist of :- Beside the JVM , JRE is composed of various other software tool and
feature to get the most out of java apps .

i) Deployment solution :- IT included as a part of JRE installation are deployment


technology like java when start and java plugging that simplify the activation of
application and provide advanced support for java updates.
ii) Deployment tool kit:- The JRE also contains tools kit design to help developers improve
their user interface .
a) Java 2-d :- An application programming interface that is used for drawing 2
dimensional graphics in java language . developers can create rich user interfaces i.e.
special effect games and animation.
b) Abstract window tool kit :- A graphical user interface that Is used for creating object,
buttons , scroll bar and windows.
c) Swing:- it is an another light weight GUI that uses a rich set of interfaces / codes for
affecting for flexible customization technology.
Note :- Java plug-in is a part of JRE that allows applets to run in browser or we can
simply chat it is used to connect the java platform tool to the software browser.

This plug-in adds java compilation testing and bundling capabilities to a project..

# Integration library:- JRE provides several IL to assist developers in creating seamless data
connection between their application and services.

Integration library are of three types:-

i) Java IDL:- it uses common object , request architecture to support distributed object
written in java programing language .
ii) Java database connectivity (JDBL):- it provides tools for developers to write application
with access to remote relationship database i.e. flat files and spreadsheets.
iii) A programing interface and directory service that helps client create portable
application that can fetch information from database by using naming conventions .

# language and utility library :- included with JRE are java long and java. Util package that are
fundamental for the design of java application , package versioning, management and monitoring, it
included some of main package are ….

i) Connection framework:- A unified architecture i.e. made up of a collection of interfaces


design to improve the store and process of application data.
ii) Concurrency utility:- A powerful framework package with high performance threading
utility.
iii) Preference API :- A Light weight cross platform persistant API that enables multiple users
on the same computer to define their AWT group of application preferences.
iv) Logging :- A Package that produce log records such as security failure, configuration error
, compilation error and performance issue for function analysis is called logging .
v) Java archive :- A platform independent file format that enables multiple files to be
bunded in for format, significantly improving download load and reduce file size .

Java Api:-java application programing interface is a software components that connects different
parts of the java programing stack. It is integrated into JDK and is a key part of open and internal
development. Java Api are made up of predefine classes interfaces and method that developers can
used in there java application they act as a bridge between different software components and
allowing them to interact with each other in standardized way. The java Api can be a value able tool
for developers they let you access a wide variety of third party services with just a few lines of code,
which can be helpful in solving problem or building apps that are difficult to do without them.

It helps developers in number of ways including

1. Using prebuild components – developers can use prewritten java components


2. integrating with external resource -Api is can help developers integrate with external
resources.
3. Stream liming development – Api can simplified the development processing make it is easy
to the user to use when required .
4. Automatic task- Api can help automate task in such a way that it can be easily retrieve by
the user
5. Machine to machine interaction- machine Api can enable interaction between machine .
6. Reducing developers work load -Api can reduce the amount of work that developers need to
do by providing predefine interfaces methods to the developers which can be very time
consuming to work on

Types of Java Api:- There are five types of java Api

1. Public java Api are often refer to as open java Api as they are part of JDK and don’t need any
extra payment. Also they are free from the areas and use causes for there implementation.
2. Private or internal java Api is design by a particular developers aur organization and is access
able only to authorized professional
3. Partner java Api are the third party Api often to business for specific operation.
4. Composed java Api is basically microservices developed by using different kind of Api.
5. Web java Api is accessed by VIA http protocol and is used to stablished a communication
bridge for browser based application/ services like web storage and web notification .
Example:- REST API makes code available and useable for every related application or
program .

Advantages of API:-

The direct impact of using Api in java is expedient the development as it makes predefined classes
and packages available for intended program . however that’s not the only advantages but more .

i. Java API keep human involvement as least as possible and empower computer so much that
they take care of the entire development job. Java API’s deploy automation of highest grade
into action and makes crucial work flow quick and error free.
ii. Service delivery is much more flexible with java Api as these Api’s are available for every
components and lift all the data access restriction. Additionally, the content or code
generated using java Api is set to be released and work . All the related channel are allow to
access this freshly generated content. This makes development quick from the ground level
iii. Java Api exhibit unmatched integration abilities as they ready to be embed in any software or
program or website . The high and integration makes data fluid enough to be used at any
platform where ever enhanced user experience for fulfilment demands .
iv. There are some other most important advantages of Api .
1. Adaptation
2. Customization
3. Scope
4. Integration
5. SQL support
6. Application
7. Efficiency
8. Automation
Java applets:- applets is a special types of program that is embedded in the web page to generate
the dynamic content. Java applet is an entity which runs inside the browser and works at clint site.

The advantages applets are :-

1. It works at clint site so it takes less response time


2. It is secure
3. It can be executed by browser running under many platform including Linux windows, and
mac etc.

Hierarchy of applets:-

Object

Components

container

Pannel

Java applets
Lifecycle of java applets:-

1. Firstly applets is initialized when started, then printed, then stop and then destroyed lastly.

Applet is
initialized

Applet is Applet is started


destroyed

Applet is stopped
Applet is painted

Life cycle and method for applets:-

1) The java. Applet. applet class provides for lifecycle method .


2) The java. AWT:-. component class provides one life cycle method for an applet .

Java. Applet. Applet class:- for creating any applet “java. Applet. Applet class “ must be inherited.

a) Public void int () :- it is used to initialized the applet, it is invoked only one
b) Public void start () :- it is used to start the applet it is invoked after the int () method or
browser is maximized .
c) Public void stop () :- it is used to stop the applet , it is invoked when applet is stop or
browser is minimized .
d) Public void destroy () :- it is used to destroy the applet and invoked only once .

Local and remote applets:- an applet developed locally and stored in a local system smooth as local
applets. When a web page is trying to find a local applet it does not need to use internet and
therefore the local system does not require the internet collection is simply purchase the direction in
the local system and loads the specify applets.

A remote applet is that which is developed by someone else and stored on a remote computer
connected to the internet. If our system is connected to the internet so we can download the remote
applet In to our system via the internet and run it . in order to load a remote applet we must know
the applet address that is URL .
Important :- Applet v/s application :-

1) applet does not have main () method unlike application .


2) Unlike stand alone application , applets can not run independently. It needs web
page using us a special features known as HTML tag .
3) Applet can’t read form or write to a file in local system .
4) Applet can’t communicate with other server on the network.
5) Applet can’t run a program from local computer .
6) Applet are restricted from using libraries from other languages like c, or C++ etc. But
it is noted that java support the same using native method.

Why we need applets:-

I. When we need to include something dynamic to included in our web page then
we can use applet directly .
II. We use applet when we required some flash out like applet to produce some
sound , animation or some special effect when displaying some certain pages.
III. We use applets when we want to create a program and want it to make
available on net so that it could used by other .

# Writing java applet code :-

To create an applet we need to follow some step:-

1) Building and applet code that is (.java file ).


2) Creating an executable applet (.class file ).
3) Designing a web page by using HTML tag .
4) Preparing <APPLLET> tag ,
5) In corporative <APPLET> tag into the web page.
6) Creating HTML file .
7) Testing the Applet code .

Step 1. :- in order to create an applet tab we have to use two classes namely ‘applet’ and ‘graphics’
from the java class library. The applets class which is contain in the java , applet package provides life
and behaviour to the applet through its methods such as init() , start() and point() , unlike application
to which the execution starts from main() function, in applets class methods for running and rapping
the applet code when applet is loaded the applet class therefore maintains the lifecycle of an applets
the point() methods of an applets class, when it is called dislocate the result of the applet code on
the screen . The output ma be text, graphics or second , the point () methods require a graphic
objects as an argument.

Syntax of point():

Public void point (graphics G)

It provides the applet code imports the java.Awt package contained in the graphics class.

➔ So they structure may looks like:-


Import java.awt.*;
Imp0rt java applet.*;
Public class hello java extends applet
{
Public void point (Graphics G)
}
g.drawstring(“Hey there”,10,100);
}}

Step2:- Now after typing the code, you have to safe save the file with any name with an
extension java and write after that you have to convert the java file to generate , class file
which is also called as byte code which is automatically generated to after the compilation of
the program.
Step3:- in order to run java applet, user used to create an HTML file and associate the applet
code with the HTML file.
Step 4:- To incorporate applet code to HTML document . we use <APPLET> .
In order to incorporate: the class file with <APPLET> so that it should be attached with HTML
file.
<applet code= file name.class height =200 widht = 400>
</applet>
Running the applet:- the order to run applet we must area have there 3 files under these
directories.
Example :- hey there.java, hey there. Class, hey there. HTML
# How to run an applet:-
• BY HTML file:-
Import java. applet . Applet ;
Import java. Awt. Graphics;
Public class first extends applet
Public void point (Graphics g)
{
g.drawstring(“welcome”,150,250);
}}

# <HTML>

<body>

<appletcode =”first .class” width = “150” height = “250”>

<applet>

</body>

</HTML>
Abstract window tool kit :- It is an Api to develop GUI or window based application in java. AWT
components are platform dependent i.e. components are displayed according to the view of OS
.AWT is heavy weight i.e. the component of AWT through using the resources of OS . The
java.AWT.package provides classes for AWT or API such as text field, label text area , radio button ,
checkbox, choice list. Etc.

Java AWT hierarchy :-

object

button

label
component

checkbox

choice

list

container

window
panel

applet
frame dialog
1) Container:- the container is a component in AWT that can contain other component like
buttons, text field and label etc. The class that extends container class are known as
container such as frame , dialog , panel .
2) Window:- The window is a container that has no border and menu bars you must use frame ,
dialog or another window for creating a window .
3) Panel:- The panel is a container that does’t contain the title bar and menu bar . it can help
other components like button text field, etc.
4) Frame:- The frame is a container that contain title bar and border.it is a container for other
GUI components and is used to create the main window of the Application.
→Frame class in java:-
Package = java.awt
External = windows
Implement = menu container
-→key features of frame:- it has the title bar that display the title of the window .
1) it is surrounding with a border .
2) it is resize able as it can be resized by the user.
3) it is closeable as it is closed by the user.
→common method of frame class:-
1) Set Title () :- Set the Title of the windows .
2) Set Size ():- Its Set the size of the windows.
3) Set Location ():- Its set the location of the windows.
4) Add ():- it adds component to the window .
5) Pack ():- It pack the window to its prefer heigh.
6) Set visible ():- it makes the windows visible or invisible .

Impact java.awt.frame;

Public class my frame

{
public static void main (string [] args)

Frame frame = new frame(“ my frame “);

Frame set Size (300, 200 );

Frame.set Location (100, 100);

Frame.add(new label (“hello there”));

Frame.pack();

Frame.setvisible(true);

}
Useful method or components class:-

Method Description

# public void add ( c) # Insert a components on this components.


# Public void set size (int width , int , height) # Set the size i.e. width and height of
components .
# Public void set layout(layout manager M) # Defines the layout manager for the
components .
# Public void set visible (Boolean status) # It changes the visibility of the
components and when the user didn’t the
system consider the value as false

# To create how to develop a Awt

1).

2) integrity method:- insure data has not been tempered with or altered during transmission or
storage.

3). Non repudiation :- from denying that they sent a message or data.

4) secure communication :- it is stablished secure communication channels to protect data in


transition .

5) digital certificate;- validate the authentication of digital certificate , used for secure connection
and data inscription .

6) software distribution :- verify the authenticity integrity of software download insuring that they
sources.

Java beans :-reusability is the main concept in any programing language. Java beans is a software
components that has been design to be reusable in a variety of environments .

Java beans is a portable, platform independent model return in java programing language. Its
components are refers to as beans .

1) Java beans are classes which in capsulate several object into a single object. It helps in
accessing these objects from multiple places, java beans contains several elements like
constructor, getter /seter methods and much more .

Benefits of java beans :-


1) Java beans components are built purely in java , hence are fully portable to any platform that
supports the java runtime environment. All platform specifies as well as support for java
beans , are implemented by the java virtual machine
1) Compact and easy:- java beans components are simple to create and easy to use . this is
an important focus sector of the java beans architecture .it doesn’t take much effort to
right a simple beans also a bean is light weight , so it doesn’t have to carry around a lot
of inherited baggage to support the java beans environment .
2) The java beans properties and methods can be expose to another application .
3) It provides and easiness to reuse the software components

Reusability : java beans can be easily reused in multiple application shaving time and effort
in development .

Encapsulation : java beans can encapsulate data and functionality making it easier to
manage and maintain code .

Plate form independent :- java beans can be used on any platform that supports java ,
making it highly portable and versatile.

Event handling : to handle events , a listener must a register java beans when an event occur,
the bean notify all register listeners. The listener than perform the necessary excel in
response the event .l,

1) The power of beans is not limited to design user interfaces a bean can be a non visual
components such as a data structure a proxy or proxy for a remote data base . bean
builder tools manipulate beans , helping to build application without requiring you to
right code . more over beans are not only useful in application design tools they can cure
useful in runtime environment as well ,

Features of java beans:-the bean specification define three tyupes of bean feature . to another
application on class, describing the state and behavior of the beans the three type of beans features
are :

1) Properties:- Exposed peaces of the beans state .


2) Event set :Stimulus from the being that something, like a changing of state has occur the
being broadcast this information to its listener .
3) Methods : public methods , callable from other beans or application .

All beans features must be public , this allows any other beans to inspect and modify properties ,
register itself as an event listener or call provided methods . this doesn’t mean that the actual data
inside the class means to be public , nor do all methods in the class needs to be public .

→TO use of simple naming convention a bean enables application to determine which features it
supports .Tools discover being features solely through the names of the public method define in a
bean class. A bean enabled tool can use the java language reflection API. To determine which public
method a class defines , the tool can also determines available bean features based on the hance of
those methods some beans also provides an explicit class called a bean info class that describes
features in more detail but this is not necessary this additional information can enhance design time
use of bean but has no affect on the run time behaviour of the bean .

# properties of java beans:- it may be read , write read only and write only. Java beans features
are accessed through two methods in the java beans implementation class.

i) Get property name()

If the property name is first name, the method name would be get() name to read that property .
this method is called the accessor .
ii) Set property name()
For example, if the property name is firstname, the method name would be
setfirstname() to write that property . This method is called the mutator.

Properties:- Properties describe part of the state of its bean, usually information that can
distinguish different instances of a bean. There are two types of properties: simple and indexed .

• A property can be either simple or indexed; it cannot be both .

• Simple Property

• Simple properties act like individual bits of data, describing the state of a bean. You define
simple properties using sets of methods that match the following patterns:public TypeName
getPropertyName()

• public boolean isPropertyName()

• public void setPropertyName(TypeName value)

• TypeName is the name of a class or primitive type, and PropertyName is the name of the
property. The presence of a get or is method defines a readable property. A set method defines a
writeable property. The property name is actually a lower-cased version of whatever follows the
get or set in the method declaration.

• For example, suppose a bean defines the following method:

public Color getEyeColor()

• This defines a readable property named eye Color of type java.awt.Color.

Note:- that there can be both a get and is method for a boolean property; the is
method is allowed for readability. Normally, you define the get and set methods, but
sometimes the get method doesn’t read naturally.
For example:-

if (list.isEmpty()) {...}

// is more readable than

if (list.getEmpty()) {...}

• The beauty of this model is its simplicity. Many programmers already use get and set methods
to access their data, so defining properties is no different from their current style.

• A tool that recognizes these get and set methods can present a list of properties to a user,
enabling the user to specify property values. The tool generates code to pass the specified values
to the set methods.

• Because the tool is only querying the names of the methods, there does not need to be any
actual data corresponding to the property. A property could simply be a computation or an
alternate means to validate and set other data inside the class. An isEmpty() method might
simply count items in a referenced list, or a if the property name is first name , the method name
would be set first name () to write that getMaximumValue() method might return an integer such
as five.
Indexed Properties :-
ndexed properties are an extension of simple properties that allow multiple values for that
property. The property acts like an array, even if there is no actual data for that property or if the
data is stored in a non-array structure.

• You define indexed properties using four methods:

• public TypeName[] getPropertyName()

• public TypeName getPropertyName(int index)

• public void setPropertyName(TypeName[] value)

• public void setPropertyName(int index, TypeName value)

• Recognizing these methods, a bean-builder tool can present a (possibly editable) list of values
for setting the property.

Bound and Constrained Properties


• While these names may conjure images of Harry Houdini, bound and constrained properties
have nothing to do with ropes, shackles, or chains. (If you’re thinking something other than
Harry Houdini, remember that this is a family show…)

• Bound and constrained properties fire events that report any modification to their state.
Bound properties notify registered listeners after their state has changed, while constrained
properties notify listeners before they change, allowing those listeners to veto the change.
You can bind and constrain simple or indexed properties.
• Bound or constrained properties greatly enhance the flexibility of a bean. Bound properties
enable you easily to keep property values in different beans synchronized. VisualAge for Java
provides techniques to take advantage of bound properties. Constrained properties allow
you to plug in validation, in the form of listener objects, rather than hardcoding that
validation into the property code itself.

JavaBeans conventions .
• It should have a public no-arg constructor.

All properties in java bean must be private with public getters and setter methods.

i) A getter method is used to read the value of a readable property


ii) To update the value, a setter method should be called

Must implement Serializable. as it allows to save, store and restore the state of a
JavaBean you are working on
i) In object serialization an object can be represented as a sequence of bytes that
includes the object's data as well as information about the object's type and the
types of data stored in the object.
ii) After a serialized object has been written into a file, it can be read from the file
and deserialized that is, the type information and bytes that represent the object
and its data can be used to recreate the object in memory.
Setter and Getter Methods in Java
Properties for setter methods:
• It should be public in nature.
• The return type a should be void.
• The setter method should be prefixed with the set.

• It should take some argument i.e. it should not be a no-arg method. Properties for getter
methods:
• It should be public in nature.
• The return type should not be void i.e. according to our requirement, return type we have to
give the return type.
• The getter method should be prefixed with get.
• It should not take any argument.

Introspection & Persistence


Bean Introspection:- Introspection is the process of exposing the properties, methods, and
events that a JavaBean component supports. This process is used at run-time, as well as by a
visual development tool at design-time. Builder tools use introspection to determine those
events that a bean sends and those events that it receive

Bean persistence:-
Beans use Java object serialization, by implementing the java. io. Serializable interface, to
save and restore states that might have changed as a result of customization. A bean has the
property of persistence when its properties, fields, and state information are saved to and
retrieved from storage. Component models provide a mechanism for persistence that
enables the state of components to be stored in a non-volatile place for later retrieval.

Components of java beans


Components of Java Beams are nothing but the class that contains the definition of beans. These
classes have specific design conventions. It consists of events, methods, persistence, and properties.
Non-GUI-based and GUI-based components are the two types of components.

The classes are discussed below:


Properties: This attribute consists of a label, font, color, size, display size, etc. It determines behavior,
appearance, and the state of Beam.

Methods: Methods in JavaBeans are similar to the normal Java methods. It does have any specific
naming convention.

Events: Events in JavaBeans is similar to Swing event handling.

Persistence: It helps in storing the state of JavaBean. Advantages of JavaBeans

• Run anywhere; write once – Java Beans eliminates the need for writing software repeatedly.
• One can work with JavaBeans on Numerous local platforms, which makes it valuable in the
global market.
• JavaBeans can capture the events that are sent by other objects. It enables object
communication.
• An application developer can control Methods, events, and the properties of any Java beans.
• Zero hassle at run time with auxiliary software; one can configure beans during design time.
• Reusable: One can make a persistence configuration setting in JavaBeans. Persistent storage
and restoration later can save the configuration setting of the bean.

Interface:- it is a blueprint of class . it has static constant and abstract methods. It is a mechanism to
achieve abstraction and multiple inheritance in java.it can have abstract methods and variable and it
be instantiated just like abstract class. It also represents I.S.A relationship .

How to declare interface:-

➔ It provides total abstraction ,means all the method in an interface are declared with the
empty body an all the fields are public static and final by default .
➔ A class that implement an interface must be implement all the methods declare in the
interface .
SYNATX-> interface<interface_name>
{
//declare constant fields
//declare methods that abstracts
// by default
}

Note:- the java compile at public and abstract key word before the interface methods . more over it
adds public , static and final keywords before the data member , in other words interface fields are
public static and final by default and the methods are public and abstract .

Relationship between class and interface

Interface Interface
Class

Extends implements extends

Interface
Class Class
Interface printable

Void print();

Class A1 implements printable

Print void print()

Sout(“Hello”); }

Public static void main(string[] args)

A1.obj = new A1();

Obj.print();

}}

Output:- “Hello”

Input -output :-

➔ Java input and output is used to process the input and produces the output .
➔ Java use the concept of a stream to make input and output operation faet.
➔ The java.io package contains all the classes required for input of output operation .
➔ We can perform file handling in java by java i/o API

Stream :-

➔ A stream is a sequence of data


➔ In java a stream is composed of bytes
➔ It’s called stream because it is like a stream of writes that continues to flow .
➔ In java 3 streams are created for us automatically
➔ All these stream are attached with the console
System.out – standard output stream .
System.in – standard input stream
System.err – standard error stream.
➔ Code to print output and an error message to the console.
System.out.println(“simple message”);
System.err.println (“error message”);
➔ Code to get input from console .
Int I = system.in.read();// return ASCII code of 1st class
System.out.println((char)i);//will print the character
Output stream vs input stream:-

➔ Output stream:- Java application uses an output stream to write data to a destination ; it may
be a file, an array peripheral device or socket .
➔ Input stream :- java application uses an input stream to read data from a source; it may be a
file , an array peripheral device or socket .

The Working of java output stream and input stream is given below:-

Output stream class:-

➔ It is an abstract class.
➔ It is the superclass of all classes representing an output stream of bytes.

Useful methods of output stream:-


Methods Description

• public void write (int) throws I/o • used to write a byte to the current
exception . output stream .
• public void write (bytes) throws I/O • used to write an array of byte to
exception current output stream .
• public void flesh() throws I/O • flushes the current output stream
exception . • used to close the current output
• public void class() throws I/o stream .
exception.
Output stream hierarchy:-

Input stream class:-

➔ it is an abstract class .
➔ it is the superclass of all classes representing an input stream of bytes.

Useful methods of input stream:-

Methods Description

• public abstract int read() throw to • Reads the nest bytes of date from the
exception. input stream.it return at the end of file .
• Public void class() throws I/O exception. • Used to class the current input stream .
Input stream Hierarchy:-

File output stream class:-

➔ it is an output stream used for writing data to a file .


➔ if you have to write primitive values into a file use file output stream class.
➔ You can write byte-oriented as well as character orients data through file output stream
class.
➔ For character -oriented data,it is preferred to use file write then file output stream.

Declaration :- public class file output stream extends stream .

Example java file output stream ( write byte)

Import java.io.file output stream;

Public class example

Public static void main (string args[])

Try

Fileoutputstream.sout=new fileoutput

Stream(“0;\\testout.text”);

Fout.write(65);

Fout.class();

System.out.println(“success”);
}

Catch(exception)

System.out.println(e);

}}}

Output:- Success.

File input stream class:

➔ It obtain input bytes from a file .


➔ It is used for reading byte – oriented data such as image data audio, video .
➔ You can also read character stream data.

Declaration:- Public class file input stream extends input stream.

Buffered output stream class:


➔ It is used for buffering an output stream .
➔ It internally user buffer to store data .
➔ It odds more efficiency than to write data directly into a stream.
➔ So it makes the performance fast.
➔ For adding buffer to an output stream. Use buffered output stream clean .

Syntax:

Output stream os= new buffered output stream (new file output stream

(“0:\\io package\\testout.ext”));

Declaration:- public class buffered output stream extends fetch output stream

Buffered input stream class:- it is used to read informantion from stream

Exceptional handling:- it is a mechanism that allow handling and managing run time errors or
exception by ensuring that the program doesn’t terminate abruptly without a major effect. It
enables developers tool detect exception . handle exception and recover from exception . an
exception is an event that distrupt the normal flow of the program it is an objective which is at
run time. And exception i.o exception SQL exception remote exception etc.

#Advantages:- it’s advantages is to maintain the normal flow of application .

Example:- statement;

statement 2;

statement 5; \\ exception occur

Statement 10;

There are 10 statement in code and there occur exception at statement 5 then rest of code will
not execute i.e; statement 6 to 10 and if we perform exception handling, rest of statement will
execute that’s why we use exception handling in java.
Types of Exception:- Mainly there are 2 types of exception

➔ Check
➔ Uncheck

A errors is considered as uncheck exception which came from run time error .

➔ Check exception:- The class which directly inherit “throwable” class except “runtime
exception and “error” are known as check exception.
Ex:- io exception SQL Exception
Check exception are checked at compile time.
➔ Unchecked Exception:- The class which inherit run time exception are know as run time
exception are known as run time exception such as arithamatic null pointer array index out
of bound exception .
➔ Error exception:-- error are irrecovroable
Ex; out of memory error virtual machine error etc.
# hierarchy of exception handling :-

Exception keyword :- There are 5 keywords in handling exception in java i.e, try , catch finally throw
.throws.

Try:- it is used to enclose the code that might through an exception and it must be through an
exception and it must be used within the method if an exception occurs at the particular statement
of ‘try’ blog . the rest of the block code will not to keeping the code in try block that will not throw an
exception .

It must be followed by either ‘catch’ or finally block


Try{

\\code that may throw an exception

Catch (exception_class_Name.ref)

{}

catch:- it is used to handle the exception by declaring the type of execution


with the parameter. The declared exception must be the _____class of
exception or generated exception type however the good approach is to
declare the generated type of exception and it must be used try black code.
We can use __________catch block in a single try block if needed .
Internal working of try and catch block :-

➔ The JVM first check whether the exception is handled or not .


➔ If exception is not handled then JVM Provides a default exception handle
that perform the following task .

(i) Print out exception description .


(ii) Print the stack trace .
(iii) Terminate the program .
➔ But if exception is handled by the application Program normal flow of the
exception is maintain that means the rest of code is executed .
Multi catch block:- it is defined as a try bock which is followed by one or
more catch block each catch blocks must be contain a different exception
handles. So if we have to perform different task the occurance of different
exception we use java multi catch block .
Note:- At a time only one catch block is executed . all catch blocks must be
ordered from most specific and most general come before catch for
exception .
Examples:- Public class example
{
Public static void main (string []args)
{
Try {
Int a =new int (5);
A[5] = 30/10;
}
Catch (arithmetic exception )
{
System.out.print (“Arithmetic exception occur”);
{
Catch (array index out of bound exception )
{
System.out.print(“_________occur”);
}
Catch (exception)
{
System.out.print(“parent exception occur”);
}
System.out.print(“out of try block”);
}
Why we use nested try block:-
Sometimes a situation may occur where a part of the block may cause one
error and the entire block itself may cause another error in such cases
exception handler have to be nested .
Throw Keyword:-it is used to explicitly throw an exception. We can throw
either check or uncheck exception .
It is mainly used to throw custom exception
Syntax:- throw exception
Throws Keywords :- is used to declare an exception and gives information to
the program that their may occur an exception so it is better for the
program to provide the exception handling is mainly used to handle the
check exception if their occur any uncheck exception such as “Null pointer”
exception .
It is programmer fault that he is not performing checkup before the being
used .
Syntax:-
Ret_type_method_name()throws excep-class name ..

You might also like