Вы находитесь на странице: 1из 137

CONCEPTS OF OOPS

&
JSE [CORE JAVA]

by:-MOHIT SINGH

Programming methodologies:The commonly used programming


methodologies are :Procedural programming
Object-oriented programming (OOP)

by:-MOHIT SINGH

Procedural programming:Involves dividing a large program into a set of

subprocedures or subprograms that perform a


particular task.
Module consists of single or multiple procedures.
Procedures are also known as functions, routines,
subroutines, or methods in various programming
languages.
Every function is interconnected to each other.
In this we can share our data anywhere within the
program only .we cannot access it outside the
program.
by:-MOHIT SINGH

Procedural programming:A procedure or a subprogram is a set of

commands that can be executed


independently.
Procedural programming is used for
developing simple applications. The
languages that use the procedural
programming methodology include Pascal and
C languages.

by:-MOHIT SINGH

Procedural programming:-

by:-MOHIT SINGH

Problem:In the procedural programming approach,


portions of the code are so interdependent
that the code in one application cannot be
reused in another.
For example,
the module used to calculate the salary of
the employees in a bank management system
cannot be used to calculate the salary of the
employees in an educational institute.
by:-MOHIT SINGH

>>
When you need to reuse the procedural
program in another application, a change in
the application results in rewriting a large
portion of the code.
This results in decreased productivity and
increased maintenance cost of the
application. This was one of the reasons that
led to the evolution of the object-oriented
approach.

by:-MOHIT SINGH

Object-oriented programming:In OOPS , we divide a large application in the

collection of the component objects. They interact to


each other.
The basic building block of the object oriented
programming are classes and objects.
Object orientation is a Software Development that is
based on modeling a real world.
The object-oriented programming methodology
enables maximum reuse of code for a programmer.
You can use the components of one program in
another. This enables the programmer to avoid coding
for similar components across programs.
by:-MOHIT SINGH

>>

by:-MOHIT SINGH

Advantages of OOPS:-

Real-world programming
Reusability of code
Modularity of code
Resilience to change
Information hiding

by:-MOHIT SINGH

>>
Real-world programming
The object-oriented approach models the real world
more accurately than the conventional, procedural
approach.
Reusability of code
In the object-oriented approach, you build classes,
which can be used by several applications.
Modularity of code
An object can be maintained independently of other
objects.
Resilience to change
Object-oriented programming also enables you to
evolve various versions of software.
When a change is suggested, the old system need not
be completely abandoned and re-built from scratch.
Information hiding
Information hiding ensures data security in a program.
by:-MOHIT SINGH

OOPS:Identify the features of object-oriented


programming:-

Encapsulation
Abstraction
Inheritance
Polymorphism
by:-MOHIT SINGH

Need of Java:-

The primary motive behind developing Java


language was the need for a portable and
platform-independent language that could be
used to produce code that would run on a
variety of Control Processing Unit(CPU) under
different environments. You can use Java to
develop network-oriented programs because
networking features are built-in features in
Java.
by:-MOHIT SINGH

Java Applications:A few types of Java applications are


CUI: Applications are executable programs that are
controlled by the operating system. These applications
have an access to the system resources, such as file
systems and can read and write to files on local
computers.
GUI: These applications are used in the Windows
environment. In GUI, you interact with the application
in graphical mode.
Applets: Applets are small executable programs that
run on a Web page. These programs require a Javaenabled browser. Applets have limited access to
system resources.
by:-MOHIT SINGH

>>
Servlets: Servlets are the programs that

are used to extend the functionality of Web


servers.
Packages: Packages are collections of

classes that can be reused by applications and


applets.

by:-MOHIT SINGH

Characteristics of Java:-

Simple
Object-oriented
Compiled and interpreted
Portable
Distributed
Secure
Robust
by:-MOHIT SINGH

How the Java Byte code and the JVM together make Java programs portable on
different platforms :-

by:-MOHIT SINGH

Objects:-

Objects are the basic runtime entities in

an object oriented system.


An object is a software package
consisting of variables and methods.
An object is defined as an instance of a
class.
Objects has the set of operations given in
the class.
by:-MOHIT SINGH

>>
An object means a material thing that is

