Está en la página 1de 157

History

In 1990 ,Sun Microsystem began a project called GREEN to


develop software for consumer electronics..It took 18 months to develop the
first working version .This language initially called Oak ,but was
renamed to Java in 1995.

Java was conceived by James Gosling ,Patrick Naughton ,Chris Warth ,Ed
Frank and Mike Sheridan ,in 1991 Gosling began writing software in C++
for embedding into such items as toasters,VCRs etc.The embedded
software makes appliances more intelligent ,typically by adding Digital
display or by using Artificial Intelligence to better control mechanism
.However ,it soon become apparent to Gosling that C++ was wrong tool for
the job . C++ is flexible enough to control embedded systems ,but it is
susceptible to bugs that can crash system .In particular ,C++ uses direct
references to system resources and requires programmer to keep track of
how these resources are managed ,which is significant burden on
programmers.This burden of resource management is a barrier to writing
reliable ,portable software ,and it is serious problem for consumer
electronics.

Java offer two flavors of programming Applet and


Application
An application is a program that resides in the
Hard Disk of your machine. When the
application needs to be executed it is fetched
from the hard disk into the internal memory
and executed. This application is a stand-alone
program all the resources that it requires, like
run time libraries are available locally.
An applet can reside on a remote machine. When
the local machine needs to execute , the applet
is fetched from the remote system into the
internal memory of the local machine Once
available on the local machine it is interpreted
and linked to the libraries locally by the
browser and executed.

Features
Java is a simple object oriented distribute,
interpreted, robust, secure, architectural, portable,
high performance, multithreaded, and dynamic
language.

Simple
It can learn easily. A JAVA programmer need not
know the internal of java.
Object-oriented
Java defines data as object with method that supports
the objectoriented. Java is purely objectoriented.
Any codes you write ,you have t write in Class.
Distributed
Java programs can access data across the web as
easily as they access data from a local system. Contd

Interpreted and Compiled


Java is both interpreted and compiled. A java
applet is written and compiled into what is called
bytecode. This byte code is binary and platform
independent. When this applet has to be executed it
is fetched to the local system where it is interpreted
by the browser.
Only 80% is compiled and 20% interpreted when
executed ,this is because security purpose .
Java environment contains an element called the
linker .The linker checks the coming data into your
machine to make sure it does not contain
deliberately harmful files or files that could disrupt
the functioning your computer.

Architecture Natural
Java can work with a variety of hardware and
operating system. The only requirement is that the
system should have java enabled Internet browser.
Robust
Robust means reliable.A reliable language will allow
you to write programs that dont crash when least
expected and will also be bug free.
Java is secure
A program traveling across the Internet onto your
machine is unseen by you and could possibly be
carrying a virus along with it. This is a possibility in
java program . But due to strong type checking done
by java on the users local machine, any changes to the
program are tagged as an error the program will not
executed.

Multithreaded
Ability of an applet to perform multiple tasks at the
same time. For e.g.; suppose you are playing a
game one thread displaying score, one graphics. In
single threaded applet only one task can be
performed at a given point of time.
Dynamic
A java program can consist of many modules that
are written by many programmers. These modules
may undergo many changes. Java makes
interconnection between modules at run time ,
which easily avoids the problem caused by the
changes of the code used by your program java
thus dynamic.

Process by which java sources code files are compiled and


interpreted.

Source Code Java Compiler


ByteCode
(ASCII FILE)
(JAVAC)
(CLASS
FILES)
Application/Applet

Bytecode is a standardized, machine


independent low level language. The
bytecode files are loaded,interpreted at
the client machine by a special program
called Java Virtual Machine [JVM] .

Basic Java Application

//This is first program of Java


public class MyFirstProg
{
public static void main(String args[])
{
System.out.println(This is first
program);
}
}
Let us check it line by line:

Line 1:This line is called comment entry ,which will be


ignored by the compiler.They make program more
readable .For multiple line it is /*..*/
Line 2:In java everything should be in class which is
declared using the keyword class . Public means your
class is available and accessible by any one .
Line 3:MyFirstProg is the name of the class .
Line 4:Main() is the entry point of your program i.e;
programs execution starts from here .
Line 5:System.out.println is used to print anything on
the console
{} defines the scope of any method / class
; line terminator

Saving File:
Primary name of file must be same as the
the name of class and extension must be
java.For eg: MyFirstProg.java

Compilation:
javac MyFirstProg.java
After compilation it creates .class file which is
bytecode format

Execution:
java MyFirstProg

Declaring Variables

Syntax:
<Data Type> <Name of Variable>
Data Type:
It says what type of value the variable going to
hold . It is of two types:
1. Primitive/Standard
They are built into the Java language.
2. Abstract/Derived
They are based on primitive data type and
have more functionality than primitive data
type.For e.g; String
Contd

Data Type

Primitive
Data
Type
Description
Size
Range

byte

Byte-length
Integer

1 Byte

-128 to 127

short

Short Integer

2 Bytes

-32,768 to 32,767

int

Integer

4 Bytes

-2,147,483,648 to
2,147,483,647

long

Long Integer

8 Bytes

-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807

float

Floating-point 4 Bytes

-3.402824347*1038 to
3.402824347*1038-1

double

Double
Precision

8 Bytes

-1.79769313486231570*10308
to
1.79769313486231570*10308-1

char

Character

1 Byte

0 to 255

boolean

A Boolean
Value

1 Bit

True/false

Variable Declaration:
<Data Type> <Name of variable>
int Salary;
String Name;

Initialization:
Salary=5000;
Name=Rani;

Identifiers:
Are the name of variables , methods , classes
, packages.Identifiers must be composed of
letters , numbers the underscores and the
dollar sign .You cannot begin a identifier
with a number.

Operators
They are used to compute and compare values and
test multiple conditions.They are:
Arithmetic: +,-,*,/,%
Assignment:
=,+=,-=,*=,/=,%=

Logical: &&,||,?:
Comparison:
==,>,>=,<,<=,!=

Unary: ++,-- (prefix & postfix)


new: to allocate memory for the instance of class

Programming Constructs
They are used to alter the path of execution of the
program.It is divided into:

Conditional
Iteration

