26.EXCEPTION HANDLING
27.MULTI THREADING
28.STREAMS
29.packages
30.AWT
31.APPLET
32.COLLECTIONS
EXCEPTION HANDLING:
******************
Exception is nothing but a an error.In the programming side we can
say Exceptionhandling is eradication that a problem occured during the program
Execution.
Exception handling is used to handle that exception.The recovery procedure
called an exception handling.java Exception handling prepares a program to know
all types of exceptions that are prefined.this makes programs more robust and performance.
java exception is an object that describes an error.when java system encounters an error
an error in a method while executing or compiling of its statements,an object is
prepared by java system and thrown.The thrown object can select its corresponding
handler whether it is system defined or user defined.if it selects system defined
cause's abnormal termination so that's why java provides a mechanism to define
handler for finding and handling such errors.
if avoid using exception handling,it reduces program clarity and performance
it helps to improve a program's fault tolerance
The style and details of exception handling mechanism similar to c++ but
predefined classes are not avilable in c++ where as avaliable in java.
Exception types:
****************
throwable
|
------------
| |
Error Exception
|
-------------
| |
checked unchecked
All Exception types are subclasses of the built-in class Throwable.Thus,
throwable is super class of all classes.it has two branches 'error' and 'exception'
but it is enough to know the developer about 'Exception' branch.'Error' branch is
for system designer. Exception are classified into two types that are checked and unchecked
exceptions.
keywords: try
catch
throw
throws
finally
try
{
statements;
}
catch(Exception e )
{
statements;
}
throw Exc....
throws Ex....
finally
{
statements;
}
multiple catch blocks: // care about exception types.
points:
1.ther is no try block without catch or finally blocks
2.the catch or finally blocks must be follwed by try blocks
3.do not apply any statements between try and catch blocks or finally blocks
4.more than one catch blocks can be defined with a single try block but only one
try block must be there.
5.finally blocks also not more can be defined.Only one is valid.
6.The statements that are defined after error caused statements are not executed
because the control cannot come back to try block.
7.nested try block are possible but try after try means multiple try blocks are
not possible.
8.catch block can be defined with only one exception class.
checked Exceptions:
ClassNotFoundException
CloneNotSupportedException
IllegalAccessException
InstantiationException
NoSuchMethodException
handling:
1.try catch
2.throws
unchecked Exceptions:
try catch
MULTITHREADING:
***************
what is multi threading?
Thread is nothing but a small program that can control another program.
Genarally a program has some stages that are start,process(going on) and stop.These
stages can be controlled by Thread.
An application can perform two are more tasks simultaniously.for example
a text editor can allow formating the text at the same time that it is printing.
Each of these independent subtask is called a thread and these two actions are being
performed by two separate threads is called multithreading.
multitasking: It is two types.It is supported all modern operating systems.These are
two distinct types of multitasking.process based(heavy weight) and thread based(light weight)
Two or more programs allows to run concurrentlyis called processbased.Multi
threading is also same but here program size is small.
java mt programing style allows you to write very efficient programs that
make maximum use of the cpu,because we can reduce idle time of the cpu.
c,c++ are single thread based.
Applications:
when a program downloads large audio video clips from internet,we need not
wait until the entire clip is downloaded.we can start the playback.for this two
threads are prepared,one for downloading the clips and another one is to play that.
Thread has some states:
start
Running
Suspended
Resume
Blocked
Terminated(stop)
how to create a thread:
thread can be prepared in two ways.
the most general form is to create thread is to get instatance for "Thread"
class that is available in "java.lang package" and with inteface 'Runnable' it is
also available in same package.
with class Thread
with interface Runnable
Thread class:
properties:
static final int MIN_PRIORITY(1)
static final int Max_PRIORITY(10)
static final int NORM_PRIORITY(5)
constructors:
Thread()
Thread(String name)
Thread(Runnable runnable_obj)
Thread(Runnable runnable_obj,String name)
methods:
Thread currentThread()// to get current thread
void start() //to start the thread
void run() // that is executed by thread
void stop() //to stop the thread
boolean isAlive()
void suspend()// to suspend the thread
void resume() // to resume the thread
void setPriority(int priority)// to set the priority
int getPriority() // to know the priority of the thread
void setName(String name)// to set name to thread
String getName() // to get the name of the thread
void sleep(milliseconds) throws InterruptedException
// to suspend thread execution some time that is mentiod
Runnable Interface:
It has only one method
public void run();
main Thread:
when a java starts up,one thread begins running immediatly.This is usually
called of main Thread.
1.the main method is the main thread that is main of other child threads means it is
not completed,the childs are completed.
2.It is the last thread to finish execution.when the main thread stops,your program
terminates.
3.The main thread is created automatically when your program is started.It can be
controlled through a Thread Object.
4.we can control main thread as like any other thread.
how to get the main thread:
currentThread() is method it returns the Thread object.
how to prepare thread with Thread class:
The first way,to create a thread is by extending "Thread" class and create
an instance of this class.The extending class must override the run() method,that
is entry point of new thread and it is activated by 'start()' method. the Thread
class has several methods to control the process.
run(): run() is a special method of Thread,actually it is method of Runnable
implemented in Thread class. it is activated by start() method.It is
overiden with the program that is controlled by the thread.So we can fill
this method with new programs.
Runnable Interface:
It is an interface provided by java to prepare a thread in another way
Sometimes class cannot be extended wIth "Thread" class(mostly in windows applicaion)
It has only one method run() must be implemented by subclass.But controlling of the
process is not availabe with this interface so,it must be linked with Thread class
to get actual thread strength.For this Thread has constructors.
Thread(Runnable obj);
Thread(Runnable obj,String name);
synchroniziation:
-----------------
when two or more threads need access to a shared resoure,they need some way
to ensure that it will be used one thread at a time.
class class-name
{
synchronized void methodname()
{
//statements;
}
}
once a thread enters into monitor,the object is blocked,no other thread can access
So after completion of one thread execution,another thread enters into monitor.
STREAMS:
*******
Flow of data is Stream
FILE:
1. All streams are defined in java.io takes operations on streams but the
class 'File' is gives information about files and file system.It has not capable
to get or set information in files,it describes about disk files.It gives such
as information of time,date,directory,path,size etc........
File class:
Constructors:
File(String filename)
File(String path,String filename)
File(File pathobj,String filename)
methods:
String getName()// to get the file name
boolean canRead()
boolean canWrite()
boolean exists()
boolean isDirectory()
boolean isFile()
boolean isHidden()
boolean delete()
long length()
int compareTo(File)
boolean setReadOnly()
so many methods are availabel in File...........
java defines two types of streams byte and character streams.
character Streams:
-----------------
it is used to handle the character based means text based input and outputs.
'Reader' and 'Writer' are the abstract super classes for all character streams.
Readers:
FileReader
BufferedReader
CharArrayReader
LineNumberReader
InputStreamReader
FilterReader
PushBackReader
PipedReader
StringReader
common methods for all above classes:
void close()
int read()
int read(char buffer[])
long skip(long num_char)
writers:
writer is an abstract class that helps to write character format into a file
writer classes:
BufferdWriter
CharArrayWriter
FilterWriter
OUtputStreamWriter
PipedWriter
StringWriter
PrintWriter
comman methods available in writer classes:
void write(char)
void write(char[])
void write(char[],int ,int)
void write(String)
void write(String, int, int)
void close()
FileReader:
java.io
FileReader is used to read data from textfiles
constructors:
FileReader(String filename)
FileReader(File fileobj)
methods:
common methods in Reader class
Constructors throws FileNotFoundException.
FileWriter:
java.io
to handle text files
constructors:
FileWriter(String filename)
FileWriter(File obj)
constructors throws IOException
methods:
common methods available in Writer class
ByteStream:
=========
This streams are used to read and write binary data such as images and sounds ,here also two
abstract classes are available that are Inputstream and OutputStream
InputStream(abstract)
FileInputStream
ByteArrayInputStream
SequenceInputStream
ObjectInputStream
LineNumberInputStream
DataInputStream
etc..
OutputStreams:
FileOutputStream
ByteArrayOutputStream
ObjectOutputStream
etc...
FileInputStream:
this class creates InputStream that can be accessed to read bytes from a file
constructors:
FileNotFoundException
FileInputStream(String str)
FileInputStream(File obj)
methods:
IOException
int read()
int read(byte[])
int read(byte[],int, int)
void close()
FileOutputStream:
it prepares a OutputStream that is used to write bytes into a file.
constructors:
filenotfoundException
FileOutputStream(String)
FileOutputStream(File)
methods:
void write(byte)
void write(byte[])
void write(byte[], int, int)
void close()
RandomAccessFiles:
with streams,either character based or byte based, user needs two streams for reading and
writing process.And also input stream can be read forward only .but RamdomAccessFiles
helps to perform read and write process in a single file and pointer can be moved to any where.
The RandomAccessFile class implements both the DataInput and DataOutput interface
constructors:
RandomAccessFile(String file,String mode)
RandomAccessFile(File obj,String mode)
first arguement is the file you want to access.
second arguements is the mode of access.
the mode should be either the String literal 'r' for readonly or 'rw' for
read/write operations.
java does not support writeonly access.
all throws IllegalException
methods:
long getFilePointer()
long length()
int read()
int read(byte[] data)
void write(int)
void write(byte[])
//to read and write primary types
boolean readBoolean()
byte readByte()
int readInt()
long readLong()
double readDouble()
String readLine()
void writeBoolean(boolean b)
void writeInt(int a)
void writeDouble(double value)
void close()
IOException
packages:
*********
java main feature is reusing the code if once created.if we need to use classes
from other programs without physically copying them into our program to development
this can be acomplishing using with packages in java.a concept as 'class libraries'
in other languages.
packages are java's way of grouping a variety of classes and interfaces together
The grouping is done according to functionality.package is nothing but container
for classes.
uses:
packages are two types:
java API packages(System)
user defined packages
java API:
lang
io
util
awt
net
applet
import packagename.[<sub-package>.]classname;// for single class importing
import packagename.[<sub-package>.]*;// for all classes importing in that package.
import java.lang.System
creating package:
-----------------------
package packagename;
public class classname
{
//body of the class
}
accessing the above class in our program:
import packagename.classname;
class ourclass
{
//body of this class
//statements using with the imported class
}
adding a class to package:
example:
adding one class :
package com.raju;
public class PackageP
{
public int sum(int a, int b){
return (a+b);
}
}
adding another class to that package:
package com.raju;
public class PackageP1
{
public int sub(int a, int b){
return (a-b);
}
}
Testing :
-----------
import com.raju.*;
public class TestP
{
public static void main(String[] args)
{
PackageP1 p=new PackageP1();
System.out.println(p.sub(19,34));
}
}
AWT PACKAGE:
************
Genarally applications are two types from the view of end user that are
CUI(console User Interface) generally used for console applications,and GUI
(Graphical User Interface) called windows applications.java provides these two types
of application interfaces.java provides awt to generate windows applications.
AWT stands for Abstract Windows Toolkit,provides windows components are
nothing but a reusable predifined classes that are generally visible in windows
environment are Frames,Labels,Buttons...................
AWT controls:
Lable
Button
TextField
CheckBox
RadioButton
List
Choicebox
so many components are available in awt.The all classes extends an abstract
class "Component".so they have some properties and behaviors that are
----------
String getName()// to get object name
void setName(String)// to set object name
boolean isVisible()//to know the component is visible or not
void setVisible(boolean)// to set visibility
Color getForegroung()// fo get foreground color of object
void setForeground(Color)// to set the foreground color
COlor getBackground()// to the background
void setBackground(Color)// to set the background color
Font getFont()// to get the font of the
void setFont(Font)//to set the font
void setLocation(int ,int)// for location setting
void setBounds(int, int, int, int)// to set the location and size of the compnents
void setSize(int, int)// for setting size of the components
void setResizable(boolean)// to handle resizable status of components
int getX()
int getY()
int getWidth()
int getHeight()
void setRequestFocus()
Frame:
------
Frame is predifined class that is available in java.awt package.It is a
top level window.It is a main Container that can contain other components like
buttons,labels and all components that are available in awt.
constructors:
Frame()
Frame(String) //with title
methods:
String getTitle()
void setTitle(string str)
boolean isResizable()
void setResizable(boolean)
Label:
------
Labels are passive controls they do not support user interaction.Labels are
used to display a static text.generally they are used to display the messages.
constructors:
Label()
Label(String caption)
Label(String caption,int alignment)
properties:
static final int LEFT
static final int RIGHT
static final int CENTER
methods:
int getAlignment()
void setAlignment()
String getText()
void setText(String)
Button:
-------
The button is most frequently used component in graphical applications.
When the user selects the button it signals the program that something needs to
be done.It has caption text and can generate an event.
constructors:
Button()
Button(String)
methods:
String getLabel()
void setLabel(String)
void setActionCommand(String)// to set the internal label of button obj
String getActionCommand()// to get internal label
void addActionListener(ActionListener)//method for event registration
TextField:
----------
Textfield is the text component for user input.This component is commonly
used for taking user input in windows application.
constructors:
TextField()
TextField(String)
TextField(int)
TextField(String, int)
methods:
void setText(String)
String getText()
int getColomns()
void setColumns(int)
char getEchoChar()
void setEchoChar(char)
Checkbox & RadioButton(Option button):
--------------------------------------
checkbox class is used to prepare checkboxes that helps to select more than
one selectio from a group.It appears as square textbox with tick property.User can
select by tick at the checkbox area.
RadioButton are also generally used as group but user can get only one
selection.java provides only one class to prepare both that is Checkbox.
`
Checkbox:
constructors:
for checkbox:
checkbox()
checkbox(String)
Checkbox(String, boolean)
for RadioButtoon:
checkbox(String, boolean, checkboxGroup)
checkbox(String, CheckboxGroup, boolean)
methods:
String getLabel()// to get label of checkbox/radiobutton
void setLabel(string) //to set caption to checkbox/radiobutton
boolean getStatus()// to get the status of checkbox/radiobutton
void setState(boolean)// to set the status of checkbox/radiobutton
Object[] getSelectedObjects()// to get selected objects from a group
List:
------
The List class provides compact multiple scrolling selection list.It supports
single selection and multiple selection.if user wants to visible more items from a
collection he can apply this control.
constructors:
List()
List(int)
List(int, boolean)
methods:
void add(String)// to add an item
void add(String, int)//to add an item at given position
void select(int)// to select particular item by index
int getItemCount()// to get howmany items the list object has.
int getSelectedIndex()//to get selected item index
int[] getSelectedIndexes()//to get selected items index(multi selection)
String getItem(int)//to get an item of given index
String getSelectedItem// get selected item
String[] getSelectedItems()//to get selected items inmultiple selection
void removeAll()// toremove all items
void removeString(String)// to remove given string
void remove(int)//to remove given index item
Choice:
-------
Choice class is used to prepare pop-up list(drop down list box).This is
combination of List and textfield.it is used for single selection but looks like
listbox when drop the list and once select the item it is going to looks like text
field.
constructor:
Choice()
method:
same as 'List' control....
LAYOUT MANAGERS:
----------------
A container or subcontainer should have a layout manager to place controls
in windows applications,Layout managers help to select controls proper place according
to its container.Layout manager are predefined classes and every container or
subcontainer has a method setLayout() to get Layout manager object.
FlowLayout
GridLayout
BorderLayout
FlowLayout:
properties:
FlowLayout.LEFT
FlowLayout.RIGHT
FlowLayout.CENTER
Constructors:
FlowLayout()
FlowLayout(int)
FlowLayout(int, int, int)//alignment, hori-gap,ver-gap
components adding method:
add(compnent)
GridLayout:
this layout place the components in two dimentional grid.
constructors:
GridLayout()
GridLayout(int, int)// rows,columns
GridLayout(int, int, int, int) // rows,columns,hori-gap,ver-gap
components adding method:
add(component)
BorderLayout:
This is common layout of top level window.It has five places.four narrow
edges and one larger center area.
properties:
BorderLayout.WEST
BorderLayout.EAST
BorderLayout.NORTH
BorderLayout.SOUTH
BorderLayout.CENTER
constructors:
BorderLayout()
BorderLayout(int, int)// hor-gap.ver-gap
components adding method:
add(component,int)
EVENT SOURCES:
Buttons,Checkbox,................
Listeners:
1.ActionListener:
It has one method and is received action events.
method:
public void actionPerformed(ActionEvent ae)
2.ItemListener:
It has one method and recognized the state of item.
method:
public void itemStateChanged(ItemEvent ie)
3.FocusListener:
it has two methods and recognize when components getfocus and loose focus
methods:
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
4.KeyListener:
It has three methods.
void keyPressed(KeyEvent ke)
void keyTyped(KeyEvent ke)
void keyRealesed(KeyEvent ke)
5.MouseListener:
It has five methods can recognized five mouse actions.
methods:
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
6.MouseMotionListener:
It has two methods and recognized dragged and moved.
method:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
7.WindowListener:
It has seven methods
methods:
void WindowActivated(WindowEvent we)
void WindowDeactivated(WindowEvent we)
void WindowClosed(WindowEvent we)
void WindowClosing(WindowEvent we)
void WindowIconified(WindowEvent we)
void WindowDeIconified(WindowEvent we)
void WindowOpened(WindowEvent we)
so many listeners are there...................
Adapter classes:
=============
public WindowAdapter implements WindowListener
{
void WindowActivated(WindowEvent we){}
void WindowDeactivated(WindowEvent we){}
void WindowClosed(WindowEvent we){}
void WindowClosing(WindowEvent we){}
void WindowIconified(WindowEvent we){}
void WindowDeIconified(WindowEvent we){}
void WindowOpened(WindowEvent we){}
}
ananimous:
========
a class is class is c
APPLET:
*******
Applet is window based program.So they are automatically becomes event driven.
java has two lives one is stand alone applications and second one is web applications.
The writen for general purpose is called application.Second is applet programing
that is executed in java compatable web browser.
Applets are small java programs.they are dynamic and interactive programs.
They can be transported over the internet from one computer to another computer
and run using the appletviewer or any browser that support java.
the difference of applications and applets is Application can be executed
with out GUI,where as applets can be excuted only in GUI.applications starts from
main() method.and applets cannot have the main method.
Applet life cycle:
Every java applet inherits a set of default behaviors from java.applet class
When applet is loaded,it undergoes a series of changes in it states.The life cycle
of applet depends on five methods that are
initilization state:init() :=
Applet enters the initilization state when it is first loaded.This is
achieved by calling init() method of applet.it is like constructor.
public void init(){}
running state:start():=
Applet enters the running state by calling start() method by applet.
public void start(){}
Idle or stopped state:stop():=
An applet becomes idle state when it is stopped from running.Stopping occurs
automatically when we leave the web containing currently running applet.
public void stop(){}
dead state:destroy():
An applet is said to be dead when it is removed from memory.This occurs
by invoking destroy() method.
public void destroy(){}
display state:paint(Graphics g):=
Applet moves to the display whenever it has to perform some output operations
on the screen.This is happen immediatly after the applet enters into the running state
public void paint(Graphics g){}// graphics is coming from awt to
// draw any diagram and text also
Simple Applet tag that can be placed in java program or HTMl page.
<applet code=javafile.class width=500 height=344> </applet>
Applet class:
constructor:Applet()
methods:
boolean isActive()
void reSize(int, int)
void showStatus(String)
void init()
void start()
void stop()
void destroy()
COLLECTIONS:
---------------------
we can handle a group of elements with arrys,. and but not different type of Objects.
so the main requirement is to store the different objects.to do this we have Collection framework.
A collection framework is a class library to handle groups of objects.Collection framework is
implemented in java.util package.
Collection object does not store the physical copies of other objects, since the other objects
are already in memory only jvm stores the references of other objects into a collection object.
Collection
Set
HashSet
LinkedHashSet
List
Stack
LinkedList
ArrayList
Vector
Queue
LinkedList
Map
HashMap<k,v>
Hashtable<k,v>
Set:
-----
A set represents a group of elements arranged just like an array, The set will grow dynamically
when the elements stored into it.
A set will not allow duplicate elements..if we tried to pass same element that is alread avaliable
in the set , then it is not stored into the set.
List:
-----
Lists are like Sets.They store a group of elements. But lists allow duplicate values to be stored.
Queue:
---------
A Queue represents arangments of elements in FIFO order.
Maps:
-------
Maps store elements in the form of key and value pairs.If the key is provided then its
corresponding value can be obtained, the keys should have unique values.
*****
*****
In all the cases the 'elements' refer to 'objects' only. This means we cannot store primitive
data types in the collection objects. We can store only objects since the main aim of collections
is to handle objects only. not the primitive data types.
Retriveing elements from Collections:
--------------------------------------------------
4 ways to retrieve any element from a collection object:
using for-each loop:
-------------------------
for(var: collection-object)
{
//statement
}
using Iterator Interface:
-------------------------------
Iterator is an interfac that contains methods to retrieve the elements one by one from
a collection object.It has 3 methods
-boolean hasNext()
-element next()
-void remove()
using ListIterator interface:
-----------------------------------
ListIterator is an interfce that contains methods to retrieve the elements from a collection
object, both in forward and reverse directions.
boolean hasNext()
element hasPrevious()
element next()
element previous()
void remove()
using Enumeration interface:
--------------------------------------
This interface is useful to retrieve one by one , the elements like the iterator. It has 2 methods.
boolean hasMoreElements()
element nextElement()
no remove method.
HashSet Class:
---------------------
boolean add(obj)
boolean remove(obj)
void clear()
boolean contains(obj)
boolean isEmpty()
int size()
LinkedHashSet class:
-----------------------------
sub class of HashSet class and its internally uses linked lists.
Stack class:
----------------
A Stack represents a group of elements stored in LIFO.
boolean empty()
element peek()
element push(element obj)
int search(Object o)
LinkedList class:
----------------------
A LinkedList contains a group of elements in the form of nodes. Each node will have
three fields. (same as double linked list)
Stack is generally used for the purpose of evaluation of expressions.
A LinkedList is used to store and retrieve data.
Insertion and deletion of elements only from the top of the Stack is possible.
Insertion and deletion of elements from any where is possible in case of LinkedList.
boolean add(element obj)
void add(int position, element obj)
void addFirst(element obj)
void addLast(element obj)
element removeFirst()
element removeLast()
element remove(element obj)
void clear()
element get(int pos)
element getFirst()
element getLast()
int size()
No comments:
Post a Comment