capable of being presented to the


senses.
An object has three things:It has a state (variable) .
It has the behavior (function) .
It has a unique identity.

by:-MOHIT SINGH

Class:-

Class is the collection of objects of

similar type.
A class captures the common
properties of the objects instantiated
from it.
Class is just a Blueprint. It means it is
not having any physical appearance.
by:-MOHIT SINGH

For example:Car is the class.


Maruti, Honda, BMW are the objects.
Car positioned at one place define its state.
The number of car is the identity.

by:-MOHIT SINGH

>>

by:-MOHIT SINGH

>>
Girls have state , such as name, color, age,

and height
and
behavior such as walking, dancing, and

sleeping.

by:-MOHIT SINGH

Encapsulation:It is the process in that we hide the

irrelevant details of an object from the user.


With the help of that we provide the
security to the data as well as the methods
of a class.
For example:In playing video games, using vacuum
cleaner etc.
by:-MOHIT SINGH

An ATM user:-

by:-MOHIT SINGH

Abstraction:-

Abstraction is a process in that we

visualize the relevant details of an


object to the user.
To implement abstraction, you also use
the encapsulation feature. Encapsulation
hides the irrelevant details of an object
and abstraction makes only the relevant
details of an object visible.
by:-MOHIT SINGH

Inheritance:Enables you to extend the functionality of an

existing class.
Enables you to add new features and
functionality to an existing class without
modifying the existing class.
Enables you to share data and methods among
multiple classes.
You create a class that inherits the attributes
and behavior of another class. Attributes refer
to the data and behavior refers to the methods.
by:-MOHIT SINGH

Superclass & Subclass:In inheritance,


A superclass or parent class is the one from
which another class inherits attributes and
behavior.
A subclass or child class is a class that
inherits attributes and behavior from a
superclass.
A subclass may have some additional and
unique features in addition to the features
inherited from its superclass.
by:-MOHIT SINGH

For ex:-

by:-MOHIT SINGH

Relationships Between Classes:-

Kind-of
Is-a
Part-of
Has-a

by:-MOHIT SINGH

Types of Inheritance:Single Inheritance:- The subclass or

the child class inherits the attributes of


the parent class or super class.
Multiple Inheritance:- In multiple

inheritance, a subclass is derived from


more than one super class.
The subclass or the child class inherits
various attributes from its superclasses.
by:-MOHIT SINGH

For example:-

by:-MOHIT SINGH

Polymorphism:Polymorphism is derived from two words:-

Poly, which means many, and morph,


which means forms.
Any thing that exists in more than one
form is known as a polymorph.
Polymorphism enables an entity to have
more than one form depending upon the
context in which it is used.
by:-MOHIT SINGH

Java Programming Language and


class File:Java programs are saved with an extension,
.java.
A .java file is compiled to generate the .class
file, which contains the Byte code. The JVM
converts the Byte code contained in the .class
file to machine object code.
The JVM needs to be implemented for each
platform running on a different operating
system.
by:-MOHIT SINGH

The following figure shows the relationship


among various components of the Java
programming environment:-

by:-MOHIT SINGH

Java Virtual Machine:-

JVM for different platforms uses


different techniques to execute the Byte
code.
The major components of JVM are:
Class

loader
Execution engine
Just In Time (JIT) compiler

by:-MOHIT SINGH

Data type:The data stored in memory of the computer can be of


many types
The various data types in Java are:
Primitive or the simple data types (value
type)
Abstract or the derived data types
(reference type)

by:-MOHIT SINGH

Defining Variables:-

A variable is the name that refers to a


memory location where some data value is
stored.
Each variable that is used in a program
must be declared.
Types of Variables:

Class variables
Instance variables
Local variables
Static variables
Automatic variables
by:-MOHIT SINGH

Definining Literals:Literals are the values to be stored in

variables and constants.


A literal contains a sequence of characters,
such as digits, alphabets, or any other symbol
that represents the value to be stored.
Literals in Java:

Integer literals
Floating point literals
Character literals
String literals
Boolean literals
by:-MOHIT SINGH

Array:An array is a group of variables of the

similar data type.


