JAVA 2.0
Introduction to Java Program Constructs Classes and Methods Inheritance Exceptions Packages Interfaces Streams and Files Applets Frame, Menu and Dialogs Thread and Multithreading Networking in Java JDBC-ODBC Remote Method Invacation Java Beans (BDK) Swing Servlets (JSDK) Introduction to Java Program constructs Classes and Methods Inheritance Exceptions Packages Interfaces Streams and Files Applets Frame, menu and Dialogs Thread and Multithreading Networking in Java JDBC-ODBC Remote Method Invacation
Java is an Object-Oriented, multi-threaded programming language developed by Sun Microsystems in 1991. It is designed to be small, simple and portable. The popularity of the Java is due to 3 key elements powerful programming language, applets and rich set of significant object classes.
Adv of Java
Components of JVM
In Java development environment, there are two parts, a Java compiler and Java interpreter. Java compiler generates byte code and interpreter executes the Java program. Eventhough the bytecode is slow, it gives platform independent application.
Java program is typed in and saved in a file with extension .java. This file is compiled by javac. It creates a file with .class extension. This is executed by Java file without extension. A simple example for a Java program is
Example 1:
class first
{
public static void main (String s[ ] )
{
System.out.println("Welcome to Java ") ;
}
}
It was saved in the file first.java and compiled by java first.java
and executed by java first.
Class declaration is done in the first line of the program by class classname
Every java program has main( ) method, which was first executed.
void keyword indicates that main( ) does not return any value.
static indicates that main( ) is a class method and can be called without creating an object.
public indicates the method is global.
Data types :
Integers :
long 64
int 32
short 16 -32768 to 32767
byte 8 -128 to 127
Float
float 64
double 32
Characters
char 16 0 to 63536
String
Boolean :
boolean true or false
Character Escape Sequences
\n \t \f \b \\ \’ \" \ddd \uxxxx
To declare a variable
type variable=value,variable=value,…;
To initialize a variable
int a=10; String name="palani"; float sal=5400.50f;
Arrays:
int arr [12] ;
char carr[ ] = { ‘a’,’b’,’c’,’d’} ;
int a[12][10] ;
char name[10][10][10] ;
Type casting:
byte a=10; int c = a + 10;
Here, a is converted to int automatically.
To manually convert a type use (type) value
For example float f = (float) a/ float(b) ; if a, b are integers.
Example 2:
class cast
{
public static void main(String args[ ])
{
byte a = 10, b = 20 ;
int c = 15, d = 2 ;
float f1 = c/d; // f1 is 7.0
float f2 = (float) c / (float) d ; // f2 is 7.5
c = b + 10 ; // b is automatically converted to int
/* b = b + 10 ; Error : cannot assign int to byte */
b = (byte) (b + 10);
System.out.println("f1 =" + f1 " + "f2 = " + f2 " + "c = " + c + "b = "+b);
}
}
Operators
1) Arithmetic - + - * / %
2) Relational - < > <= >= !=
3) Logical - && || !=
4) Assignment - =
5) Comparision - = =
6) Incre/Decrement - ++ --
7) Bitwise operator - ~ & | ^ >> >>> << &= != ^=
8) Conditional - ? :
Comments :
// Single line comment
/* */ Multiline line comment
/** */ Document line comment
2. PROGRAM CONSTRUCST
They are divided into
Misc - break, exit, continue, and return
a) If
If (condition)
{
set of statements1;
}
else
{
set of statments2 ;
}
Example 3:
class if
{
public static void main(String a[ ])
{
int a=5,b=10;
if (a>b)
System.out.println("A is big");
else
System.out.println("B is big");
}
}
b) for
for (var=value1; condition; iteration)
{
statements;
}
Example 4:
class for
{
public static void main(String a[ ])
{
for(int a=0; a<10; a++)
System.out.println("A is big");
}
}
c) while and do..while
while(condition) do
{ {
statements; statements;
} } while(condition);
Example 5:
class dowhile
{
public static void main(String a[ ])
{
int a=5 ;
do
{
System.out.println("A is big");
a--;
} while(a>0);
}
}
d) switch
switch (expr)
{
case value1:
statements1 ; break;
case value2:
statements2 ; break;
:
:
case valuen:
statementsn; break;
default:
statements ;
}
Example 6:
class switch
{
public static void main(String a[ ])
{
int a=5 ;
switch(a)
{
case 0:
System.out.println("Zero"); break;
case 1:
System.out.println("One"); break;
case 2:
System.out.println("Two"); break;
default:
System.out.println("greater than 2");
}
}
}
e) break, continue and exit
break will transfer the control out of the loop, in continue , the rest of the lines are ignored and loop continue after the next iteration. The exit function will stop the program execution.
3. CLASSES AND METHODS
Classes
The most important feature of the OOP is classes. A class defines the shape and behavior of an object and is a template for multiple object with similar features. It is a logical construct upon which the entire java language is built because it defines the shape and nature of the object.
To create a class, a source file with the class keyword in it, followed by a name and pair of curly braces for the body.
access class classname
{
type instance-variable;
type method(parameters)
{
body of method;
}
}
Once class is created, an instance of class is created by new keyword. The instance of class is used to access the variables and methods that form part of the class. The dot operator is used to get the value of the class variable (object.variable).
Instance Variable : Data is encapsulated in a class by declaring varables inside the class declaration. Variables declared in this scope are called as Instance variables.
Class Variable : Class variables are global to class and all the instances of the class. To declare class variable static keyword is used.
The access of class may be public, private, abstract or final.
Methods
Methods are functions that operate on instances of classes in which they are defined. Method definition has four parts. They are name of the method, return type , list of parameters and body of the method.
returntype methodname (type arg1, type arg2,…)
{
Statements;
}
To call a method
methodname( ) or
obj.methodname(para1, para2,…) ;
An example for a class which has a class and method
Example 7:
class area
{
int len=10, bra=20;
void calc( )
{
int ara = len * bra;
System.out.println("The area is " + ara);
}
public static void main(String a[ ])
{
area a = new area( );
a.calc( );
}
}
Access Specifiers:
Public : If any method or variable is declared as public, it is visible to all
classes.
Private : If any method or variable is declared as private , it is visible to
classes in which it is declared.
Protected : It is visible in class and all its subclasses.
Package : It is indicated by the lack of any access modifier in a declaration.
It has an increased protection and narrowed visibility.
Final : It can not overridden by subclass
Abstract : in abstract class without body, must be overridden by subclass.
Static : It is automatically called when creating instance of class.
this:
The this keyword is used inside any instance method to the current object.
Constructor
A constructor method is a special kind of method that determines how an object is initialized when created. They have the same name as the class but do not have any return type. Consturctor can also be overloaded.
Example 8:
class cons
{
int I; int j;
cons(int a, int b)
{ I=a; j=b; }
void print( )
{System.out.println("the addition of " + I + "and " + j + " is " +(I+j)); }
public static void main(String s[ ] )
{
cons c = new cons(10,10);
c.print( );
}
}
Garbage collection
When no reference to object exits, the object no longer needed, the memory occupied by the object is reclaimed. This is called garbage collection. Java periodically does garbage collection.
Finalizer :
Finalizer method is the exact opposite of constructor method. They are called just before the object is garbage collected and its memory is reclaimed. All cleanup operations are performed in this method.
protected void finalize( )
{ }
Methods overloading
Methods overloading is creating different methods with same name but with different parameters. This is the one type of creating polymorphism in Java
Example for method overloading and constructor overloading
Example 9:
Box( )
{
int depth;
int width;
int height;
Box(int w, int d, int h)
{
witdth = w; height = h; depth = d;
}
Box(int a)
{
witdth = a; height = a; depth = a;
}
Box( )
{
witdth = 1; height = 1; depth = 1;
}
void show( )
{
System.out.println(width * height * depth);
}
void show(int a)
{
System.out.println("Width = " + w);
System.out.println("Depth = " + d);
System.out.println("Height = " + h);
System.out.println("Cube is " + (width * height * depth )) ;
}
}
class boxdemo
{
public static void main(String args[ ])
{
Box b1 = new Box(3,4,5);
Box b2 = new Box(5);
Box b3 = new Box( );
b1.show(1);
b2.show( );
b3.show( );
}
}
Method Overriding
Method overriding is creating a method in the derived class that has the same name arguments as in the superclass. This new method hides the superclass method.
Recursion
Recursion is the process of defining something in terms of itself. A method that calls itself is said to be recursive.
Example 10:
class factorial
{
int fact(int n)
{
int result;
if(n==1) return 1;
result = fact(n----1) * n;
return result;
}
}
class recurse
{
public static void main(String a[ ])
{
factorial f = new factorial( );
System.out.println("Fact of 3 is "+f.fact(3));
}
}
Nested Class
It is possible to nest a class definition within another and treat the nested class like any other method of that class. An inner class is a nested class whose instance exists within an instance of its enclosing class and has direct access to the instance members of its enclosing instance.
class enclosingClass
{
class innserClass
{
}
}
Example :
class outclass
{
int a =10;
public void m1( )
{
System.out.println("This is inner class method");
inclass in = new inclass( );
in.m2( );
}
class inclass
{
public void m2( )
{
System.out.println("This is inner class method");
System.out.println("a = "+ a);
}
}
public static void main(String arg[ ])
{
outclass out = new outclass( );
out.m1( );
}
}
Inheritance is the method of creating new class based on the already existing class. The new class derived is called as sub class or derived class which has all features of the existing class and its own. The existing class is called as super class or base class.
Adv : reusability of code, accessibility of variables and methods of the base class
by the derived class.
If the class is derived from more than one class , then it is called as multiple inheritance. This is not available in Java. To overcome this problem use interface.
Method Overriding
Whenever there are methods of the same name both in the base class as well as in the derived class and if that method is called by main, the method in the derived class is always executed. This is called overriding. See example11.
Example 11:
class A
{
void m( )
{
System.out.println("This is super class");
}
}
class B extends A
{
void m( ) // it will override super class's method
{
System.out.println ("This is sub class");
}
}
Super
Super has two forms. First it calls the superclass’s constructor. The second is used to access a member of the superclass that has been hidden by a member of a subclass.
Example 12:
class A
{
int a = 10;
void A(int k)
{
System.out.printn("k is " + k);
}
void m( )
{
System.out.println("This is super class");
}
}
class B extends A
{
int a = 20;
void m( ) // it will override super class's method
{
System.out.println("This is sub class");
}
void call( )
{
super(5); // to call super class's constructor
m( ) ; // it will call the method in the derived class
super.m( ); // to call super class's method
int c = a ;
int d = super.a ; // to assign super class's varaible.
System.out.println("c = " + c + " d = " + d );
}
}
class inh
{
public static void main(String args[ ])
{
B ob = new B( );
ob.call( ): // output is c = 20 d = 10
}
}
Final
final float pi =3.14f;
final int a = 40
final is used to create constant variable.
b) final modifiers - to prevent overriding
Final modifiers are those to which no further alteration can be made. We can not override the method using final
Example 12:
class A
{
final void meth( )
{
System.out.println("this is the final method can not overridden");
}
}
class B extends A
{
void method( ) //this line will show error.
{
System.out.println("Illegal");
}
}
c) final class - to prevent inheirtance
If the class is declared as final , we cannot inherit it. All methods in the final class are final
final class A
{
}
class B extends A // error cant subclass of A
{
}
Abstract
Sometimes we will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. To declare abstract class
abstract type name(parameters);
We must override the abstract method. An abstract class cannot be directly instantiated with the new operator. We cannot declare abstract constructors or abstract static methods.
Example 13 :
abstract class A
{
abstract void callme( );
void display( )
{
System.out.println("This is example for abstract class"):
}
}
class B
{
void callme( )
{
System.out.println("B's implementation of callme");
}
}
class abst
{
public static void main(String a[])
{
B b = new B( );
b.callme( );
b.disp( );
}
}
An exception is an abnormal condition or error that occurs during the execution of the program. Exception in java is handled by five keywords – try, catch, finally, throw and throws.
The object class has a subclass called Throwable to handle exception and errors, which has two subclasses Exception and Error.The classes of exception are IOException and RuntimeExveption
The try and catch fixes the error and prevents the program from terminating abruptly. The finally block will be executed if no catch matches it and always executed. If you use try block, finnaly block or atleast one catch block should be used.
If you don't want to use try and catch statements then use throws clause. The throws class is responsible to handle the different types of exceptions generated by the program. This clause usually contains a list of types of exceptions that are likely to occur in that program.
The throw clause is used to call exception explicitly. User defined exception can be called by throw clause. User defined exception is created by extending the class Exception.
Examples for simple catch statements
Example 14 :
class exc4
{
public static void main(String args[])
{
try{
int a[5]; a[12]=33;
}
catch(ArrayIndexOutOfBoundsException a)
{
a[1]=33;
}
System.out.println("After catch/try block");
}
}
Example multiple catch statements If you pass any arguments to main then, second error occur or division by zero will occur. finally is always called.
Example 15:
class except
{
static void proca(int v)
{
int k[4];
try
{
System.out.println(10/v);
System.out.println("Inside proca");
K[10] =2;
}
catch(ArithmeticException e)
{
System.out.println("division by zero");
}
catch(Exception e)
{
System.out.println("other than arithmetic exception");
}
finally
{
System.out.println("finaly Exceptin is caught");
}
}
public static void main(String a[])
{
int l = a.length;
proca(l);
}
}
Example to use throws clause.
Example 16 :
class ThrowsException
{
public static void main(String s[ ]) throws ArithmeticException
{
System.out.println("Inside main") ;
int j = 40/0;
System.out.println("This stt is not printed");
}
}
Example for user defined exception
Example 17 :
class myexcep extends Exception
{
private int detail;
myexcep(int a)
{ detail =a; }
public String toString( )
{
return "MyException"+detail;
}
}
class exc11
{
static void compute(int a) throws myexcep
{
System.out.println("called compute"+a);
if (a>0)
throw new myexcep(a);
System.out.println("Normal exit");
}
public static void main(String arg[])
{
try{
compute(-1);
compute(20);
}catch(myexcep e)
{
System.out.println("My excep caught"+e);
}
}
}
Some Unchecked runtime exceptions are
ArithmeticException
ArrayIndexOutOfBoundsException
ClassCastException
IndexOutOfBoundsException
NullPointerException
NumberFormatException
SecurityException
Java’s Built In exceptions are
ClassNotFoundException
CloneNotSupportedException
IllegalAccessException
Package contains set of classes in order to ensure that class names are unique. Packages are container of classes used to keep the class name space compartmentalized.
If package is created, then we can import all classes in the package by
Import packname.*; or particular class by
Import packname.classname;
Example 18 :
package pack;
public class class1
{
public static void greet( )
{
System.out.println ("Hello");
}
}
save above in file class1.java in the directory pack.
Import pack.*;
class importer
{
public static void main(String s[])
{
class1.greet( );
}
}
save it as importer.java in the previous to pack directory and execute
it.
If Java source file contain package, interface, classes then the order should be
An interface is a collection of abstract behavior that individual classes can implement. An interface consists of set of method collections. Using interface, you can specify what a class must do but not how it does it. All methods and final variables in interface must be public.
Multithreading is not available in Java. To overcome this problem, interface is introduced.
access interface name
{
returntype mehodname(para);
type final-variable=value;
}
access is either public or default.
Example 19:
public interface address
{
public void add(String add);
public void name(String name);
}
class A implements address
{
public void add(String a)
{
System.out.println("Inside implemented method");
}
public void name(String n)
{
System.out.println("Inside implemented method");
}
void disp( )
{ System.out.println("Method of class A");}
public static void main(String a[ ])
{
A a = new A( );
System.out.println("Inside main of class A which implements
address interface");
a.disp( );
a.name("swathi");
a.add("3,sivan koil st");
System.out.println("==============");
}
}
Input
int read( ) throws IOException
final String readLine( ) throws IOException
int n = System.out.read( );
String str = inData.readLine( );
Here DataInputStream inData = new DataInputStream (System.in);
Output
System.out.println( );
System.out.print( );
System.out.write (int byte); - console output
Reading and Writing files
It throws IOException
FileInputStream fin = new FileInputStream(filename);
int fin.read( ) - to read a char from a file
void fin.close( ) - to close a file
FileOutputStream fout = new FileOutputStream(filename);
void fout.write(int I);
fout.close( );
String Methods :
String s = new String( );
char chars[ ] { ‘a’, ‘b’, ‘c’);
String s1 new String(chars);
Int s.length( )
boolean s.equals(s1)
String s.substring(int,int) ;
char s.charAt(int);
String toString(object);
String s.replace(char,char);
String s.trim( );
String s.toLowerCase( );
String s.toUpperCase( );
8. Multhithreading in Java
Thread
A process is a program in a execution. A thread is a line of execution. Two or more processes running concurrently in a computer is called multitasking. The process can contain multiple threads to execute its different sections. This is called multhreading. Using this, we can run different parts of the programs at a time.
States of thread
There are four states of thread. They are new, runnable, blocked and dead The fig shows the states of the thread.
start( ) suspend( )/wait( ) / sleep( )
resume( )
stop( ) run( ) stop( )
Adv of thread:
Thread is created by
a) the class Thread which has the interface Runnable.
b) creating the objects of the class Thread
a) Using runnable interface
class c1 implements Runnable
{
}
To create a thread
Thread t = new Thread(this) ;
Thread t = new Thread(this,"Demo thread’);
Where this referes the Applet object.
After thread is created , it will first execute start( ) method then run( ) method is automaticall called.
b) Creating Thread Class Objects
class c1 extends Thread
{
}
Thread
Thread(Runnable, String)
Thread(ThreadGroup, Runnable, String)
ThreadGroup
ThreadGroup(String name)
ThreadGroup(ThreadGroup ob,String name)
Example:
class thread1 implements Runnable
{
Thread t = new Thread(this,"test thread") ;
System.out.println("Child thread : " + t) ;
t.start( ) ;
}
public void run( )
{
try{
for(int I=5; I>0; I--)
{ System.out.println("child thread"+I);
Thread.sleep(500);
}
} catch(InterruptedException e) { }
System.out.println("exiting child thread");
}
public static void main(String g[ ])
{
thread1 th = new thread1( );
try{
for(int j=5;j>0;j--)
{
System.out.println("Main thread : "+ j);
Thread.sleep(1000);
}
} catch (InterruptedException e) { }
System.out.println("Main thread exiting …");
}
}
Creating Thread extends Thread class
class thread2 extends Thread
{
thread2( )
{
super("test thread") ;
System.out.println("Child thread : " + this) ;
start( ) ;
}
public void run( )
{
try{
for(int I=5; I>0; I--)
{ System.out.println("child thread"+I);
Thread.sleep(500);
}
} catch(InterruptedException e) { }
System.out.println("exiting child thread");
}
public static void main(String g[ ])
{
new thread2( );
try{
for(int j=5;j>0;j--)
{
System.out.println("Main thread : "+ j);
Thread.sleep(1000);
}
} catch (InterruptedException e) { }
System.out.println("Main thread exiting …");
}
}
Runnable abstracts a unit of executable code. We can construct a thread on any object that implements Runnable.
The thread methods are start( ), resume( ), sleep( ), suspend( ) , join( ) and toString( )
.
Synchronization
Two or more threads accessing the same data simultaneously may lead to loss of data integrity. Java uses the concept of monitor. A monitor is an object, used as a mutually exclusive lock.
Java offers interprocess communication through the use of wait( ), notify( ) and notifyall( ) methods of Object class and all are synchronized methods.
Thread Priorities
The usage of setPriority( ) and getPriority( ) methods are used to set and get the priorities of thread respectively. The yield( ) method enables provision of CPU’s time to threads with equal priority and prevents monopolization of a single thread. The Thread has final variables declared line – NORM_PRIORITY (5), MINIMUM_PRIORITY (1) and MAXIMUM_PRIORITY (10).
9. APPLET
An applet is a dynamic and interactive program that can run inside Web page displayed by a Java-capable browser or applet viewer.
All applets are subclasses of Applet. You should import java.applet and java.awt since all applets run in a window. Applet defines three interfaces Appletcontext, AppletStub and AudioClip.
/* <Applet CODE="classname.class" WIDTH=400 HEIGHT=100>
</APPLET>
*/
Applet extends java AWT class Panel, Panel extends Container which extends Component.
The init( ) Method
This method gets called as soon an applet is started. Initialization of all variables, creation of objects, setting of parameters, etc. can be done in this method.
The start( ) method
This method is executed after the init mehod. Also used to restart the applet that was stoped.
The stop( ) method
This method is used to halt the running of an applet. This method is called when a web browser leaves the HTML document containing the applet.
The destroy( ) method
This method is used to free the memory occupied by the variables and objects initialized in the applet. Called by the browser just before the applet is terminated.
The paint( ) method
This method helps in drawing, writing and creating a colored background or an image on to the applet. This method is called each time your applet’s output must be redrawn. It has one parameter called Graphics.
The repaint( ) method
This method is used in case an applet is to be repainted. The repaint method calls update( ) method to clear screen and paint( ) method to redraw the contents of the current frame.
resize (width, height)
Resize the applet window
showStatus (str)
Displays the string in the status window of the applet
When starting the applet init, start, paint methods and when terminating stop and destroy methods are called.
9.a. The Graphics Class in java.awt package
drawString(message,x,y);
drawLine (x1,y1,x2,y2);
drawRect (x1,y1,width,height)
drawRoundRect (x1,y1,width,height,width1,height1)
draw3Drect (x1,y1,width,height,boolean)
drawPolygon (xs,ys,pts)
drawOval (x1,y1,width,height)
drawArc (x1,y1,widht,height,angle1,angle2)
fillRect (x1,y1,width,height)
fillRoundRect (x1,y1,width,height,width1,height1)
fillPloygon (xs,ys,pts)
fillOval (x1,y1,width,height)
fillArc (x1,y1,widht,height,angle1,angle2)
9.b. Font Class in java.awt package
Font f = new Font ("fontname", format, size);
Formats are Font.BOLD, Font.ITALIC, and Font.PLAIN
g.setFont(f)
9.c. Color Class in java.awt package
Color.grey, Color.green, Color.yellow, Color.pink, Color.red, Color.blue, Color.magenta, Color.cyan
setColor (color)
getColor (color)
setBackground (color)
getBackground (color)
setForeground (color)
getForeground (color)
9.d. Images
getImage (URL,string)
drawImage (Image,x,y,imageObserver)
to find URL
getCodeBase ( ) can be used
To create image
createImage (width,height)
getGraphics ( )
Clipping
A technique by which the drawing area can be restricted to a small portion of the screen.
Method is clipRect( )
clipRect(x1,y1,x2,y2);
Animation
Animation is technique by the object is moved on the screen In which the original image is clreared and placed in another place.
9.e. Events
Mouse Events methods
boolean mouseDown(event , x, y)
boolean mouseDrag(event , x, y)
boolean mouseEnter(event , x, y)
boolean mouseExit(event , x, y)
boolean mouseMove(event , x, y)
boolean mouseUp(event , x, y)
boolean mouseDown(event , x, y)
boolean mouseDown(event , x, y)
KeyBoard Events
boolean keyDown(event , x, y)
boolean keyUp(event , x, y)
Types of Event handling
a)Low Level event
Low level classes Low level event Listener
ComponentEvent ComponentListener
FocusEvent FocusListener
KeyEvent KeyListener
ContainerEvent ContainerListener
MouseEvent MouseListener
MouseMotionListener
WindowEvent WindowListener
InputEvent
b) Semantic Events
Low level classes Low level event Listener
ActionEvent ActionListener
AdjustmentEvent AdjustmentListener
ItemEvent ItemListener
TextEvent TextListener
Example:
import java.awt.*;
mport java.awt.event.*;
import java.applet.*;
public class mousetest extends Applet implements MouseListener
{
public void init( )
{
addMouseListener(this);
}
public void mouseClicked(MouseEvent e)
{
showStatus("Mouse clicked at " + e.getX( ) +" , " + e.getY( ));
}
// Write above code for other mouse events
}
Each component class in the AWT has one addXXXListener( ) method for each event type.
9.f. ABSTRACT WINDOW TOOLKIT (AWT)
Button
Button( ) setLabel(String)
Button("label") getLabel( )
Label
Label( ) getText( )
Label(String) setText(String)
Label(String, int) getAlignment( )
SetAlignment(int)
where Int is alignment. It may be Label.LEFT, Label.RIGHT, Label.CENTER
Checkbox
Checkbox( ) setLabel(string)
Checkbox(String) getLabel( )
Checkbox(String,grp,boolean) setState(boolean)
getLabel( )
Choice
Choice( ) getItem(int)
addItem(String) getItemcount( )
getSelectedItem( )
getSelectedIndex( )
TextComponent
TextField( ) getText( )
TextField(String, int) setText(String)
TextArea( )
TextArea(String, int, int) int represents rows and columns
List
List( ) getItem(int) int starts from 0
List(int,boolean) getItemCount( )
AddItem(String) select(int)
getSelectedItem( )
Scrollbar
Scrollbar( ) setValue(int)
Scrollbar(orient, value, visible, min, max) getValue( )
Layout Manger
A set of classes used to position the components in a container.
First create instantiate a layout manager class and use setLayout( ) method
Flow Layout
Lays components linewise from left to right
FlowLayout( )
FlowLayout(align, hgap, vgap)
Align – FlowLayout.LEFT, FlowLayout.RIGHT, FlowLayout..CENTER
Grid Layout
Position the components in the cellf of the grid.
GridLayout(int rwo, int col)
GridLayout( int rwo, int col, int hgap, int vgap)
Border Layout
Lays components relative to the edges of the container
BorderLayout( )
BorderLayout(int hgap, int vgap)
add("direction",item);
direction may be NORTH, SOUTH,EAST , WEST or CENTER
Insets(int, int, int, int)
Used to give spacing around the container
Panel
A panel class is a non-abstract, recursively nestable container.
Panel( )
9.g. Frames, Menus and Dialogs
Frame
Inherited from Frame class
Frame( )
Frame(String)
Methods
setVisible(boolean)
setSize(Dim)
setLocation(int,int) getLocation( )
dispose()
setTitle(String) getTitle( )
Menus
Menubar( )
Menu(String)
MenuItem(String)
CheckboxMenuItem(String)
SetState(boolean) getState( )
menu.add(MenuItem)
menubar.add(menu)
Frame.setMenubar(menubar)
Dialog
Dialog(Frame,boolean)
Dialog(Frame,String,boolean)
setResizable(boolean)
isModal( )
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
class fram extends Frame
{
String msg=" ";
fram()
{
super("Menu Frame");
MenuBar mb = new MenuBar();
Menu m1 = new Menu("File");
Menu m2 = new Menu("Edit");
MenuItem mi1 = new MenuItem("Open");
MenuItem mi2 = new MenuItem("Save");
MenuItem mi3 = new MenuItem("Copy");
MenuItem mi4 = new MenuItem("Paste");
m1.add(mi1);
m1.add(mi2);
m2.add(mi3);
m2.add(mi4);
mb.add(m1);
mb.add(m2);
setMenuBar(mb);
winadapt w = new winadapt(this);
addWindowListener(w);
mnuhandler handler = new mnuhandler(this);
mi1.addActionListener(handler);
mi2.addActionListener(handler);
mi3.addActionListener(handler);
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
}
}
class mnuhandler implements ActionListener
{
fram f1;
public mnuhandler(fram f2)
{
f1 = f2;
}
public void actionPerformed(ActionEvent ae)
{
String msg;
String s = (String) ae.getActionCommand();
if(s.equals("Open"))
msg = "Open";
else if(s.equals("Save"))
msg ="Save";
else if(s.equals("Copy"))
msg = "Copy";
else
msg = "Paste";
msg = msg +" selected";
f1.msg=msg;
f1.repaint();
}
}
class winadapt extends WindowAdapter
{
fram f1;
public winadapt(fram f2)
{
f1 = f2;
}
public void windowClosing(WindowEvent e)
{
f1.dispose();
}
}
public class frammenu extends Applet
{
Frame f;
public void init()
{
f = new fram();
f.setSize(300,300);
f.setVisible(true);
}
}
10. Wrapper Classes - java.lang
double doubleValue( )
float floatValue( )
long longValue( )
int intValue( )
String toString( )
Boolean boleanValue( )
char charValue( )
Double and Float
boolean isNaN( )
boolean isInfinite( )
boolean equals(object obj)
int hashCode( )
Integer
static int parseInt(String str) throws NumberFormatException
static String toHexString(int num)
static String toOctalString(int num)
static Integer valueOf(String str) throws NumberFormatException
Character
isDigit( )
isLetter( )
isUpperCase( )
isLowerCase( )
toLowerCase( )
toUpperCase( )
toTitleCase( )
Process
void destroy( )
int exitValue( )
InputStream getErrorStream( )
InputStream getInputStream( )
OutputStream getOutputStream( )
Runtime
process exec(String progName) throws IOException
long freeMemory( )
void gc( )
static Runtime getRuntime( )
long totalMemory( )
void runFinalization( )
System
static void arraycopy(Object source, int sstart, object target, int tstart, int size);
static void gc( )
static void load(String librayfileName)
void runFinalization( )
static long currentTimeMillis( )
Object
Object clone( ) throws CloneNotsupportedException
boolean equals(Object obj)
void finalize( ) throws Throwable
int hashCode( )
int notify( )
int notifyAll( )
final void wait( ) throws InterruptedException
string toString( )
final Class getClass( )
Class
static Class forName(String name) throws ClassNotFoundException
string getName( )
Class getSuperclass( )
boolean isInterface( )
ClassLoader getClassLoader( )
Math
Transcendental sin(d) cos(d) tan(d)
Exponential exp(d) log(d ) pow(d1,d2) sqrt(d)
Rounding abs(I) ceil(d) floor(d) max(x,y) min(x,y) round(f)
Thread
Thread( )
Thread(ThreadGroup grp,Runnable threadob, String Thname)
void destroy( ) interrupt( ) stop( ) yield( ) start( ) run( ) resume( ) list( )
static Thread currentThread( )
final boolean isAlive( )
static boolean interrupted( )
ThreadGroup
ThreadGroup(String name)
ThreadGroup(ThreadGroup ob,String name)
final ThreadGroup getParent( )
Java.net package
The objectives are
Network Datagram
Protocol DatagramPacket
Socket DatagramSocket
Client/Server TCP/IP
Internet (IP) Address Socket
Domain Name Service ServerSocket
InetAddress URL
Network is a set of computers physically connected together. It enables the sharing of computer pheriperals and resources by different computers.
The communication between the computers requires certain set of rules called protocols. Some important protocols are TCP/IP, HTTP, FTP, SMTP and NNTP. Port no 21 is for FTP, 23 is for Telnet, 25 is for e-mail and 80 is for HTTP.
IP is a low-level routing protocol that breaks data into small packets and sends them to an address across a network. TCP is a higher level protocol that manages string together these packets, sorting and retransmitting them to reliably transmit your data. UDP (user Datagram Protocol) can be used to support fast, connectionless, unreliable transport of packets.
Socket is the place used to plug in just like electric sockets, from the socket the communication starts.
Client is the machine, which sends some request to another computer. The computer that does the request is called the Server.
A proxy server speaks the client side of protocol to another server. A client would connect to a proxy server, which have no restrictions, and the proxy server would in turn communicate for the client.
Every computer connected to the network has unique address it contains four numbers between 0 and 255 separated by period. Ex is 80.0.0.50
It is very difficult to remember the IP of the computer. To overcome this problem domain name service (DNS) is used. It maps the IP address by string of characters. Ex is www.microsoft.com
InetAddress is a class, which is used to encapsulate IP address and DNS.
InetAddress getLoaclHost( ) throws unknowHostException
InetAddress getByName (String hostName)
InetAddress getAllByName (String hostName)
URL
Uniform Resource Locater. It contains four parts protocol, separated by : and //, host name of IP address, port number, file path.
For ex http://www.starwave.com/index.html
Constructors of URL throws MalformedURLException
URL (String urlspecifier)
URL (String protocolName, String hostName, int port,String path)
URL (String protocolName, String hostName, String path)
getPort( ), getHost( ),getFile( ) and toExternalForm( )
To access content information of a URL, use url.openConnection( ) method.
Datagrams
Datagrams are bundles of information passed between machines. It contains two classes
DatagramPacket for container of data
DatagramSocket for send or receive the DatagramPacket
DatagramPacket constructors are
DatagramPacket (byte data[ ], int size);
DatagramPacket (byte data[ ], int size, ipAddress, int port);
Methods of DatagramPacket are
InetAddress getAddress( ), int getPort( ) , byte( ) , getData( ) and
int getLength( )
DatagramSocket constructors are
DatagramSocket.send (DatagramPacket d);
DatagramSocket.receive (DatagramPacket p);
client.java
import java.net.*;
class client
{
public static DatagramSocket ds;
public static byte buffer[] = new byte[1024];
public static void main(String arg[]) throws Exception
{
ds = new DatagramSocket(6);
while(true)
{
String a;
DatagramPacket p = new DatagramPacket(buffer,buffer.length);
ds.receive(p);
a=new String(p.getData(),p.getLength(),1);
if (a.equals("q"))
{
System.out.println("Server response is shut off now");
return;
}
System.out.println(new String(p.getData(),0,p.getLength()));
}
}
}
server.java
import java.net.*;
class server
{
public static DatagramSocket ds;
public static byte buffer[] = new byte[1024];
public static void main(String a[]) throws Exception
{
InetAddress ia = InetAddress.getByName("rad-tm-04");
System.out.println(ia);
ds = new DatagramSocket(123);
int pos=0;
while(true)
{
int c = System.in.read();
switch(c)
{
case 'q':
System.out.println("Server quits");
return;
case '\r':
break;
case '\n':
ds.send(new DatagramPacket(buffer,pos,ia,456));
pos=0;
break;
default:
buffer[pos++] = (byte) c;
}
}
}
}
TCP/IP
TCP/IP sockets are used to implement reliable, bidirectional, persistent, point to point, stream based connection between hosts on the Internet.
It contains two classes. They are Socket and ServerSocket. ServerSocket class is designed to wait for clients to connect and Socket class is used to connect to ServerSocket.
ServerSocket (int port)
ServerSocket (int port, int maxqu)
ServerSocket (int port, int maxqu, InetAddress localAddress)
ServerSocket has a method accept( ) that waits for client to initiate communication.
Socket (String hostName, int port)
Socket (InetAddress ipAddress, int port)
=============================================================
JDBC is a set of Java API for executing SQL statements.
Two-Tier Model
Client Machine
DBMS propictary protocol
Database server
Three-Tier Model
Client Machine(GUI)
HTTP, RMI, CORBA
Server Machine
DBMS-proprictary protocol
Database Server
Two-Tier Model
In Two-Tier Model, a Java applet or application talks directly to the database. This requires a JDBC driver that can communicate with the particular database management systems accessed. Users SQL statement is delivered to the database and the results of those statements are sent to the user. This is referred to as client/server configuration.
Three-Tier Model
In this a middle tier is introduced for fast performance. It sends the SQL statements to the databases. The results of the query are send to middle tier, which sends them to user.
Example :
a) Create a data base students in Ms-Access with table student containing the following fields studid number, sname text, course text and marks number.
import java.sql.*;
class dbappn
{
static connection con;
public static void main(String a[ ]) throws Exception
{
class.forName("sun.jdbc.odbc.JdbcOdbcdriver");
open( );
select( );
insert( );
delete( );
update( );
select( );
close( );
}
static void open( ) throws SQLException
{
/*con = DriverManger.getConnection("dsn","username","pwd"); */
con = DriverManager.getConnection("jdbc:odbc:student","palani","kumar");
con.setAutoCommit(false);
}
static void close( ) throws SQLException
{
con.commit( );
con.close( );
}
static void select( ) throws SQLException
{
Statement stmt = con.createStatement( );
ResultSet rs = stmt.executeQuery("Select * from student");
Boolean more = rs.next( );
If (!more)
{
System.out.println("No rows found");
Return ;
}
while(more)
{
System.out.println("ID " : " + rs.getString("studid"));
System.out.println("Name : " + rs.getString("sname"));
System.out.println("Course : " + rs.getstring("course"));
System.out.println("Marks : " + rs.getString("marks"));
more = rs.next( );
}
rs.close( );
stmt.close( );
}
static void insert( )
{
try{
Statement stmt = con.createStatement( );
int rows = stmt.executeUpdate("Insert into student
values(100, ‘Subash’,’Java’,80)");
con.commit( );
stmt.close( );
System.out.println(rows + " row added");
} catch(SQLException s) { System.out.println("Error"); }
}
static void delete( )
{
try{
Statement stmt = con.createStatement( );
int rows = stmt.executeUpdate("Delete from student
where id = 100;
con.commit( );
stmt.close( );
System.out.println(rows + " row deleted");
} catch(SQLException s) { System.out.println("Error"); }
}
static void update( )
{
try{
Statement stmt = con.createStatement( );
int rows = stmt.executeUpdate("Update student
set marks = 90 where id =100 ;
con.commit( );
stmt.close( );
System.out.println(rows + " row added");
} catch(SQLException s) { System.out.println("Error"); }
}
}
13. Remote Method Invocation (RMI)
RMI allows java object that executes on one machine to invoke a method that executes on another machine. This is the one method of creating distributed application.
Steps to create client/server application using RMI
inter.java
import java.rmi.*;
public interface inter extends Remote
{
public void getdata(int m,int n) throws RemoteException;
int adddata() throws RemoteException;
}
client.java
import java.rmi.*;
public class client
{
public static void main(String arg[])
{
try
{
int a = Integer.parseInt(arg[1]);
int b = Integer.parseInt(arg[2]);
int result;
inter i = (inter) Naming.lookup("rmi://" + arg[0] + "/Addserver");
System.out.println("client");
i.getdata(a,b);
result = i.adddata();
System.out.println(result);
}catch(Exception e)
{
System.out.println("error " + e);
}
}
}
server.java
vbnm,import java.rmi.*;
import java.rmi.server.*;
public class server extends UnicastRemoteObject implements inter
{
int x,y;
public server() throws RemoteException
{
}
public int adddata() throws RemoteException
{
return x+y;
}
public void getdata(int m, int n) throws RemoteException
{
x=m; y=n;
}
public static void main(String arg[])
{
try
{
server s = new server();
Naming.rebind("Addserver",s);
}
catch(Exception e)
{
System.out.println("Exception e");
}
}
}
15. Swing
Swing is a set of classes that provides more powerful and flexible components than are possible with the AWT. In addition to buttons, check boxes and labels, Swing supplies severals components including tabbed panes, scroll panes, trees, picture buttons, combo box , etc.
Unlike AWT components, Swing components are platform independent since they are written in Java. They are called as lightweight components. Swing related classes are contained in javax.swing and its subpackages.
JApplet
Applets that use Swing must be subclasses of JApplet, which extends Applet. JApplet is rich in functionality than Applets and provides various panes such as content pane, glass pane and root pane. To add a component, obtain the pane then call add( ) method for the pane of the JApplet.
Container getContentPane( ) to obtain the content pane
void add(comp) to add a component in content pane
Comp |
Constructor |
Methods |
label |
JLabel(Icon I) JLabel(String s) JLable(String s, Icon I, int align) |
Icon getIcon( ) String getText( ) void setIcon(Icon I) void setText(String s) |
Text Field |
JTextField( ) JTextField(int cols) JTextField(String s) JTextField(String s, int cols) |
|
Buttons |
JButton(Icon i) JButton(String s) JButton(String s, Icon I) |
|
CheckBox |
JCheckBox(Icon I) JCheckBox(String s) JCheckBox(Icon I, boolean) JChcekBox(String s, boolean) JCheckBox(String s, Icon I, boolean) |
|
Radio Buttons |
JRadioButton(Icon I) JRadioButton(String s) JRadioButton(String s, boolean) JRadioButton(s, I, boolean) |
|
Combo Box |
JComboBox( ) JComboBox(Vector v) |
|
Tabbed Panes |
JTabbedPane( ) |
addTab(title, comp) |
Scroll Panes |
JScrollPane(comp) JScrollPane(int vsb, int hsb) JScrollPane(comp, vsb, hsb) |
|
Trees |
JTree(HashTable h) JTree(Object ob[]) JTree(TreeNode t) JTree(Vector v) |
|
Tables |
JTable(Obect data[][], Object colheads[]) |
Icons
Method
Int getIconHeight( )
int getIconWidth( )
void paintIcon(comp, Graphics, x, y)
void setDisabledIcon(icon)
void setPressedIcon(icon)
void setSelectedIcon(icon)
void setRolloverIcon(icon)
Scroll Panes
JScrollPane(comp, vsb, hsb)
The vsb, hsb constants are
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
Example :
import javax.swsing.*;
import java.awt.*;
public class Jlabel extends JApplet
{
public void init( )
{
Container cp = getContentPane( );
ImageIcon ii = new ImageIcon("Birds");
JLabel jl = new JLabel("Birds",ii,JLabel.Center);
Cp.add(jl);
}
}
Example :
import javax.swing.*;
import java.awt.*;
public class jscroll extends JApplet
{
public void init( )
{
Container CP = getContentPane( );
Jpanel jp = new Jpanel( );
jp.setLayout(new GridLayout(20,20));
int b = 0;
for(int ii = 0; I<20; I++)
{
for(k=0;k<20;k++)
{
jp.add(new JButton("Button " + b));
b++;
}
}
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JscrolPane(jp, v, h) ;
CP.add(jsp, BorderLayout.CENTER);
}
}
Example :
Servlets
Servlets are small programs that execute on the server side of a Web connection, used to extend the functionality of a Web Server.
JSDK
Java Servlet Development Kit (JSDK) contains class libraries to create servlets. It contains the utility servletrunner to test the servlets. The basic life cycles of servlets are init( ), service( ) and destroy( ). The steps to create a servlets are
Adv of servlets over CGI :
The javax.servlet package
Interfaces |
Class |
Methods |
Servlet |
GenericServlet |
Init(ServletConfig sc ) |
ServletRequest |
ServletInputStream |
Service(ServeltRequest req, ServletResponse res |
ServletResponse |
ServletOutputStream |
void destroy( ) |
ServletConfig |
ServletException |
ServletConfig getServletConfig( ) |
ServletContext |
UnavailableException |
|
SingleThreadModel |
The first two methods throws SerlvelException
The javax.servlet.http Package
Interface |
Class |
HttpServletRequest |
Cookie |
HttpServletResponse |
HttpServlet |
HttpSession |
HttpSessionBindingEvent |
HttpSessionBindingListener |
HttpUtils |
HttpSessionContext |
Example :
Step 1 : colorGet.html
<html>
<body>
<center>
<form name ="form1" method ="get"
action=<http://localhost:8080/servlet/colorGetServlet">
<B> color : </B>
<Select name="color" size="1">
<option value = "Red"> Red </option>
<option value="Blue"> Blue </option>
</select>
<br> <br>
<input type = submit value="submit">
</form>
</body>
</html>
Step 2 : colorGetSelvlet.java
import java.io.* ;
import javax.servlet.*;
import javax.servlet.http.*;
public class colorGetServlet extends HttpServlet
{
public void doGet (HttpServlet request, HttpServletResponse response)
throws ServletException, IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter( );
pw.println("<B> The selected color is : " );
pw.println(color);
pw.close( );
}
}
Step 3: compile the above program colorGetServlet.java
Step 4 : start servlet runner by c:\javawebbrowser2.0\jserv
Step 5: Display the web page in the browser. Select a color and submit.
17. KEYWORDS IN JAVA
/* class , method, constuctor, subclass , superclass, this, super, final, finalize(), garbage collection, method overriding, package, interface, import, extend, implement, private, public, protected, static , try, catch, finally, throw, throws , thread, multhread, run, suspend, resume, start, stop, synchronization, deadlock, applet. */
Bytecode
Java compiler generates machine independent bytecode instead of machine dependent exe file. So it gives ‘write once run anywhere’ . Due to this, most of the communication programs are done in Java instead of using C++ or VC++.
Class
The most important feature of the oop is classes. A class defines the shape and behaviour of an object and is a template for multiple object with similar features. Class contains the decl of instance variables and methods.
Constructor
A constructor initializes an object immediately upon creation. Once defined, it is automatically called immediately after the object is created before the new operator is completed. It has the same name as class and is similar to method but does not have the return type.
Garbage collection
When no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object is reclaimed. This technique is called garbage collection.
finalize( )
This method is called just prior to garbage collection. It means it is called, when an object goes out of scope.
new
The new operator dynamically allocates memory for the object and returns reference to it.
this
this can be used inside any method to refere to the current object.
Method overloading
It is possible to have two or more methods with same name but different parameters within the same class. This is called method overloading.
Method Overriding
Whenever there are methods of the same name both in the base class as well as in the derived class and if that method is called by main, the method in the derived class is always executed. This is called overriding.
Recursion
It is a process of defining something in terms of itself.
static
When a member is declared as static, it can be accessed before any objects of its class are created and without reference to any object.
final variable
used to declare constant variable . final float PI=3.14
Inheritance
Inheritance is the method of creating new class based on the already existing class. The new class derived is called as sub class or derived class which has all features of the existing class and its own. The existing class is called as super class or base class.
Adv : resuablity of code, accessibility of variables and methods of the base class
by the derived class.
If the class is derived from more than one class , then it is called as multiple inheritance. This is not available in Java.
extend
extend keyword is used to create a subclass from a basic class.
super
super has two forms. First it calls the superclass’s constructor. The second is used to access a member of the superclass that has been hidden by a member of a subclass.
Thread
A thread is a line of execution. Using multithreading, we can run the different parts of the program at a time.
Synchoronized.
This keyword is used with a method to enable synchronization. It contains an object which allows only one thread to
Network
A set of computers and peripherals physically connected together to enable sharing of resources and communication. Java network can be done either by Datagram which contains DatagramPacket for container of data and DatagramSocket which contains send and receive methods or TCP/IP which contains Socket class for client and Serversocket for server.
RMI
It allows an object running in a system to access a method that runs on another system. It is used to create distributed application in Java. In this rmic compiler is used to create Stub class and Skeleton classes for client and server respectively. Rmiregistry is used to map the name of server.
Beans
Beans are software component that are reusable in variety of environments. After creating beans, it can be added to toolbar of microsoft office, browser, etc.
Servlets
Servlets are small program that are executed on the web server to extend the functionality of the server. It contains two packages javax.servlet and javax.servlet.http
New in Java 2.0
Swing – contains tabbed panes, scroll panes, picture button, etc.
Collections
More security mechanisms
JIT – to create exe file instead of bytecode
Can play wav,au,midi and sudio files
Drag and drop capabilities
wait( ) , sleep( ) and suspend( ) are deprecated in Java 2.0
Java Plug-in directos browser to use JRE rather than JVM