if .. else Construct
This is used to check the condition.Its Syntax is:
if(condition)
Do Some action
This returns true if the checked condition is true otherwise false

class Hello
{
public static void main(String args[])
{
int iVar1=20, iVar2=10;
if (iVar1>iVar2)
System.out.println(iVar1 is greater than
iVar2);
}

switch..case Construct

Is used to successively test the value of an expression against a list of integer or


character constants.Only integer or character can be passed.

class Hello
{
public static void main(String args[])
{
int I=0;
switch(I)
{
case 0:
System.out.println(Value is Zero);
case 1:
System.out.println(Value is One);
case 2:
System.out.println(Value is two);
default:
System.out.println(None of the condition is true);
}
}
}

Iteration Construct
Loop Constructs:
Are used to repeat a section of the
program a certain number of times
Are categorized as:
while
do..while
for

while Loop
Repeats the body of the loop as long as the loop
condition is true
class Hello
{
public static void main(String args[])
{
int iNum=1;
while ( iNum<=100)
{
System.out.println(iNum);
iNum= iNum +1 ;
}
}

do..while Loop
Executes the body of the loop at least once
Tests the expression at the end of the loop
Takes the form:
do
{
.
.
.
} while(Condition test);

for Loop
Is used for fixed iterations.Syntax is :
for(initialization,condition,step value)
class Hello
{
public static void main(String args[])
{
int iVar;
for(iVar=1; iVar<=10; i++)
{
System.out.println(iVar * iVar);
}
}
}

for Loop (contd.)


The statement:
for(iVar=0; iVar<=10; iVar++)
consists of three parts:
iVar=0 is the initialization expression,
iVar<=10 is the test expression and
iVar++ is the increment expression

break Statement
Is used to terminate a case in a switch
construct
Is also used to terminate a loop
construct

continue Statement
Is used to skip all subsequent
instructions in a loop and take the
control back to the beginning of loop

Array
Are a collection of elements of the same
type and referenced by a common name
Elements of an array are referred to by
an array name and a subscript
Array subscript starts from zero
All elements in an Array must of the same
data type
Mainly used for grouping related
information

Declaration

There are two ways to declare:


Place a pair of bracket after the
variable type .
Place brackets after the identifier
name.
int MyIntArray[];
Or
int []MyIntArray;

Allocation of Space and Data Placement

To allocate space ,the new


keyword followed by the variable
type and size is required.
new elementType[arraySize]
To place data :
<name of Array<[subscript]=<value>;

One-dimensional Arrays
Example:
int Num;
Num=new int[10];
In the example, a int array called
Num has been defined, which holds
10 numbers.

Initializing Array

Array can be initialize as:


Num[5]=10;
Num[10]=11;
int Num[]={10,20,30,40,50};

Getting the Size of an Array


To get the size of an array:
arrayname.length
class ArrayDemo

{
public static void main(String args[])
{
int num[];
num=new int[5];

System.out.println("Size is :"+num.length);
}
}

Double Dimensional Array


Single dimensional made up of
either row or column.
Is made up of rows and columns.
Each element can be accessed by
row and column subscripts.

Two-dimensional Character Array


Declaration

char arrayname[x][y];
where:
x: is number of rows
y: is number of columns

Initializing Two-dimensional Arrays


char Weekdays[7][10] = {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
};

Object-Oriented Language
A language which supports the following
features:
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
It combines both data and the functions into a
single unit called an object
Offers data encapsulation
Is used to create Abstract Data Types

Characteristics of Object-oriented
Language

Realistic in Nature
Reusability of code
Resilience to Change

Class
A class is a Blue Print/Prototype that defines the variables and the methods common to all
Objects of certain kind.
In the real world, you often have many objects of the same kind. For example: Your Bicycle
is really just one of the many Bicycles in the world .If we talk in language of Object
Oriented terminology, we say that your bicycle object is an instance of the class of Objects
known as BICYCLES. All objects have some state (Current gear, current cadence, two
wheels) and behavior (changing gears, braking) in common.
When producing bicycles, manufacturers take advantage of the fact that bicycle from the
same blueprint -it would be very inefficient to produce a new blueprint for every individual
bicycle manufactured.
Software "blueprints" for objects is called CLASSES. For e.g.; you could create the bicycle
class that would declare several variables to contain the current gear, the current gear
cadence etc. It would also declare and provide implementations for the methods that allows
the rider to change gears ,brake and change the pedaling cadence.
The values for variables are provided by each instance of the class .So after youve created
the bicycle class, you must instantiate it(Create instance of it) before you can use it .when
you create an instance of class , the variable declared by class are allocated space in the
memory.
BENEFIT:
Reusability of Code.

Syntax
It is collection of member variables and functions.It is
created using the keyword class . A class declaration
defines a new type. This new type is then used to
declare objects of that class . Thus a class is a logical
abstraction , but an object has physical existence .An
object is an instance of a class.

[access specifier][modifier]class <classname>


{
statements
}

Example
class MyClass
{
int RegNo;
String Name;

VARIABLES

}
Class defines a type of data.Here it is MyClass
Note:Class declaration only creates template; it
does not create an actual object

Defining the Object


An object is an instance(example) of a class
Syntax:
<ClassName> <objectname>;
<objectname>=new <ClassName>;

MyClass my;
my=new MyClass();
Note:All objects share the same copy of the member
functions but maintain a separate copy of the
member data.

Accessing Members of Class

The .(dot) operator


Is used to access the members.
Associates the object name and the
members.For eg, If you want to assign
the value 5 to RegNo you would use:
My.RegNo=5;

Methods
Methods
are
used
to
perform
operation/action. The general form is :
<type> <method name> (parameter-list)
Type:Type of data returned by the
method.It may return any valid data type ,
and if it does not return any data , type is
void.

class MyClass
{
int RegNo;
String Name;
void accept()
{
RegNo=5;
Name=Deepu;
}
void display()
{
System.out.println(Registration NO.:+RegNo);
System.out.println(Name is :+Name);
}
public static void main(String args[])
{
MyClass my=new MyClass();
my.accept();
my.display();
}
}

Constructor
A Constructor initializes an object immediately upon
creation.It has same name as the class in which it
resides and is syntactically similar to method.Once
defined it is called automatically when a new object of
the class created.It does not return any value.
Class Hello
{
public Hello()
{
S.O.P(Hello);
}
}

Access Specifiers

It determines which feature of a class (class,data


members and methods) may be used by another
classes.Java supports three access specifiers (access
modifiers):
Public:Accessible everywhere.We can also define public
data members and methods.
Private:Only objects of the same class can access a
private variable or method.We can only declare
variables,methods, and inner class as private.
Protected:Are accessible only to the subclasses of the
class in which they are declared.
Friendly:If user fails to specify any specifier by default
it is friendly(not a keyword).Same as public specifier,but
only in same package.

Modifiers
They determine how data members are used in
other objects.
Static:By default , member variable/function of
any class dependent on class.If want to make it
independent of any objects of that class.
Final:To
declare
the
variable
as
constant(unchangeable)
Abstract:When applied to a class , it indicates
that the class has not been fully implemented and
that it should be instantiated .If applied to a
member function declaration,the abstract
modifier means that the function will be
implemented in a subclass.

Synchronized:Used
with
multi
threads.Allows only one thread to execute
the function at a time.

Modifier

Classes

Mem. Func.

Mem. Var.

Local Var.

abstract

Yes

Yes

No

No

static

Yes

Yes

Yes

No

public

Yes

Yes

Yes

No

protected

Yes

Yes

Yes

No

private

No

Yes

Yes

No

synchronized

No

Yes

No

No

native

No

Yes

No

No

transient

No

No

Yes

No

volatile

No

No

Yes

No

final

Yes

Yes

Yes

Yes

Method Overloading
Using same method name again
and again.Signature of the
methods must be same every
time.Signature consists of :
Type of parameters
Number of parameters
Sequence of parameters

Inheritance

Acquiring properties from other .For eg a child


inherits properties from its parents.
A class that is inherited is called Base Class /Super
Class
A class that does inheriting is called Derived Class /
Sub Class

A subclass inherits variables and methods from


its superclass and all of its ancestors. The
subclass can use these members as is, or it can
hide the member variables or override the
methods.
Note:Constructors are not members and are not
inherited by subclasses.

What Members Does a Subclass Inherit?

Subclasses inherit those superclass members


declared as public or protected.
Subclasses inherit those superclass members
declared with no access specifier as long as the
subclass is in the same package as the
superclass.
Subclasses don't inherit a superclass's member if
the subclass declares a member with the same
name. In the case of member variables, the
member variable in the subclass hides the one in
the superclass. In the case of methods, the
method in the subclass overrides the one in the
superclass.
Creating a subclass can be as simple as
including the extends clause in your class
declaration

Syntax
class Base
{
..
}
class Derived extends Base
{
..
}

Method Overriding
When a method of subclass has the same
name and type signature in its superclass
,then the method in the the subclass is
said to override the method in the
superclass.When an override method is
called from within subclass , it will
always refer to the version of that method
defined by the subclass.The version of the
method defined by the superclass will be
hidden .

Using super

Super keyword is used to refer to its


immediate superclass. It has two general
forms:
The first calls the superclass constructor.
A subclass can call the constructor method
defined by its superclass.
super() must always be the first statement
executed inside a subclass constructor
super(parameter-list);

The second is used to access a member of the


superclass that has been hidden by a member of a
subclass.

Abstract Class
Sometimes, a class that you define represents an abstract concept
and, as such, should not be instantiated. Take, for example, food
in the real world. Have you ever seen an instance of food? No.
What you see instead are instances of carrot, apple, and (our
favorite) chocolate. Food represents the abstract concept of things
that we all can eat. It doesn't make sense for an instance of food to
exist.
Sometimes you want to create a super class that only defines a
generalized form that will be shared by all its subclasses ,leaving it
to each subclass to fill in the detail
An abstract class is not required to have an abstract method in it.
But any class that has an abstract method in it or that does not
provide an implementation for any abstract methods declared in
its superclasses must be declared as an abstract class.
An abstract class is a class that can only be subclassed-- it cannot
be instantiated.

Syntax
abstract class Number
{...}

abstract class A
{
abstract void callMe();
public void callMeToo()
{
System.out.println("Abstract class"); }
}
public class abscheck extends A
{
void callMe()
{
System.out.println("Hello in abscheck");
}
public static void main(String args[])
{
abscheck b=new abscheck();
b.callMe();
}
}

final keyword
The keyword final has three uses:
If used with variable ,prevents its
contents from being modified
To prevent Overriding.
To prevent Inheritance.

User Interface
It is dynamic and interactive
communication between a program
and its users.It is effective means of
making applications user-friendly .
Types of User Interface:
CUI(Character User Interface):
DOS
GUI(Graphical User Interface):
Windows

About AWT(Abstract Window ToolKit


This package provides an integrated set of
classes to manage users interface components
like
buttons,window,check
boxes
etc.
Component class is base class for all the
components .The major UI elements are:
Controls:
They are used to interact with program .It
includes labels , textfields , menus etc.
Layout Managers:
They control the appearance of the
display.They are FlowLayout, BorderLayout,
CardLayout,GridLayout,GridBagLayout.

Containers :
Components that can hold another components . For
eg:Frame,Dialog,Panel

Events:
They are used to respond to the interaction between
the components and the containers of the application.

The look and feel of awt components are different on


different platform.To address the shortcomings of
the AWT,the JFC(Java Foundation Classes) were
developed ,which is an extension of the original
AWT.It was released in 1997.Renamed to SWING
by one of the developer.Swing components are
available and consistent across the platforms.Here
JComponent is superclass for all GUI elements.Here
all the components are prefixed by J. For eg;
JButton

JFrame:
Used to create window,which has a TitleBar an
optional MenuBar and resizable border.It is
derived
from
java.awt.Frame
class.Its
constructor takes a String as argument.The
string is displayed on the title of the frame.
JFrame frame=new JFrame(Hello);
To display framesetVisible(true);
To set the Size of framesetSize(200,300);

getContentPane():Primary container for


components. Components cant be added
directly to the frame .To add
getContentPane().add(child);

JButton:
To create push button.Constructors are:
JButton()
//Without Label
JButton(Hello)
//With Label
JButton(icon)
//With Icon
JButton(String,icon) //With String and icon
To create HOT KEY: setMnemonic(Character);
To set Tool Tip:setToolTipText(String);
To set Label:setLabel();
To get Label:getLabel();

JPanel:
This is used to organize the components.
Only single Constructor:
JPanel pan=new JPanel();

JToggleButton:
A two-state button .A button that doesnt
spring back.The first time the button is
clicked , it stays in the pressed position.
Constructor are same as JButton.
JToggleButton tb=new JToggleButton();

JCheckBox:
An item that can be selected or
deselected. Constructors are:
JCheckBox cb=new JCheckBox();
JCheckBox(String);
JCheckBox(String,true);
//Selected

JRadioButton:
Same as Check Box but for single
selection it is used.Constructors are same
as JCheckBox.To make it for single
selection ButtonGroup class is used:
ButtonGroup bg=new ButtonGroup();
JRadioButton radio1=new JRadioButton (Male);
JRadioButton radio2=new JRadioButton (Female);

bg.add(radio1);
bg.add(radio2);

This says that both the radio


buttons belong to same group

JComboBox:
To create drop down list box.The Constructors
are:
JComboBox()
//Without any item
JComboBox(Object obj[]) ;
String flavors[]={Strawberry,Chocolate};
JComboBox combo=new JComboBox(flavors);
To set maximum rows setMaximumRowCount(n);
To make it editablesetEditable(true);
To add item at runtimeaddItem(Item 1);

JList:
Same as ComboBox but displayed always.The
Constructors are same as JComboBox:
JList()
//Without any item
JList (Object obj[]) ;
String flavors[]={Strawberry,Chocolate};
JList list=new JList (flavors);
To set visible rows setVisibleRowCount(n);
To add scroll barpanel.add(new JScrollPane(list));
To select one item at a time-list.setSelectionMode(ListSelectionModel.SIN
GLE_SELECTION);
MULTIPLE_INTERVAL_SELECTION

JLabel:
Used to display single line of text
,image or both.The Constructors are:
JLabel()
//Without Label
JLabel(icon)
JLabel(String)

JTextField:
It holds single line of text.
Constructors are:
JTextField();
JTextField(int cols);
JTextField(String str);
JTextField(String str,int cols);
Cols shows no. of visible characters.

JPasswordField:
Used to hide text.Constructors are same
as JTextField.
To set echo Character
setEchoChar(character);

JTextArea:
Used to display multiple line text.
Constructors are:
JTextArea();
JTextArea(int row,int cols);
JTextArea(String text);
JTextArea(String text,int rows,int cols);

Applet is a program that appears embedded in a


Web Document and is meant to be hosted by a Web
Browser, which provides home for Applet.It can be
viewed either by Browser or Appletviewer.
Every applet is implemented by creating a subclass
of the Applet class.
Applet class is available in applet package

Steps:
Create Java Source file:

import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello world!", 50, 25);
}
}
Compile the file, just like in case of applications

Create an HTML File that Includes the Applet


<HTML>
<HEAD> <TITLE> A Simple Program </TITLE> </HEAD>
<BODY> Here is the output of my program:

<APPLET CODE="HelloWorld.class"
WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>
Run the Applet:To run the applet, you need to
load the HTML file into an application that can
run Java applets

Receiving Parameters in Applets:


Parameters Are passed by NAME and
VALUE pairs in <PARAM> tags between
the opening and closing Applet
tags.Inside the applet we can read the
value which is passed through <PARAM>
tags with the getParameter() method of
Applet class .This method takes one
argument -a string representing the name
of the parameter and returns one
argument-a string containing the
corresponding value of that parameter

import java.awt.*;
import java.applet.*;
public class HelloApplet extends Applet
{
Font f=new Font("Arial",Font.BOLD,20);
String nam;
public void init()
{
nam=getParameter("name");
if(nam==null)
nam="ANU";
nam="HELLO "+nam+" !!";
}
public void paint(Graphics g)
{
g.setFont(f);
g.setColor(Color.blue);
g.drawString(nam,5,50);
}
}

<applet code=HelloApplet.class width=400


height=500>
<PARAM Name="name" Value="Anurag">
</applet>

Life Cycle of Applet:


init: Called Once,to initialize the applet each time
it's loaded (or reloaded). Mainly used to allocate
memory , defining variables.
start: To start the applet's execution, such as when
the applet's loaded or when the user revisits a page
that contains the applet.
stop: To stop the applet's execution, such as when
the user leaves the applet's page or quits the
browser.
destroy: To perform a final cleanup in preparation
for unloading.
paint: When applets canvas area needs to be
repainted.

Adding UI Components:If extending Applet


import java.applet.Applet;
public class CompAdd extends Applet
{
Button b1;
TextField tx;
public void init()
{ b1=new Button("Hello");
tx=new TextField(10);
}
public void start()
{ add(b1);
add(tx);
}

Adding UI Components:If extending JApplet


import javax.swing.*;
public class CompAdd extends JApplet
{
Button b1;
TextField tx;
public void init()
{ b1=new Button("Hello");
tx=new TextField(10);
}
public void start()
{ getContentPane().add(b1);
getContentPane().add(tx);
}

showStatus():
This is method is used to display
message on Status Bar of Applet
public void paint(Graphics g)
{
showStatus("Hello");
}

Color Font and Graphics


The Color Class:This class contains methods that
control the colors of the user interface components,
create new colors,change and query the existing
foreground and background colors.
Methods:Each method of class Color requires one
parameter of the same class.
Setting Colors:
setBackground(Color.red);
setForeground(Color.blue);
setColor(Color.pink) :to change the foreground
color but can be invoked only through the object of
the class Graphics.

Using Color Class :


Color c=new Color(210,200,240);
g.setColor(c);

The Font Class:This class is used to set and use


fonts.This represents a given font-its name,style and
size.To change font to the desired one,create an instance
i.e object of the Font class.Each font object represents
an individual font i.e its name,style and size.
Font names are string representing the family of Font
e.g. Times Roman,Courier etc.
Fonts styles are constants defined by the Font class and
can be used as: Font.PLAIN,Font.BOLD,Font.ITALIC .
The two styles can be used together using + symbol as
Font.BOLD+Font.ITALIC
Font size determines the size or the height of the
characters.

Font f=new Font("ComicSans",Font.BOLD,50);


g.setFont(f);

Graphics Class:This class is used for drawing


lines,shapes,characters and images.Graphics
class is an abstract class.To use Graphics class
outside paint method ,use getGraphics() method
to create object and then use Graphics methods
.The methods are:
drawString(String s,int col,int row):Used to draw text
on the screen on the specified col and row position.
drawLine(int x,int y,int x1,int y1):Draw line from
starting x and y co-ordinate to ending x1 and y1 coordinates.
drawRect(int

x,int

y,int

height,int

width):Draw

plain

rectangle of specified width and height.


fillRect(int x,int y,int height,int width)
drawRoundRect(int x,int y,int height,int width,int arcwidth,int

drawOval(int x,int y,int width,int height):Draw

a
Circle / an ellipse .The center is (x,y).If
width and height is same ,it is circle.

fillOval(int x,int y,int width,int height)

Layout Managers are special objects that determine


how elements are organized in the display area.
They are:
FlowLayout:
This is default layout for applet and panel.This adds
objects to a container in rows from left to
right.When first row fills the container , the
components are wrapped to the next row
automatically.With this only the alignments and the
horizontal and vertical spacing between the
components can be changed . By default alignment
is centered.The constructors are:

FlowLayout():
Components are centrally aligned with default 5 pixels of
spacing
FlowLayout(int align): For eg:
new FlowLayout(FlowLayout.LEFT)
Components are left aligned with no space
new FlowLayout(FlowLayout.LEFT,10,15)
Left aligned with gap of 10 pixels between components on
the same row and 15 pixels between rows

Use:
FlowLayout flow=
new FlowLayout (FlowLayout.RIGHT, 10 , 10);
getContentPane().setLayout(flow);//To set the Layout

BorderLayout:
This enables us to position
component using the directions
North,South, West , East & Center.It
is default layout for JFrame and
JApplet. A maximum of five
components can be displayed in the
container.The constructors are:
BorderLayout()
BorderLayout(int hgap,int vgap);

GridLayout:
It divides the screen into equal-sized
rows and columns producing a
spreadsheet
arrangement.
The
constructors are:
GridLayout(int rows,int cols)
GridLayout(int
rows,int
cols,int
hgap,int vgap)

Card Layout
It is used to create a stack of layouts with the
layouts arranged one behind the other.It shows
only one card at a time.The Constructor is:
CardLayout()
The methods are:
first(Container container)
next(Container container)
previous(Container container)
last(Container container)
show(Container container,String CardName)

Box Layout
It is used to create a stack of layouts with the
layouts arranged in a row vertically or
horizontally in a container.The Constructor is :
BoxLayout(Panel pan,axis)

Where axis may be :


BoxLayout.X_AXIS

BoxLayout.Y_AXIS

Box Layout (Contd.)

Box Layout with two panels arranged in a row


horizontally

GridBagLayout:
This is most complex and highly flexible layout manager.The
basis is a grid.Unlike GridLayout components in the
GridBagLayout manager are not constrained to a single ,
regular cell.
The way the applet specifies the size and position
characteristics of its components is specifying constraints for
each component.To specify constraint, set the variables in a
GridBagConstraints objects and specify the GridBagLayout
with setConstraints() method ,to its associate the constraints
with the component.
GridBagLayout clas has single constructor which does not take
any argument.
Position of each component in a layout is controlled by a
GridBagLayout object and is determined by the currently set
GridBagConstraints object.This also does not take any
argument.

Its an extension of the GridLayout


Manager, but differs in following
ways:Component can take up more than
one cell in the grid.
The proportion between rows and
columns do not have to be equal .
Component inside grid cells can be
arranged in different ways
It has following data members:

gridx,gridy:
They are cell coordinates of the cell that contains the
components . GridBagConstraints.RELATIVE which
is default , is used to specify the component should be
placed just to right of (gridx) or just below (for gridy)
the component added to the container before this
component.

gridwidth,gridheight:
They are number of cells the component
spans(stretch) .gridwidth for columns , gridheight for
rows.Default value is 1 .

weightx,weighty:
They are used to set up the proportions of rows and
columns . They determine whether the components
stretch horizontally/vertically to fill up the display
area.

fill:
If the component is smaller than its cell(s),this
variable determine whether to resize the component
to fit into the available area.It has following values:

GridBagConstraints.NONE(dont resize)
GridBagConstraints.HORIZONTAL(make use of width)
GridBagConstraints.VERTICAL(make use of height)
GridBagConstraints.BOTH(make use of all the space)

anchor:
If the component is smaller than its cell(s),this
variable determine what corner or edge of the cell
area to attach the component to.Valid arguments are:
GridBagConstraints.CENTER , NORTH , EAST , SOUTH,
WEST, NORTHWEST , NORTHEAST , SOUTHEAST,
SOUTHWEST

Events:
If you are asleep early in the morning and your
alarm clock goes off, That is an Event.An event
an unexpected external happening.
An event represents a users interaction with
the program . When a user performs an action
such as mouse click, the system creates an
event and passes it to the program event
handling methods.The event handling method
than respond with the relevant behavior for
that event .For eg: when user clicks submit
button , the data associated with the dialog is
sent to the appropriate Server.

Components of Event: Event Object:An event is an object that


describes a state change in a source. It can be
generated as a consequences of person
interacting with the elements in a GUI .Some
of activities that cause event to be generated
are pressing a button , entering a character via
keyboard, selecting an item in a list and
clicking the mouse .
Event may may be generated when a timer
expires , a counter exceeds a value , a
software/hardware failure occurs, or an
operation is completed .

Event SourceA source is an object that generates an event.


This occurs when the internal state of that object changes in
some way.Sources may generate more than one type of event
.A source must register listeners in order for the listeners to
receive notifications about a specific type of event. Each type of
event has its own registration method.
Syntax is :
public void addtypeListener(typelistener el)
type is the name of the event
el is a reference too the event listener
For eg:
To register keyboard event listener-addKeyListener()
To register mouse motion listener-addMouseMotionListener()
To register button event listener-addActionListener()

When an event occurs, all registered listeners are notified


and receive a copy of the event object.This is multicasting
the event.In all cases , notifications are sent only to
listener that register to receive them.

Event Listener(Handler)Listener is an object that is


notified when an event occurs.It has two major
requirements:
It must have been registered with one/more sources to
receive notification about specific type of events.
It must implement methods to receive and process these
notifications.
The methods receive and process events are defined in a
set of interface found in java.awt.event.

Root Classes:
Root of event class hierarchy is
EventObject.Superclass for all events.It
has
only
one
constructor:EventObject(Object src)
Where src is object that generates this event

Event Delegation:
The process of assigning an object to
handle a component event is called
delegation.Java 1.1 onwards supports
event delegation model.

Event Classes

Interface:
They are abstract classes that are left
completely unimplemented.The benefits
are same as abstract classes.Interface
provide a means to define protocols for a
class without worrying about the
implementation details.At a time we can
extend only one class , but we implement
more than one interface,so we can
implement concept of multiple inheritance.
Limitation with interface is that we have to
override all the methods in the interface.

Steps:
Implement
the
appropriate
interface in the listener so that it
will receive the type of event
desired.
Implement code to register the
listener as a recipient for the
event notifications.

import java.awt.*;import java.awt.event.*;


import java.applet.Applet;
public class Delegate extends Applet
{TextField text1; Button b1;
public void init()
{ text1=new TextField(20);
add(text1);
button =new Button("OK");
add(b1);
ButtonListener blisten=new ButtonListener();
b1.addActionListener(blisten); }
class ButtonListener implements ActionListener
{ public void actionPerformed(ActionEvent event)
{
String msg="Hello from Java!!!";

import java.applet.Applet;import java.awt.*;


import java.awt.event.*;
public class EvetYour extends Applet implements ActionListener

{ TextField text1;Button b1;


public void init()
{ text1=new TextField(20);
add(text1);
b1 =new Button("OK");
add(b1);
b1.addActionListener(this); }
public void actionPerformed(ActionEvent event)
{ String msg="Hello from Java!!!";
Object obj=event.getSource();
if(obj==b1)
{
text1.setText(msg);}
}}

Exception

An Exception is an abnormal condition that


disrupts normal flow of program .There are
many cases when abnormal conditions happen
during program execution ,such as:
The file you try to open may not exist.
The class file you want to load is missing or in wrong
format.
The other end of network connection may be nonexistent.
An operand is not in the legal range prescribed for
operation/methods.
If these abnormal condition is not prevented or at least
handled properly ,either the program will be aborted
abruptly or incorrect results or status will be carried on
,causing more and more abnormal conditions

Exception Hierarchy
Throwable

Error

Represents usually
serious
&
unrecoverable
exceptions , such as
running out of
memory.

Exception

It

represents
unusual conditions
that arise in the
course of program
execution.

Uncaught Exception
class excep
{
p s v m(string args[])
{
int d=0;
int a=42/d;
s.o.p(value is :+a);

}
}

When the JAVA run-time system detects the


attempts to divide by zero , it constructs a new
Exception object and then throws this exception .
This causes the execution of Excep to stop ,
because once an exception has been thrown , it
must be caught by an Exception handler .Here,
we havent supplied any exception handlers of
own , so the exception is caught by default
handler provided by the java run-time system .
Any exception that is not caught by your
program will be ultimately be processed by the
default handler .The default handler display a
string describing the exception , prints the point
at which exception occurred, and terminate the

Techniques to handle Exception

It is divided into the following:


try block
catch block
throw statement
finally block

try block
Although the default exception handler provided by the
java, which is useful for debugging, you will usually
want to handler an exception yourself. Doing so provides
two benefits
It allows you to fix the error.
It prevents the program from automatically
terminating.
In the try block, statements which might throw an
exception are enclosed, It indicate that program is
prepared for testing the existent of exceptions. If an
exception occurs, the program flow is interrupted, call to
exception handler is made if one exists, otherwise abort()
is invoked.
The try block needs to be accompanied by one or more
catch blocks or one finally block.

Catch block
An exception handler is associated with a try
block by providing one/more catch blocks
immediately after the try block.
No statement is allowed between the end of try
block and the beginning of the catch block. It
takes 2 parameters - Name of the throwable class
and the name of the variable by which the handler
can refer to the exception caught.
Same as try block
catch (ArithmeticException e)
{System. Out. Print (Division by zero.) }

Finally Block

This block is optional portion of the


try statement. There can be only one
finally block for one try statement
,and it must follow the last catch
block . Mainly it is used for the
cleanup after executing exception
handling code

throw

Used to throws an Exception explicitly. Syntax:


throw ThrowableInstance
Steps to use:
In the method declaration , specify the type of
exception that can be thrown, using throws modifier.
Determine the situation when an error condition
,which matches the specified exception type, occurs
and then dynamically create an instance of the
exception class or one of its subclass for that error
condition.
Throws the exception object.When the exception is
thrown , pass string as an argument that can be used
by calling code to display an error message to the
user

Class ClassName
{
public int methodName()throws Exception
{
statements
if (<some condition>)
{
throw new Exception(Message);
}
}
}

Built-in Exceptions
NullPointerException:Raised
when
variable is used without initializing it
ArithmeticException:Caused by math
errors like division by zero
ArrayIndexOutOfBoundException:When
an array element which does not exist is
accessed
ArrayStoreException:When program tries
to store the wrong type of data in an array
ClassNotFoundException:When specified
class file not found.

FileNotFoundException:Attempt
to
access a non-existence file.
IOException: By general I/O failure
NumberFormatException:
When
conversion of String to number fails
OutOfMemoryException: When there
is not enough memory to allocate for a
new Object
StringIndexOutOfBoundsException:
When String element which does not
exist is attempted to be accessed.

A Thread is a single flow of control within a program.


A program is normally broken into small chunks
called tasks, and task is further broken down into
smaller chunks called threads. If we take the example
of preparing breakfast, it involves preparing the
components that constitutes it. One such component is
coffee, which could be considered as task. In order to
prepare coffee, there are few smaller chunks of task
involved liking boiling water and milk, adding coffee
powder and sugar to a cup, adding the boiled milk and
water into the cup and stirring the contents of the cup.
Each of these tasks is required to prepare a cup of
coffee, and each could be considered a Thread

A few of these tasks can be performed simultaneously. It


can therefore be concluded that preparing coffee has a
number of threads of execution. In computer
terminology more than one thread executing at any
point in time is called multithreading. The main
advantage of multithreading is the speed of execution
of the program.
Difference with Process:
Both is sequential flow of control. The difference lies
in fact that a thread cannot exist on its own, meaning
that a thread cannot exist without a process. Threads
run within a process. A process made of only one
thread is said to SingleThreaded. Process having more
than one thread in a single process is said to be
multithreaded.
For Eg:
Microsoft Internet Explorer

Life Cycle of Thread:

New Statement

Newly
Created

start()

stop()

run ends

suspend()
wait()
sleep()
BlockingBlocked
RunnableI/O
resume()
notify()
sleep time out
stop()
I/O finished
run ends
stop()
run ends

Dead

Every thread after creation and before destruction, will


always be in one of the four states:
Newly Created: A thread enters the newly created state
immediately after creation. In this state, the local data
members are allocated and initialized. After the start()
method is called, the thread will be put into the runnable
state.
Thread newThread=new Thread(this)
//this- current instance

Runnable: In this state, the execution context exists and


the thread can be scheduled to run at any time. This
state is divided into 2 sub states: the running and
queued. When it is in running state, it is assigned CPU
cycles and is actually running. When thread is in the
queued state, it is waiting in the queue and competing
for its turn to spend CPU cycles.

Blocked(Not Runnable): The blocked state is entered when


one of the following event occurs:
The thread itself or another thread calls the suspend()
method
The thread call an objects wait() method
The thread itself calls the sleep() method
The thread is waiting for some I/O operation to complete
A thread in a blocked state will not be scheduled for
running. It will go back to the runnable state when the
following events occurs:
If suspended, another thread calls its resume() method.
If by wait() method, the objects notify() or notifyAll()
method called
If put to sleep(), the sleeping time elapsed.
If I/O, the specified I/O operation completes.

Dead Thread:
The dead state is entered when a thread finishes
its execution or is stopped by another thread
calling its stop() method.

How to create Thread:


Java has both a class and interface that can be
used to create threaded applet or applications.
Java support for thread is found in the java.lang
package in the Thread class and the one interface
Runnable. There are two ways:
By implementing a Runnnable interface
By extending Thread class

Synchronization:When two or more threads need


access to a shared resource , they need some way to
ensure the resource will be used by only one thread
at time .The time by which it is achieved is called
Synchronization
Key to synchronization is the concept of
monitor(also called semaphore).A monitor is an
object that is used as a mutually exclusive lock, or
mutex.Only one thread can own a monitor at a
given time . When a thread acquires a lock , it is
said to have entered the monitor. All other threads
attempting to enter the locked monitor will be
suspended until the first
thread exists the
monitor.These other threads are said to be waiting
for the monitor.A thread that owns a monitor can
reenter the same monitor if it so desires.

User can synchronize their code in


two ways:
By using synchronized method
By using synchronized statement

DeadLock:
This situation occurs when two threads have a
circular dependency on a pair of synchronized
objects.For e.g. Suppose one thread enters the
monitor on object X and other thread enters the
monitor on object Y.If the thread in X tries to
call any synchronized method on Y , it will block
as expected.However if the thread in Y , in turn
tries to call any synchronized method on X the
thread waits forever , because to access X , it
would have to release its own lock on Y so that
the first thread could complete.

STREAMS:
A Stream is a continuous flow of
data from source to a destination , it could be from
memory to hard disk , from network to local
system or from one area of memory to another.If
stream is used as source of information , it is called
an Input Stream.If stream is used as a destination
for information it is called an Output Stream.
Java defines two types of streams:Byte and
Character. Byte streams provides a convenient
means of handling input and output of bytes.They
are used when reading and writing binary data.
Character Streams provide a convenient means for
handling input and output of characters.

Byte Stream Classes: It is defined by


using two classes hierarchies . At the top
are two abstract classes :InputStream and
OutputStream
.They
define
several
methods that the other stream classes
implement .Two of the most important are
read() and write() which are used to read
and write bytes of data.

Character Stream Classes:

It is also
defined by using two class hierarchies.At
the top are two abstract classes Reader and
Writer.

Methods of InputStream:
int available() :No. of bytes available
void close()
:Closes the input stream
int read()
:To read bytes
int read(byte buff[]):Read up to bufferlength bytes into buffer
int read(byte buff[],int start,int end):
Attempts to read up to end into
buffer starting at start

Methods of OutputStream:
void write(int n)

:Write specified byte


to an output stream
void write(byte []b):Write an array of
bytes
void write(byte []b,int start,int end):
Attempts to write up to end into buffer
starting at start
void flush()
:Forces to writes whenever
the data accumulates in the output stream
void close()
:Closes output stream.

FileInputStream:
This is used to read bytes from file.The
available Constructors are:
FileInputStream(String filepath);
FileInputStream(File fileobj);
FileInputStream fi=new FileInputStream(file1.txt);

File f=new File(file1.txt);


FileInputStream fi=new FileInputStream(f);

FileOutputStream:
This is used to write bytes to a file.The
available Constructors are:
FileOutputStream(String filepath);
FileOutputStream(File fileobj);
FileOutputStream(String fil,boolean app);
FileOutputStream fo=new FileOutputStream(file1.txt);
FileOutputStream fo=new FileOutputStream(file1.txt,true);

Character Streams: Like input and output


stream here , Reader and Writer are abstract
classes.
File Reader: It is used to read contents of a file. It
has two constructors.

FileReader (String filepath)


FileReader (File fileobj)
FileWriter: It creates a writer that is can used to
write to a file.Constructors are:

FileWriter (String filepath)


FileWriter (String path, boolean append)
FileWriter (File obj)

RandomAccessFile:It is used to read


from or written to random locations
within file.It implements the interfaces
DataInput and DataOutput.It also
supports positioning requests- that is
we can position the file pointer within
the file.It has two constructors:
RandomAccessFile(File obj,String access)
RandomAccessFile(String filename,String access)

Where access is either r or rw

Methods are:
seek(long value):To set current position of
file pointer within file.Next read write will
occur at the new file pointer
getFilePointer():Returns current location.
length():Length of file in terms of byte.

Networking
Client/Server Model:
Server:
One who Serves on request of client
Client:
One who request for service to the
Server.
The communication between Server and
client is termed as Networking

Protocols:
When computers communicate , they need to follow certain
rules like human .Data is sent from one machine to another
machine in the form of packets . Rules govern packaging of
data into in the form of packets, speed of transmission and
recreation of data to its original form .These rules are called
network protocol .Network protocols are set of rules and
conventions followed by systems that communicate over a
network.Examples of Protocols are:
TCP/IP
UDP(User Datagram Protocol)
ICMP(Internet Control Message Protocol)
AppletTalk
IGMP(Internet Group Multicast Protocol)
NetBEUI

In JAVA there are two tools for communication


Datagram that uses UDP
Sockets that uses TCP/IP

A Datagram packet is an array of bytes sent from


one program to another.They are unreliable as there
is no guarantee that the data packet that user is
sending will reach its destination.It just transmit data
with IP address and Port as the destination of the
packet.They are used only when the data to be
transmitted is very less and the distance between
sender and receiver is not very large.There is chance
of packet getting lost if the network traffic is very
high , or receiving program is handling multiple
request simultaneously from other programs.It can
send only a 65,536 bytes packet.

Sockets on the other hand , use TCP for


communication .The advantage of Socket
model is that the server is not affected by
the source of client requests.It services all
requests, as long as the client follow the
TCP/IP protocol .Any Computer that
support TCP/IP can talk to any other
computer that supports it through the
socket model.
Datagrams are faster than Sockets because
there is no overhead of establishing a
connection.Sockets however first establish
connection and then transmit.

Internet Addressing Method:


On the Internet every machine has an internal
address ,which is a number that uniquely identifies
each computer on the Net.An IP Address has 32-bits
and its is referred to as a sequence of four numbers
between 0-255 separated by dots(192.168.0.3).These
nos. are assigned hierarchically so that every machine
can be remembered easily.Since there are many
computers interconnected on the Internet , it is
difficult to remember the numeric address .To
overcome this problem , an alternative addressing
method is derived which is known as Domain Naming
Service(DNS).DNS is textual addressing method.The
general
form
is
host.subdomain.domain
(www.niit.com).
A port number is numeric address through which
service requests are processed.

Socket:
A socket is a handle to communication link with
another application over the network .They are often
used in client/server application .A centralized service
waits for various remote machines to request specific
resources, handling each request as it arrives.In order
for clients to know how to communicate with server,
standard application protocols are assigned wellknown ports.
java.net Package:
It includes several classes and interfaces , which
provide support for networking.

Steps:
1. Open a socket.
2. Open an input stream and output stream to the
socket.
3. Read from and write to the stream according to the
server's protocol.
4. Close the streams.
5. Close the socket.

Creating Socket Client:


Create Socket Class Object:
Socket clisocket=new Socket(techedge,1001);
Constructor takes two arguments IP Address/DNS name
and port no.

Reading from and Writing to Socket:

Two class are required for this purpose:


PrintStream(For writing to Socket)
BufferedReader(For reading from Socket)
PrintStream out=new
PrintStream(clisocket.getOutputStream());
BufferedReader in=new BufferedReader(new
InputStreamReader(clisocket.getInputStream());

Closing Connection:
out.close()
in.close();

Creating the Server:


Create object of ServerSocket Class
ServerSocket server=new ServerSocket(1001);
ServerSocket server=bew ServerSocket(1001,2);

accept() method:
The accept() method waits for a client connection by
listening to the port to which it is bound.When client
attempts to connect to the server,the method accepts
the connection and returns a client socket.The socket
is later used for communication between the server
and its client.

Collections
A collection is an object that contains a group of
objects within it. The contained objects are called
the elements of the collection
The Java programming language supports collection
classes like Vector,
Bits,
Stack,
Hashtable, and LinkedList. A collection has
references to objects of the type Object
The collection API typically consists of interfaces
that are used to maintain objects. These are the
Collection, Set, and List interfaces

The Vector Class


The Vector class allows us to create dynamic
arrays that can contain multiple objects
It provides methods for adding, removing, and
inserting elements
Constructors are:
Vector vector = new Vector();//By default initial
Capacity is of 10 elements
Vector vector = new Vector(5);//Initial Capacity is of 5
elements grow by initial capacity
Vector vector = new Vector(5,2);//Initial Capacity is of 5
elements grow by 2

Adding Objects to Vectors:


addElement(Object n):
It adds the new object, n, as the last element in the vector

insertElementAt(Object n, int index):


It inserts a new object, n,at the position specified by the
index

setElementAt(Object n, int index):


It replaces the element at index with the object, n

Removing Objects from vectors:


removeElementAt(int index)

Accessing the Elements of a Vector:


capacity() method:

To see the capacity of Vector


elementAt(int index)method :

To access the elements of a vector.


firstElement() method:

To see the first element of vector


lastElement() method:

To see the last element of vector


size()method:

To find out the number of objects


present in a vector

The Stack Class


The Stack class is a subclass of the Vector class.
push() method:
To add item in a Stack.

pop() method:
Remove the item from Stack.Last element will removed
first.

search() method :
To search for an object in a stack .

empty() method :
Returns true if a stack is empty.

Inter-thread Communication
The communication between threads is called interthread communication
Inter-thread communication is achieved using four
methods wait(), notify(), notifyAll(),
and yield()
They can only be called from a synchronized
method
A synchronized method is used when access has
to be coordinated for an object
We can invoke only one synchronized method
for an object at any given point of time. This
prevents conflicts between the synchronized
methods in multiple threads

The wait() Method:


The wait()method tells the current thread to give up the
monitor and sleep until another thread calls the notify()
method
Syntax:
public final void wait() throws InterruptedException;

The notify() Method:


The notify() method wakes up a single thread that is waiting for the
current monitor of an object
If multiple threads are waiting, one of them is chosen arbitrarily
A thread becomes the owner of the monitor of an object in one of the
three ways:
By executing a synchronized instance method of that object
By executing the body of a synchronized statement that synchronizes
the object

By executing a synchronized static method of a class

The yield() Method:


The yield() method causes the runtime system to
put the current thread to sleep and execute the next
thread in the queue