Array is the special variable in that we
can store the more than one value of the
similar data type.
A specific element of an array can be
accessed by its index.
An array is a block of memory locations.
by:-MOHIT SINGH

Class:A class defines the attributes and


methods of objects of the same type
sharing common characteristics.
The main components of a class are:
Data members
Method

by:-MOHIT SINGH

Creating Classes in Java:Various data members and methods of a class are defined
inside a class. The statements written in a Java class must end
with a semicolon, ;. The following syntax shows how to declare
a class:
class ClassName
{
//Declaration of data members
//Declaration of methods
}
by:-MOHIT SINGH

An object is an instance of a class and has a

unique identity.
Creating
Classes:TheObjects
identity of anof
object
distinguishes it from
other objects.
Classes and objects are closely linked to each
other. While an object has a unique identity, a
class is an abstraction of the common properties
of various objects.
by:-MOHIT SINGH

To create an object, you need to perform the following


steps:
Declaration: Declares a variable that

holds the reference to the object.


class_name object_name;
Instantiation or creation: . The new
operator allocates memory to an object
and returns a reference to that memory
location in the object variable.
object_name= new
class_name();
by:-MOHIT SINGH

Methods:Methods are used to access the variables

that are defined in a class.


A method is an interface to a class.
Parameterized methods need some extra
information for its execution.
The extra information is passed to the
method by using arguments.
Arguments are also known as parameters of
the methods.
by:-MOHIT SINGH

Parameterized Methods:Parameterized methods use parameters to

process data and generate an output.


The output of a parameterized method is not
static and depends on the value of the
parameters passed.
<return_type> method_name(parameter_list)
{
statements;
return value;
}
by:-MOHIT SINGH

Method overloading is defined as the function

that enables you to define two or more methods


with the same name but with different signatures
Overloading
within the Methods:class.
The methods that share the same name, but have
different signatures are called overloaded
methods.

by:-MOHIT SINGH

The signature of a method (function) consists of:

The name of the method.


The number of arguments it takes.
The data type of the arguments.
The order of the arguments.

by:-MOHIT SINGH

Passing Arguments to a Method:Call-by-value: Copies the value of the actual

parameters to the formal parameters. Therefore,


the changes made to the formal parameters have
no effect on the actual parameters.
Call-by-reference: Passes the reference and not
the value of the actual parameters to the formal
parameters in a method. Therefore, the changes
made to the formal parameters affect the actual
parameters.
You can also pass arguments to the main()
method at the run-time of a program.
by:-MOHIT SINGH

Constructors:In Java, you can create constructors of the

classes that automatically initialize the


data members of the class when you
create an object.
A constructor is a method with the same
name as the class name.
A constructor of a class is automatically
invoked every time an instance of a class
is created.
by:-MOHIT SINGH

Characteristics of Constructors:There is no return type for a

constructor.
A constructor returns the instance of
the class instead of a value.
A constructor is used to assign values
to the data members of each object
created from a class.

by:-MOHIT SINGH

OVERRIDING METHODS:Method overriding is defined as creating a

method in the subclass that has the same


return type and signature as a method
defined in the superclass.
Signature of a method includes the name,
number, sequence, and type of
arguments of a method.
The created method of the subclass hides
the method defined in the superclass.
by:-MOHIT SINGH

Abstract Class:An abstract class is a class that cannot be instantiated.

It contains methods that have no implementation.


The methods having no implementation in the
abstract class are called abstract methods.
An abstract method is implemented in the subclass
instead of being implemented in the abstract class.
An abstract class is always inherited by other classes.
by:-MOHIT SINGH

Interface:Interfaces contain a set of abstract

methods and static data members.


Interface is known as a prototype for a
class.
Methods defined in an interface are only
abstract methods.
You can implement multiple interfaces in
a single class.
by:-MOHIT SINGH

>>
Interfaces also enable you to declare

constants that can be imported into


multiple classes.
The constant values declared in an
interface can be implemented in any
class.
The constants defined in an interface are
declared using the final keyword.
by:-MOHIT SINGH

>>
It is 100% abstract class. It contains two

things:Public static final variable(constant)


Abstract function

We cannot create object of interface. If a class is


implementing interface it means that class has
to define the body of all the functions of the
interface.
by:-MOHIT SINGH

>>
We cannot use the private and protected

before the class.

We can have a class inside a class that class

is known as inner class.


We can use all the access specifier before the
inner class because it is treated as a member.

by:-MOHIT SINGH

Component:Components are the visual controls such as

label, textbox etc.


There are three types of components:Top level component:-Acts as a container for placing
the intermediate-level and atomic swing components, such as
panels , frames, buttons, and check boxes .
Intermediate component:- Placed on the top-level
containers and contains atomic components..
Atomic component:-Placed on the intermediate-level
swing containers. Atomic components are used to accept input
from a user.
..

by:-MOHIT SINGH

Packages:-

Package is the collection of some

predefined classes and some interface.


If we do not use any package that time
java.lang package is automatically
called. This is default package.

by:-MOHIT SINGH

Abstract Window Toolkit:Provides capabilities for graphical user

interfaces.
This is basically used to do graphical programing.
The AWT defines windows according to a class
hierarchy that adds functionality and specificity
with each level.
The main purpose of the AWT is to support
applet windows, it can also be used to create
stand-alone windows that run in a GUI
environment, such as Windows
by:-MOHIT SINGH

>>
The API of the AWT package consists of a

collection of classes and methods that enables


you to design and manage the Graphical User
Interface (GUI) applications.
The AWT package supports applets, which
help in creating containers, such as frames or
panels that run in the GUI environment.

by:-MOHIT SINGH

Java Foundation Class(Swing):-

It is an extension of AWT.
Swings Components offer Cross Platform

Support it means if we create a button on


the windows operating system it would
same in all O.S. (in terms of look and
feel).

by:-MOHIT SINGH

>>
Swing components also provide GUI

environment to Java in addition to applets.


Swing components are a collection of
lightweight visual components that provide a
replacement for the heavyweight AWT
components.
The major difference between the lightweight
visual components and heavyweight visual
components is that lightweight components
have transparent pixels
by:-MOHIT SINGH

Java programs:Java programs are categorized into

applications and applets.


An application is a Java program that runs

by using the Java interpreter from the


command line.
Java applications support the Character User
Interface (CUI).

by:-MOHIT SINGH

Applet:An applet is a Java program that can be

embedded in an HTML Web page.


An applet is compiled on one computer and
can run on another computer through a Java
enabled Web browser or an appletviewer.
Applets are developed to support the GUI in
Java.
Applets programs always gets executed
inside the web browser so the web browser
must be java enabled.
by:-MOHIT SINGH

>>
Applets are basically web programming.

It is basically used to add the dynamic


aspects such as animation and sound to a
web.
Applets reduces the load on the web
server because they always execute
inside the web browser.

by:-MOHIT SINGH

Trusted and Untrusted Applets:The sandbox model of Java ensures the

security of Java code when an applet runs.


Being confined to the sandbox model, an applet

cannot perform functions, such as reading,


writing, or deleting files from the local file
system. This type of applet is known as an
untrusted applet.
A trusted applet enables you to perform
operations, such as reading and writing data to
a local computer. A trusted applet is digitally
signed by a trusted source.
by:-MOHIT SINGH

Applet class:-

The Applet class is a member of the Java

API package, java.applet.


You use the Applet class to create a Java
program that displays an applet.

by:-MOHIT SINGH

The following figure shows the hierarchical


representation of the Java classes:-

by:-MOHIT SINGH

>>

by:-MOHIT SINGH

>>

by:-MOHIT SINGH

>>

by:-MOHIT SINGH

Or:-

by:-MOHIT SINGH

Applet States:-

Every applet inherits a set of default

behaviors from the Applet class.


As a result, when an applet is loaded, it
undergoes a series of changes in its
state.

by:-MOHIT SINGH

The applet states include: Initialisation(init):-invoked when applet is

first loaded.
Running(start):-for the first time, It is
automatically called by the system after
init() method execution. It also invoked
when applet moves from idle/stop() state to
active state.
Display(paint):- it happens immediately
after the applet enters into the running
state. It is responsible for displaying output.
by:-MOHIT SINGH

>>
Idle(stop):- it is invoked when the applet

is stopped from running. It occurs when


we leave a web page.
Dead(destroy):- this occurs
automatically by invoking destroy method
when we quite the browser.

by:-MOHIT SINGH

HTML:The Hyper Text Markup Language.


The language used to design web pages.

In HTML , elements are of two types:1. Container:- are those which having the
start tab and end tab.for ex:<html>..</html>
2. Empty:- are those which are having only
start tab. For ex:-<br/> , <body
bgcolor=value>
by:-MOHIT SINGH

Layout Managers:The layout managers are used to position the

components, such as an applet, a panel, or a frame


in a container.
The
layout
managers
implement
the
java.awt.LayoutManager interface.
A layout manager is an instance of the
LayoutManager interface in Java.
You can use the following method to apply the
desired layout to the components:
void setLayout(layoutManager obj)

>>
Java has various predefined classes of

layout managers.
All layout managers make use of the
setLayout() method to set the layout of
a container.
If the setLayout() method is not used,
then the default layout of the
container is set.

FlowLayout Manager:The

flow layout is the default layout


manager used for the Applet class.
In the flow layout manager, the components
are placed in a container window in a
sequence one after the other in rows.
Java provides the FlowLayout class to apply
flow layout to the various components that
you are inserting in an applet.
You can use the following constructors to
create an instance of the FlowLayout class:
FlowLayout()
FlowLayout(int align)
FlowLayout(int align, int hgap,int vgap)

BorderLayout Manager:BorderLayout is the default layout of the Frame class.


The BorderLayout layout manager divides the

container into north, south, east, west, and centre


regions.
Java provides the BorderLayout class to apply the
border layout to the components.
The setLayout() method is used for applying border
layout to a container.
You can use the following constructors to create an
instance of the BorderLayout class:
BorderLayout()
BorderLayout(int h, int v)

GridLayout Manager:The grid layout is the layout that divides the container

into rows and columns.


The intersection of a row and a column of the grid
layout is called cell.
The GridLayout class of Java enables you to create a
grid layout.
All the components in a grid are of the same size.
You can use the following constructors to create an
instance of the GridLayout class:
GridLayout()
GridLayout(int r, int c)
GridLayout(int r, int c, int h, int v)

GridBag Layout Manager:The

GridBag layout manager divides a


container into a grid of equally sized cells. In
the GridBag layout, a component can extend
over multiple rows and columns.
You specify the position of each component by
specifying its x and y coordinates.
You can resize the component by assigning
weights to the components in the GridBag
layout. Weights specify the horizontal and
vertical space required to fill the display area of
a container.
The constructor to create an instance of the
GridBagLayout class is:
GridBagLayout() g = new GridBagLayout();

>>
You need to specify the constraints for

each component, when you want to size


and position the components.
You apply the constraints in the GridBag
layout manager by using the
setConstraints() method.
GridBagConstraints(): Creates a
GridBagConstraints object with the default
values for the gridbag layout attributes.

Event Handling:An object that describes a change of state in a source

component is called an event.


The source components can be the elements of the
Graphical User Interface (GUI).
Identifying the Source Of Events:An event source is an object that generates an event.
An event source registers some listeners, which receive

notifications about a specific type of event generated by that


particular event source.

by:-MOHIT SINGH

>>
All the registered listeners are notified about the

generation of an event and receive a copy of the event


object. This is known as multicasting the event.
Some sources allow only single listener to register.
This is known as unicasting of event.
Event sources also provide methods to
unregister the event listeners. The
notification about the event generation is
passed only to the registered listener.
by:-MOHIT SINGH

Sources:-

Checkbox
Button
List
Text components
Scrollbar
Window

by:-MOHIT SINGH

Event Listeners:An event listener listens for a specific event and is

notified when that specific event occurs.


An event listener registers with one or more event
sources to receive notifications about specific types
of events and processes the events.

by:-MOHIT SINGH

Event Handlers:An event-handler is called by the event listener whenever

a specific event occurs.


Event listeners are interfaces and the event-handler is a
method declared in the event listener interface that is
implemented by the application.
The syntax of a method that registers an event listener
with an event source is:
public void addTYPEListener(TYPEListener obj)

by:-MOHIT SINGH

The Delegation Event Model:The delegation event model is based on the

concept that source generates the event and


notifies one or more event listeners.
The delegation event model allows you to
specify the objects that are to be notified when a
specific event occurs.
In delegation event model, the event listener has
to be registered with a source in order to get
notified about the occurrence of a particular
event.
by:-MOHIT SINGH

Event Classes:-

by:-MOHIT SINGH

Action Event class:ActionEvent is generated by an AWT

component, such as a button, when a


component-specific action is performed.
The action event is generated when a button
is pressed, a list item is double-clicked, or a
menu item is selected.
The following syntax shows the declaration of
the constructor of the ActionEvent class is:
public ActionEvent(Object source, int id, String
command)
by:-MOHIT SINGH

>>
The main methods included in the

Action Event class are:


String getActionCommand()
int getModifiers()

by:-MOHIT SINGH

MouseEvent:The MouseEvent class extends the

java.awt.event.InputEvent class.
The mouse event indicates that a mouse
action has occurred on a component.
The MouseEvent class is used for both,
mouse events and mouse motion events.
The mouse event class defines some
integer constants that can be used to
identify several types of mouse events.
by:-MOHIT SINGH

>>
The mouse events include:
Pressing a mouse button
Releasing a mouse button
Clicking a mouse button
Entering of mouse in a component area
Exiting of mouse from a component area

The mouse motion events include:


Moving a mouse
Dragging a mouse

by:-MOHIT SINGH

>>
The syntax of one of the constructors of the

MouseEvent class is:


public MouseEvent(Component source, int
eventType, long when, int modifiers, int x, int y, int
clickCount, boolean triggersPopup )

by:-MOHIT SINGH

>>

by:-MOHIT SINGH

Event Listener Interfaces:ActionListener:- Defines the

actionPerformed() method to receive and


process action events.
MouseListener:- Defines five methods to
receive mouse events, such as when a mouse is
clicked, pressed, released, enters, or exits a
component.
MouseMotionListener:- Defines two methods
to receive events, such as when a mouse is
dragged or moved.
by:-MOHIT SINGH

>>
AdjustmentListner:- Defines the

adjustmentValueChanged() method to receive


and process the adjustment events.
TextListener:- Defines the
textValueChanged() method to receive and
process an event when the text value changes.
WindowListener:- Defines window methods
to receive events.
ItemListener:- Defines the
itemStateChanged() method when an item has
been selected or deselected by the user.
by:-MOHIT SINGH

Adapter Classes:The Java programming language provides adapter

classes, which implement the event listener


interfaces containing more than one event-handling
Method.
An adapter class provides an empty implementation
of the event-handling methods in an event listener
interface.
The adapter classes are useful because they allows
you to receive and process only some of the events
that are handled by a particular event listener
interface.
by:-MOHIT SINGH

>>
You can define a class that acts as an

event listener by extending one of the


adapter classes and overriding its
methods to handle a particular type of
event.

by:-MOHIT SINGH

Adapter Classes: KeyAdapter:- Provides empty implementation of the

methods of the KeyListener interface.


MouseAdapter:-Provides empty implementation of the
methods of the MouseListener interface.
MouseMotionAdapter:-Provides empty implementation
of the methods of the MouseMotionListener interface.
WindowAdapter:-Provides empty implementation of the
methods of the WindowListener and WindowFocusListener
interfaces.
FocusAdapter:-Provides empty implementation of the
methods of the FocusListener interface, such as
focusGained() and focusLost() methods for receiving
keyboard focus events.
by:-MOHIT SINGH

Exception Handling:The term exception in Java indicates an

exceptional event.
An exception can be defined as an abnormal
event that occurs during program execution
and disrupts the normal flow of instructions.
Errors in a Java program are categorized into
two groups:
Compile-time errors
Run Time errors

by:-MOHIT SINGH

>>
Concept of Exceptions:The unexpected situations that occur during

program execution are:


Running out of memory
Resource allocation errors
Inability to find files
Problems in network connectivity

by:-MOHIT SINGH

Exception hierarchy:-

by:-MOHIT SINGH

>>
Throwable Class:- The Throwable class is a

subclass of the Object class. The Throwable


class is the superclass of all the exception
objects that are thrown in Java.
Exception Class:- The Exception class has
various subclasses, such as
ClassNotFoundException, IllegalAccessException,
and RuntimeException.
Error Class:- The Error class defines exceptions
related to the Java run-time environment.
by:-MOHIT SINGH

>>
The built-in exceptions in Java are

categorized on the basis of whether the


exception is handled by the Java
compiler or not. Java consists of the
following categories of built-in
exceptions:
Checked Exceptions
Unchecked Exceptions

by:-MOHIT SINGH

Checked exceptions:Checked exceptions are the objects of the

Exception class or any of its subclasses


excluding the Runtime Exception class.
Checked exceptions are the invalid
conditions that occur in a Java program
due to invalid user input, network
connectivity problem, or database
problems.
by:-MOHIT SINGH

Unchecked exceptions:Unchecked exceptions are the run-time

errors that occur because of


programming errors, such as invalid
arguments passed to a public method.
The Java compiler does not check the
unchecked exceptions during program
compilation.

by:-MOHIT SINGH

>>
You can implement exception-handling

in a program by using the following


keywords:
Try
Catch
Throw
Throws
finally

by:-MOHIT SINGH

try and catch statements:The try block encloses the statements

that might raise an exception within it


and defines the scope of the exception
handlers associated with it.
The catch block is used as an
exception-handler. You enclose the code
that you want to monitor inside a try
block to handle a run time error.

by:-MOHIT SINGH

Multiple catch statements:A single try block can have many catch

blocks. This is necessary when the try


block has statements that raise different
types of exceptions.
The multiple catch blocks generate
unreachable code error.
To avoid unreachable code error, the last
catch block in multiple catch blocks must
contain the Exception class object.
by:-MOHIT SINGH

Finally:-

The finally block executes whether or

not an exception is raised.


If an exception is thrown, the finally
block executes even if no catch
statement matches the exception.

by:-MOHIT SINGH

throw statement:The throw statement causes termination of the

normal flow of control of the Java code and stops


the execution of the subsequent statements if
an exception is thrown when the throw
statement is executed.
The throw clause transfers the control to the
nearest catch block handling the type of
exception object throws.
The following syntax shows how to declare the
throw statement:

throw ThrowableObj
by:-MOHIT SINGH

throws statement:The throws statement is used by a

method to specify the types of


exceptions the method throws.
If a method is capable of raising an
exception that it does not handle, the
method
must
specify
that
the
exception has to be handled by the
calling method.
by:-MOHIT SINGH

Difference:The throw statement causes termination of

the normal flow of control of the Java code


and stops the execution of subsequent
statements after the throw statement.
The throws clause is used by a method to
specify the types of exceptions thrown by the
method.
The throw keyword throws a new exception
whereas the throws keyword refers to a
method that throws an exception.
by:-MOHIT SINGH

super keyword:Java provides the super keyword that

enables a subclass to refer to its


superclass. The super keyword is used to
access:
superclass constructors
superclass methods and variables

The syntax to invoke the constructor of a

superclass using the super() method is:


super (<parameter1>, <parameter
2>,..,<parameterN>);
by:-MOHIT SINGH

>>
If no parameters are passed to the super()

method, it invokes the default constructor of


the superclass.
If the superclass contains the overloaded
constructor, you can pass parameters to the
super() method to invoke a particular
constructor.
When you use the super() method in the
constructor of the subclass, it should be the
first executable statement in the
constructor.
by:-MOHIT SINGH

>>
The syntax to access the member

variable of a superclass is:


super.<variable>;

The subclass can also access the

member methods of the superclass


using the super keyword.

by:-MOHIT SINGH

this Keyword:The this keyword is used to refer to the

current object.
You can use the this keyword when a
method defined in a Java class needs to refer
to the object used to invoke that method.
Another situation where you can use the this
keyword is when the local and instance
variables have the same name.
In addition, you can use the this keyword in
a constructor of a class to invoke another
constructor of the class.
by:-MOHIT SINGH

>>
Unlike the super keyword, the this keyword

can invoke the constructor of the same class.


The following code snippet shows how to
invoke a constructor using the this keyword:
class Book {
public Book(String bname) {
this(bname, 1001); }
public Book(String bname, int bcode) {
bookName=bname;
bookCode=bcode;
}}
by:-MOHIT SINGH

final Keyword:The final keyword can be used with:


A variable
A method
A class

The use of the final keyword prevents you

from changing the value of a variable.


When you use the final keyword with a
variable, the variable acts as a constant.
It is recommended that you name the final
variable in uppercase.
by:-MOHIT SINGH

>>
The syntax to declare the final variable is:
final int MY_VAR=10;

In the above syntax, the MY_VAR variable is

declared as final. As a result, the value of the


variable cannot be modified.
The final keyword is used with methods and
classes to prevent method and class overriding
while implementing inheritance in a Java
application.
If a method in a subclass has the same name
as the final method in a superclass, a compile
time error is generated.
by:-MOHIT SINGH

>>

The following syntax shows how to declare

the final method:


class SuperClass
{
final void finalMethod()
{}
}

Similarly, if a class is declared final, you

cannot extend that class.


If you extend the final class, a compile time
error is generated.
by:-MOHIT SINGH

Thread:Heavy weight and light weight


process:Heavy weight processes are those
process those are directly interacting with
operating system.
Light weight process are those process
those are executing inside a process.
A Thread is defined as a execution of

Program.
by:-MOHIT SINGH

>>
If a process is made of one thread is

known as single threaded process.


If a process that creates two or more
threads is known as Multithreaded
process.
In a program, if we want to achieve the
multithreading concept that time we
inherit the thread class or enable the
runnable interface.
by:-MOHIT SINGH

>>
Runnable is the predefined interface it

comes in the java.lang package. It has


got only one function that is run().
Start is the predefined function of the
thread class. Once we call the start
function, it automatically call the run
function on a different thread.

by:-MOHIT SINGH

Life Cycle of thread:New State


Runnable State:- once we call the start()

function, thread comes from the new state


to runnable state.
Running State:- once thread is executing
the run function that state is known as the
running state.
Not Runnable State:- it is also known as
the waiting, blocked and sleep.
Terminated and Dead Condition
by:-MOHIT SINGH

File Handling:-

File is the predefined class, it comes in

the java.io package, with the help of


that we can create a new file, folder,
we can remove and delete the folder
also.
We cannot read and write the data
with the help of the file class.

by:-MOHIT SINGH

>>
File class does two operations:If file is not there it just create the logical file.
If file is already there it just open that file in the
memory.

createNewFile is the predefined function

of the file class it creates a new file if file


is not there.
If file is already there it would not create
there.
by:-MOHIT SINGH

>>
read is the predefined function , it accept a

single character at a time but it returns the


int type value.
So if we dont write (char) in the
System.out.println then they can give the
int value of that character.
There are three overloaded function of
read:read ()
read (byte[])
read (byte[],int offset, int length)

by:-MOHIT SINGH

>>
We can read & write the data in a file in

two format:Binary
Character

When we have the large data such as

image file, jar file etc. that time we should


use the binary format.
But when we have some small text file that
time we should use the character format.
by:-MOHIT SINGH

>>
For writing and reading in the binary

format we have two classes:Output Stream


Input Stream

Both classes are the abstract classes.

by:-MOHIT SINGH

>>
File Input Stream is the predefined class it

is inherited from the input Stream class


with the help of that we can read the data
from the file.
File Output Stream is the predefined class
it is inherited from the output stream class
with the help of that we can do two job:We can write the data in a file.
It creates a file if file is not there.

by:-MOHIT SINGH

>>
When we want to read and write the data in the
character format that time we use two classes:Reader class
Write class

Both classes are abstract classes.


Syntax of reader class:File reader f=new File reader(mohit.txt);
int ch;
While((ch = f.read()!=-1)
{
S.O.P((char)ch);
}
by:-MOHIT SINGH

>>
Syntax of writer class:String str=character stream classes in java;
File Writer fout= new File Writer(evening.txt);
Fout.write(str,0,str.length());
Fout.close();

by:-MOHIT SINGH

>>
File Reader and File Writer are the low
level classes but Buffered Reader and
Buffered Writer are the high level
classes.

by:-MOHIT SINGH

Вам также может понравиться