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

12.02.

2010
What is Java?
Java is a technology from Sun overtaken by Oracle developed by James Gosling in 1991
with initial name Oak with the goal to work with any kind of device.
It was renamed to Java in 1995.
It is divided in four sub-technologies
1.
2.
3.
4.

Java SE (Java Standard Edition)


Java EE (Java Enterprise Edition)
Java ME (Java Mobile Edition)
Java Fx

Resource
http://java.sun.com
Tools Required
1. JDK (Java Development Kit)
2. JRE (Java Runtime Environment)
3. IDE (Integrated Development Environment)
a. NetBeans
b. Eclipse
c. Visual Age
d. JDeveloper
e. JCreator
f. Etc.
Versioning in Java
Java provides two kinds of version
1. Product Version
2. Developer Version
Developer Version
Deals with JDK

1.0
1.1
1.2
1.3
1.4
1.5

1.6
1.7

Product Version
Product version deals with Java as product which shows the reliability, scalability and
strength of Java.

1.0
1.1
1.2 (Java 2)
1.3
1.4
5.0
6.0
7.0

Rules in Java
1. Java is case sensitive
2. File extension will be .java
3. Compiler used is JAVAC.EXE
Introduction to PATH
PATH is an environmental variable used to hold list of folders to search an executable file
(.exe, .com, .bat) in given folders.
Setting temporary PATH
SET PATH=%PATH%;C:\jdk1.6\bin
Set Permanent Path
My Computer Properties Advanced Environmental Variables System Variables
PATH Edit Add your path
Syntactical Rules in Java
1. All keyword and package names must be in lower case
2. All class and interface names starts with upper case. (PascalCase)
a. Math, System, BufferedReader, InputStreamReader
3. All fields and methods starts with lower case (camelCase)
a. length(), parseInt()
Features of Java
1. Simple and Sober

2.
3.
4.
5.
6.
7.

Secure
Object Oriented
Multi Threaded
Portable
Platform Independent
Robust
a. Java provides a big set of libraries for almost any purpose
b. Java provides built-in garbage collector for automatic memory management
c. Java provides in-built features exception handling to trap the runtime errors

13.02.2011
What makes Java Platform Independent?
Is JVM is platform Independent?
Java provides a software called JRE (Java Runtime Environment) which contains sub
softwares like Java Virtual Machine (JVM) and Garbage Collector.
JVM contains other software like Class Loader, Code Verifier and Just-in-time compiler
(JIT)
.java JAVAC .class (byte code language) JVM (Class Loader Coder Verifier
JIT Binary Code) Execution
JVM is a machine dependent software but makes the Java platform Independent.
Writing First Java Program
1. File Name must be .java
2. Every executable class must have an entry point called main()
a. public static void main(String args[])
Hierarchy in Java
JAR File package class field, methods and static objects
JAR is Java Archive. It is a compressed file created from JAR.EXE tool. It contains a set of
packages.
A package is a collection of related set of class.

java.lang
o A package that provides commonly used classes
o Math, String, System, Integer, Float, Double, Character etc.
o It is by default
java.io
java.util
java.awt
java.awt.event

javax.swing
java.sql
javax.servlet
javax.servlet.jsp
javax.servlet.jsp.tagext
etc.

Working with General Input/Output Operations


-

Java provides in-built object inside System class


o in
o out
o err
in is a static object of InputStream class from java.io package
out and err are the static objects of PrintStream class from java.io package

Methods of PrintStream class


-

print()
println()
printf()

//First.java
class Sample
{
public static void main(String args[])
{
System.out.printf("Hello to Java");
}
}
Compiling the Program
JAVAC <programname.java>
Example
JAVAC First.java Sample.class
Running a class
Use JAVA.EXE tool
JAVA <classname>
Example
JAVA Sample
File naming rules in Java

1.
2.
3.
4.

A file name can be upto 255 characters including space and extension
A program can have many classes
All or none of the classes can have the main()
Program name and class name can be same or different except if the class is public
then both must be same

Using NetBeans 6.9.1


public class Sample
{
public static void main(String[] args)
{
int a=5,b=6;
System.out.printf("Product of %d and %d is %d",a,b,a*b);
}
}

Data Types in Java


Special keyword used to define type of data and range of data.
Can be of two types
1. Primitive Types
2. User Defined Types
Primary Types can be
Integrals (All are signed)
1. byte 1 byte
2. short 2 byte
3. int
- 4 bytes
4. long - 8 bytes
Floating
1. float - 4 bytes
2. double - 8 bytes
Characters
1. char

- 2 bytes (Unicode)

Booleans
1. boolean 2 bytes
Literals or Constant Values
The values that we use from our side for assignment or some expression are called as
literals.
Integrals
-

Default is int
Use l or L with long as suffix

o int num=10;
o long p=5L;
Floatings
- Default is double
o Use f or F with floats
o double num=5.6;
o float k=5.6; //compile time error
o float k=5.6F; //compile time error
Character Literals
- Enclosed in single quotes
o char ch=A;
String Literals
-

All strings are Managed by String class


Enclosed in double quotes
o String name=Vikas;

19.02.2011
Using classes from different packages
Use import command
To import specific class
import <packagename.classname>;
To import all classes of a package
import <packagenme.*>;
Example
import java.io.*;
import java.util.Scanner;
Using Scanner class of java.util package to read the data from Keyboard
Create an object of Scanner class
Scanner sc=new Scanner(System.in);
Different methods of Scanner class
String next()
int nextInt()
float nextFloat()
double nextDouble()
Example
WAP to input name and age of a person and check it to be valid voter.
import java.util.Scanner;
class Voter
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Name : ");
String name=sc.next();
System.out.print("Age : ");
int age=sc.nextInt();
if(age>=18)
System.out.printf("Dear %s you can vote",name);
else
System.out.println("Dear "+name+" you cannot vote");
}
}

Importing the static members of the class


Use import static keyword
Example
import static java.lang.System.*;
import static java.lang.Math.*;
Full Code
import static java.lang.System.*;
import java.util.Scanner;
public class Voter
{
public static void main(String[] args)
{
Scanner sc=new Scanner(in);
out.print("Name ");
String name=sc.next();
out.print("Age : ");
int age=sc.nextInt();
if(age>=18)
out.printf("Dear %s you can vote", name);
else
out.printf("Dear %s you cannot vote",name);
}
}
Reading data using BufferedReader class of java.io package
When we input data from keyboard (System.in), a stream of bits get passed and provided to
object of another class InputStreamReader which convert the bit pattern into a character.
These characters get buffered into memory space using another class BufferedReader. Use
readLine() method of BufferedReader class to read the data.
public String readLine() throws IOException

Wrapper Classes
Special classes under java.lang package, corresponding to some data type which provides
advance functionality on data types as well conversion from String type to numeric types.

Data Type

Wrapper Class

byte
short
int
long
float
double
char
boolean

Byte
Short
Integer
Long
Float
Double
Character
Boolean

Example
WAP to input a number and convert into octal, hexa decimal and binary. Check a character
to be alphabet, digit and special character.
public class WrapperTest
{
public static void main(String args[])
{
int num=3456;
System.out.println(Integer.toBinaryString(num));
System.out.println(Integer.toHexString(num));
System.out.println(Integer.toOctalString(num));
char ch='$';
if(Character.isDigit(ch))
System.out.println(ch+" is a digit");
else if(Character.isLetter(ch))
System.out.println(ch+" is an alphabet");
else
System.out.println(ch+" is special character");
}
}
Conversion from String type to numeric type
datatype variable=wrapperclass.parseDatatype(stringdata);
Example
int age=Integer.parseInt(br.readLine());
double basic=Double.parseDouble(br.ReadLine());
Mixing Scanner and BufferedReader
import static java.lang.System.*;
import java.io.*;
import java.util.Scanner;
public class Mix
{

public static void main(String args[]) throws IOException


{
Scanner sc=new Scanner(in);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
out.print("Name ");
String name=br.readLine();
out.print("Age : ");
int age=sc.nextInt();
if(age>=18)
out.printf("Dear %s you can vote", name);
else
out.printf("Dear %s you cannot vote",name);
}
}
Creating static objects
We can define static objects in some class and access them any time in any class
import static java.lang.System.*;
import java.io.*;
import java.util.Scanner;
public class MyClass
{
public static Scanner sc=new Scanner(in);
public static BufferedReader br=new BufferedReader(new InputStreamReader(in));
}
Using Static objects
import static java.lang.System.*;
import java.io.*;
public class Mix
{
public static void main(String args[]) throws IOException
{
out.print("Name ");
String name=MyClass.br.readLine();
out.print("Age : ");
int age=MyClass.sc.nextInt();
if(age>=18)
out.printf("Dear %s you can vote", name);
else
out.printf("Dear %s you cannot vote",name);
}

}
20.02.2011
What is Class?
What is Object?
What is Reference?
How object different from Reference?
What is Class?
A class is a set of specifications or blueprint about an entity to create similar set of objects.
A class defines a set of attributes and behavior about the entity. A class is user defined data
type created with class keyword.
class <classname>
{
//members
}
Members inside a class
A class can have three kinds of members
Fields or Attributes
Methods or Behaviors
Static Objects
Types of class members
These members can be categorized in two categories
1. Static or Class Members
2. Non-Static or instance members
Class members do not require an object to use them but can be used though the objects.
Use static keyword with such members.
Instance members always require an object.
What is an object?
A real entity created based on class specifications is called object or instance. Use new
keyword along with special method called Constructor to create an object.
To use the object for different operations we need to hold reference of it.
<classname> <referencename>=new <constructor>(<arguments>);
Example
Number x=new Number()

Number y=new Number();


What is a Constructor?
A constructor is a special method inside a class having some features
1.
2.
3.
4.

Same name as class


No return type
Used to initialized fields of an object
If no constructor is created then default or blank constructor is created
automatically, but if create any parameterized constructor then blank constructor is
not created automatically, we have to create it, if required.
5. Constructors can be overloaded
6. Constructor can be private as well
Note:

Use JAVAP tool of JDK to view members inside a class.


Data can be passed to the instance variable using two ways
i. Using constructor
ii. Using methods

E.g.
JAVAP Number
Example 1
Create a class Number having a num as field to get the data. Create some methods like
square(), cube(), cuberoot() on data. Pass data to num using a method like setNumber().
class Number
{
double num;
void setNumber(double n)
{
num=n;
}
double square() //non-static
{
return num*num;
}
double cube() //non-static
{
return square()*num;
}
double cubeRoot() //non-static
{
return Math.pow(num,1.0/3);
}
}

class Test
{
public static void main(String args[])
{
Number x=new Number();
Number y=new Number();
x.setNumber(6);
y.setNumber(9);
System.out.println(x.cubeRoot());
System.out.println(y.cubeRoot());
}
}

Example 2
Create a class Number having a num as field to get the data. Create some methods like
square(), cube(), cuberoot() on data. Pass data to num using a constructor.
class Number
{
double num;
Number(double n)
{
num=n;
}
double square() //non-static
{
return num*num;
}
double cube() //non-static
{
return square()*num;
}
double cubeRoot() //non-static
{
return Math.pow(num,1.0/3);
}
}
class Test
{
public static void main(String args[])
{
Number x=new Number(6);
Number y=new Number(9);
System.out.println(x.cubeRoot());
System.out.println(y.cubeRoot());

}
}
Example 3
Create a class Number having a num as field to get the data. Create some methods like
square(), cube(), cuberoot() on data. Pass data to num using a constructor or using a
method.
class Number
{
double num;
Number()
{
}
Number(double n)
{
num=n;
}
void setNumber(double n)
{
num=n;
}
double square() //non-static
{
return num*num;
}
double cube() //non-static
{
return square()*num;
}
double cubeRoot() //non-static
{
return Math.pow(num,1.0/3);
}
}
class Test
{
public static void main(String args[])
{
Number x=new Number();
x.setNumber(6);
Number y=new Number(9);
System.out.println(x.cubeRoot());
System.out.println(y.cubeRoot());
}
}

Example 4
What happens when parameter name and field names are same. In such cases use this
keyword to refer the current object
class Number
{
double num;
Number()
{
}
Number(double num)
{
this.num=num;
}
void setNumber(double num)
{
this.num=num;
}
double square() //non-static
{
return num*num;
}
double cube() //non-static
{
return square()*num;
}
double cubeRoot() //non-static
{
return Math.pow(num,1.0/3);
}
}
class Test
{
public static void main(String args[])
{
Number x=new Number();
x.setNumber(6);
Number y=new Number(9);
System.out.println(x.cubeRoot());
System.out.println(y.cubeRoot());
}
}
Assignment
Create a class Customer having fields accno, name and balance. Create constructor to open
an account. Create methods deposit(), withdraw() and showBalance().

class Customer
{
int accno;
String name;
double balance;
Customer(int accno, String name, double opamount)
{
this.accno=accno;
this.name=name;
balance=opamount;
}
void deposit(double amount)
{
balance+=amount;
}
void withdraw(double amount)
{
balance-=amount;
}
void showBalance()
{
System.out.println("Current Balance is : "+balance);
}
}
class ICICI
{
public static void main(String args[])
{
Customer c=new Customer(123,"Amit Verma",9000);
c.deposit(5000);
c.withdraw(3400);
c.showBalance();
}
}
Home assignment
Create a class Book having field bookno, title, author, status, lastissuedate and price. Create
constructors and methods to create an instance of book.
Create method issue(), receive() and isavailable(), getIssueDate().
Test the application with three books.
Solution
public class Book
{

int bookno;
String title,author,lastissuedate=null;
boolean status=true;
double price;
public Book()
{
}
public Book(int bookno, String title, String author, double price)
{
this.bookno=bookno;
this.title=title;
this.author=author;
this.price=price;
}
String getTitle()
{
return title;
}
void setData(int bookno, String title, String author, double price)
{
this.bookno=bookno;
this.title=title;
this.author=author;
this.price=price;
}
public void issue(String issuedate)
{
lastissuedate=issuedate;
status=false;
}
public String getIssueDate()
{
return lastissuedate;
}
public boolean isAvailable()
{
return status;
}
public void recieve(String rcvdate)
{
lastissuedate=null;
status=true;
}
public static void main(String[] args)
{
Book b[]=new Book[3];
b[0]=new Book(12,"Programming in C","Balgurwawmi",600);

b[1]=new Book(13,"Programming in Java","James Gosling",750);


b[2]=new Book(15,"Programming in .NET","Microsoft Press",567);
b[0].issue("12-Feb-2011");
if(b[0].isAvailable())
System.out.println("Book "+b[0].getTitle()+ " is avaible");
else
System.out.println("Book "+b[0].getTitle()+ " is not availble");

}
}

26.02.2011
Pillars of OOPs
Encapsulation
It stats that place all the members of a class under one body.
class <classname>
{
//members
}
Abstraction
Java provides four abstraction layers to control the accessibility of members.
-

Private
o Within the class
Public
o Anywhere access
Protected
o In current class or in child class
Package (default)
o Within the package or current folder

What is a package?
How to create a package?
How to use a package?
How to distribute a package?
What is JAR?
Package
A package is a folder having related set of classes which can be bundled into a JAR or ZIP
file.
Each of the classes placed in a package must have package command on top.
package <packagename>;
How to create a package?
Create a folder to hold your packages.
e.g. d:\pkg17
Now decide the package name

e.g. testpackage
Now create the classes and place into this package folder. Each of such classes must have
package command on top.
package testpackage;
public class General
{
public static long factorial(int n)
{
if(n==0 || n==1)
return 1;
else
return n*factorial(n-1);
}
}
Using the package
-

Import the classes of the package


Set the classpath to lookup the classes and package on the disc

Set classpath=%classpath%;d:\pkg17;
package testpackage;
public class General
{
public static long factorial(int n)
{
if(n==0 || n==1)
return 1;
else
return n*factorial(n-1);
}
}
Distributing the package
Convert the folder into a JAR or ZIP
To create the zip file, select all the package and convert into a zip file and set into classpath
Example
set classpath=%classpath%;c:\testpackage.zip;
Creating JAR files (Java Archive)
Create JAR file using JAR.EXE tool with options

c for create
t for Tabulate
x for Extract
v for Verbose
f for File Name
JAR cvf <filename.jar> <file list>
Example
First goto the folder having packages
JAR cvf test.jar .
Now set the test.jar file into classpath
set classpath=%classpath%;c:\test.jar;
27.02.2011
Polymorphism
When an items can perform more than one task, it is called as polymorphism. It is a
concept which get implemented using overloading.
Java allows only method overloading.
When two or more methods have the same name but different number of arguments or type
of arguments, called as method overloading.
Return type do not participate in overloading.
Example
Create a class Test having three methods to calculate area of circle, square and rectangle.
class Test
{
public void area(int side)
{
System.out.println("Square is "+side*side);
}
public void area(double r)
{
System.out.println("Square is "+Math.PI*r*r);
}
public void area(int l, int w)
{
System.out.println("Area is "+l*w);
}
}

Inheritance
Most important pillar of OOPs which provides re-usability of code. Classes can be at three
levels
1. Parent class
2. Super class
3. Child class
All classes in Java are child of Object class.
Java allows only single inheritance.
Use extends keyword to inherit a class into other class.
class A
{
}
class B extends A
{
}
If B is a current class, A is super class and Object is parent class.
Use this keyword to refer object of current class and super keyword to refer object of super
class.
Example
Create a Num2 having two fields a, b. Create methods to return bigger one and product of
those numbers.
Create another class Num3 working on three numbers. Also create method for product and
biggest one.
Use inheritance.
class Num2
{
int a,b;
public Num2(int a, int b)
{
this.a=a;
this.b=b;
}
public int g2()
{
return a>b?a:b;
}

public int p2()


{
return a*b;
}
}
class Num3 extends Num2
{
int c;
public Num3(int a, int b, int c)
{
super(a,b);
this.c=c;
}
public int p3()
{
return p2()*c;
}
public int g3()
{
return g2()>c?g2():c;
}
}
class IntTest
{
public static void main(String args[])
{
Num3 x=new Num3(4,5,6);
System.out.println(x.p3());
}
}
Method Overriding
A method in parent class, re-written in child class with same signature but different
contents, is called as method overriding.
While overriding we can increase the scope of overridden method but cannot decrease it.
class Num2
{
int a,b;
public Num2(int a, int b)
{
this.a=a;
this.b=b;
}
public int greatest()
{

return a>b?a:b;
}
public int product()
{
return a*b;
}
}
class Num3 extends Num2
{
int c;
public Num3(int a, int b, int c)
{
super(a,b);
this.c=c;
}
public int product() //overriding
{
return super.product()*c;
}
public int greatest() //overriding
{
return super.greatest()>c?super.greatest():c;
}
}
class IntTest
{
public static void main(String args[])
{
Num3 x=new Num3(4,5,6);
System.out.println(x.product());
}
}

Method overriding is mainly used for Runtime Polymorphism or Dynamic Method


Dispatch (DMD).
05.03.2011
Golden rule of Inheritance
A parent can hold reference to its childs and invoke only those methods of child whose
signature is provided from parent to the child.
Runtime Polymorphism

When reference of a parent is re-used to hold reference of multiple child classes, it is called
as runtime polymorphism.
It allows to execute the methods of childs using the same reference, it is called as dynamic
method dispatch (DMD).
It can be done only if method overriding is done.
Example
class A
{
public void show()
{
System.out.println("Calling from A");
}
}
class B extends A
{
public void show() //Overriding
{
System.out.println("Calling from B");
}
public void welcome()
{
System.out.println("Welcome to B");
}
}
class C extends B
{
public void show() //overriding
{
System.out.println("Calling from C");
}
}
class D
{
public void show()
{
System.out.println("Calling from D");
}
}
class X
{
public static void main(String args[])

{
A p; //Runtime polymorphism
p=new A();
p.show();
p=new B();
p.show();
p=new C();
p.show(); // dynamic method dispatch (DMD)
}
}
Types of classes
Java provides three kinds of classes
1. Concrete class
2. Abstract class
3. Final class
A class that can be instantiated and can also be inherited, is called as concrete class. It is by
default.
class X
{
}
A class that is always made for inheritance purpose only but can never be instantiated, such
classes is called as abstract class. Use abstract keyword to declare a class as abstract. An
abstract class may or may not have any abstract method but if a class contains any abstract
method the class must be declared as abstract.
A class that can be instantiated but can never be inherited is called as final class. Use final
keyword to create such classes.
Types of Methods
The methods again can be of three types
1. Concrete methods
2. Abstract methods
3. Final methods
Concrete methods
A method having the body contents and allows to overriding the contents, is called as
concrete method. It is by default.

Abstract methods
When a method has the signature but no body contents, it is called as abstract method. Such
methods can be declared at two places
1. Inside an abstract class
2. Inside an interface
If declared inside an abstract class, use abstract keyword but if declared inside an interface
then no keyword is required. All methods inside an interface are public and abstract by
default.
Abstract methods are made for overriding purpose only.
Final methods
A method that can be used in child class but can never be overridden is called as final
method. Use final keyword with such methods
Method Overloading Vs Method Overriding
Multiple methods having same name but different signatures in same or child class is called
as method overloading.
When a method of parent class, re-written in child class is called as overriding. It can never
be in same class.
While overloading we can increase or decrease the scope of overridden method but while
overriding we can increase the scope of overridden method but can never decrease it.

Example
Create a class as Common to manage common data of Customer, Vender and Employee
like name, email,mobile etc.
abstract class Common
{
private String name,email,mobile;
public Common()
{
}
public Common(String name, String email, String mobile)
{
this.name=name;
this.mobile=mobile;
this.email=email;
}
public void setName(String name)

{
this.name=name;
}
public String getName()
{
return name;
}
public void setEmali(String email)
{
this.email=email;
}
public String getEmail()
{
return email;
}
public void setMobile(String mobile)
{
this.mobile=mobile;
}
public String getMobile()
{
return mobile;
}
}
class Customer extends Common
{
private int cid;
public Customer()
{
}
public Customer(int cid,String name, String email,String mobile)
{
super(name,email,mobile);
this.cid=cid;
}
public void setCid(int cid)
{
this.cid=cid;
}
public int getCid()
{
return cid;
}
}
class Vendor extends Common
{
}

class Employee extends Common


{
}
public class Inheritance
{
public static void main(String[] args)
{
Customer c=new Customer();
c.setCid(456);
c.setName("Rakesh");
c.setEmali("rakesh@gmail.com");
c.setMobile("9898889889");
System.out.printf("Name is %s, Email is %s and CID is
%d",c.getName(),c.getEmail(),c.getCid());
}
}

Interfaces
A user defined data type very similar to class but contains all abstract methods and final
fields. All methods are public and abstract by default and all fields are public and final by
default.
It allows implementing multiple inheritance in Java.
Use interface keyword to declare an interface
When inheriting an into a class use implements keyword
When inheriting an interface into another interface use extends keyword
Example
public interface Finance
{
void budget();
}
public interface Hr
{
void salaryInfo();
}
public class ERP implements Hr,Finance
{
public void budget()
{
System.out.println("Budget is 4Cr");
}
public void salaryInfo()
{
System.out.println("Salary will be given on 7th");
}
}
class ITC
{
public static void main(String args[])
{
Hr x=new ERP();
x.salaryInfo();
Finance f=new ERP();
f.budget();
}
}
06.03.2011

What are the finals?


If used with fields, makes the constant
If used with the method, do not allows the method to overriding
If used with class, do not allow to inherit a class
static blocks
static constructor
Finalizer
Garbage collection
Can we run some before the entry point?
Yes, using static blocks.
Can we run a Java program without using entry point?
Yes, using static block.
Can be initialize static fields?
Yes, using static blocks
What is the output of following?
class Test
{
static
{
System.out.println("Hi");
}
public static void main(String args[])
{
System.out.println("Hello");
}
static
{
System.out.println("Kese Ho");
}
}
Output
Hi
Kese Ho
Hello
Static Blocks

A block of code which always executes before the entry point


static
{
//statements
}
Example
class Test1
{
static
{
System.out.println("Hi");
System.exit(0);
}
}

class Test1
{
static int num;
static
{
num=6;
System.out.println(num);
System.exit(0);
}
}
What is Finalizer?
A method from Object class which automatically get called when object is garbage
collected by the Garbage Collector.
protected void finalize()
We need to override this method in our class to provide some cleanup work.

Can be forcibly call the Garbage Collector?


Yes, using System.gc() method
Creating .jar file using NetBeans

Create a new project as Java Class Library


Add your packages
Add classes within the packages
Build the project
It creates a .jar file under dist folder
Using a .jar file in NetBeans
Create a new project and add your .jar file into libraries
Revision
1. import
2. import static
3. this
4. super
5. extends
6. implements
7. abstract
8. final
9. static
10. interface
11. class
12. for-each loop
13. finalize()
Arrays
Array is again a variable that can hold multiple values of similar data type. Use new
keyword to create an array. Each array is treated like object and provides length property.
int num[]=new int[5];
int num[][]=new int[3][4];
Object x[]=new Object[5];
We can use a variable to define size of array.

Example
//Array Test
class ArrayTest1
{
public static void main(String args[])
{

int num[]=new int[5];


num[0]=56;
num[1]=577;
num[2]=333;
num[3]=222;
num[4]=555;
for(int i=0;i<num.length;i++)
System.out.println(num[i]);
Object x[]=new Object[5];
x[0]=678;
x[1]=56.89;
x[2]='a';
x[3]="Amit";
x[4]=new java.util.Date();
for(int i=0;i<x.length;i++)
System.out.println(x[i]);
}
}
Using foreach loop
A variant of for loop which works with arrays and collections only. It works without
knowing size of array and array indexing.
for(datatype variable : arrayname)
{
Statements;
}
Example
//Using foreach loop
class ForEachTest
{
public static void main(String args[])
{
int num[]=new int[5];
num[0]=56;
num[1]=577;
num[2]=333;
num[3]=222;
num[4]=555;

for(int x : num)
System.out.println(x);
}
}
Example
WAP to create an array of user defined size and find the sum of all the numbers in array
import java.util.Scanner;
class ArrayTest2
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int num;
System.out.print("Size of array : ");
num=sc.nextInt();
int ar[]=new int[num];
int sum=0;
for(int i=0;i<ar.length;i++)
{
System.out.printf("Enter number %d : ",i+1);
ar[i]=sc.nextInt();
sum+=ar[i];
}
System.out.println("Sum is : "+sum);
}
}

Abstract Window Toolkit (AWT)


It is a Java technology for GUI development using a set of classes provided under java.awt
package.
It provides three kinds of classes
1. Containers
2. Components
3. Supporting Classes

A container class is used to hold some components. Example


Frame, Applet, Dialog, Panel etc.
A component is again a class used for user interaction. Example
Label, Button, TextField, TextArea, Choice, Checkbox, Menu etc.
Supporting classes used to support the containers and the components. Examples
Font, Color, Dimension etc.
All components and containers are child of Component class which is an abstract class
which provides common methods for all components and containers

setSize(int w, int h)
setLocation(int x, int y)
setBounds(int x, int y, int w, int h)
setVisible(boolean value)
setEnabled(boolean value)
setBackground(Color c)

Example
Create a window based application in Java having a window of 200x300 and background
color as red
Method 1: without inheriting
import java.awt.*;
class FirstApp
{
public static void main(String args[])
{
Frame f=new Frame();
f.setSize(200,300);
f.setBackground(Color.red);
f.setVisible(true);
}
}
Method 2: Using inheritance
import java.awt.*;
class MyWindow extends Frame
{
public MyWindow()
{
setSize(300,300);

setBackground(Color.blue);
setVisible(true);
}
public static void main(String args[])
{
new MyWindow();
}
}
Working with containers
Each container is a class inherited from Container class which provides common methods
for all the containers

public void add(Component c)


public void setLayout(LayoutManager lm)

LayoutManager is an abstract class providing common method for all layout manager
classes

FlowLayout default for Applet


BorderLayout default for Frame and Dialog
GridLayout
GridBagLayout
CardLayout

Frame class
A container class which is required for any GUI based application. Every desktop
application must inherit from Frame class.
Constructors
Frame()
Frame(String title)
Methods
void setTitle(String title)
void setResizable(boolean value)
Component classes

Label
TextField
TextArea
Checkbox
Choice

List
Button
Menu
MenuItem
PopupMenu

Naming Convention of Controls


Use Hungarian notation given by Charles Simony of Hungary. It states that use three
character prefix to define the type of control along with purpose of control.
Label lbl
TextField txt
Button btn or cmd
Form frm
Checkbox chk
Option Button opt
Menu mnu
MenuItem mit
Example
cmdOk, txtNumber etc.

Label class
-

To place some text inside a container


o Label()
o Label(String text)
o void setText(String text)
o String getText()

TextField class
- To create single line text and password fields
o TextField()
o TextField(int columns)
o void setText(String text)
o String getText()
o void setEchoChar(char ch)
Button class
-

To create a push button

o
o
o
o

Button()
Button(String label)
void setLabel(String label)
String getLabel()

TextArea class
- To create multiline textbox
o TextArea()
o TextArea(int rows, int columns)
o void setText(String text)
o String getText()
Example
Create a form having a login, password and remarks. Also create a button Login Check
import java.awt.*;
class TestApp extends Frame
{
Label l1,l2,l3;
TextField t1,t2;
TextArea ta1;
Button b1;
public TestApp()
{
l1=new Label("Login");
l2=new Label("Password");
l3=new Label("Remarks");
t1=new TextField(20);
t2=new TextField(20);
t2.setEchoChar('*');
ta1=new TextArea(5,20);
b1=new Button("Login Check");
setLayout(new FlowLayout());
add(l1);add(t1);
add(l2);add(t2);
add(l3);add(ta1);
add(b1);
setSize(280,300);
setResizable(false);
setVisible(true);
}
public static void main(String args[])
{

new TestApp();
}
}
Placing components at specified position
First setLayout() as null
Use setBounds() method of the components to define the location
import java.awt.*;
class TestApp1 extends Frame
{
Label l1,l2,l3;
TextField t1,t2;
TextArea ta1;
Button b1;
public TestApp1()
{
l1=new Label("Login");
l2=new Label("Password");
l3=new Label("Remarks");
t1=new TextField(20);
t2=new TextField(20);
t2.setEchoChar('*');
ta1=new TextArea(5,20);
b1=new Button("Login Check");
setLayout(null);
l1.setBounds(20,50,80,20);t1.setBounds(100,50,100,20);
l2.setBounds(20,90,80,20);t2.setBounds(100,90,100,20);
l3.setBounds(20,130,80,20);ta1.setBounds(100,130,100,100);
b1.setBounds(100,250,100,20);
add(l1);add(t1);
add(l2);add(t2);
add(l3);add(ta1);
add(b1);
setSize(280,300);
setResizable(false);
setVisible(true);
}
public static void main(String args[])
{

new TestApp1();
}
}
Checkbox class
-

Used to create a checkbox and radio button. Checkbox allows to select none or all
items while radio button allows to select only one item from group
To create the radio buttons we need to make the groups using CheckboxGroup class
Constructors for Checkbox
o Checkbox()
o Checkbox(String text)
o Checkbox(String text, boolean checked)
Constructor for radio button
o Checkbox(String text, boolean checked, CheckboxGroup cg)
o Checkbox(String text, CheckboxGroup cg, boolean checked)
Methods
o boolean getState()

Choice class
-

Used to create a drop down list and allows to select only one item
o Choice()
Method
o void add(String item)
o String getSelectedItem()

List class
-

Allows to select multiple items


o List()
o List(int size)
o List(int size, boolean multiple)

Example
Create a checkbox having text Agree to Terms and Conditions and two radio buttons for
Gender Selection as Male or Female.
Also create a dropdown list having some country names.

Introduction to Events in Java


Each event in Java is an abstract method defined in some interface. Such interfaces are
called as listeners.

ActionListener
o For Button, MenuItem etc.
MouseListener
MouseMotionListener
KeyListener
o For TextField, TextBox etc.
ItemListener
o For Choice, List, Checkbox etc.
WindowListener
AdjustmentListener

All such interfaces are provided under java.awt.event package. All such interfaces
provides a pre-defined set of abstract method that we need to override to define the
functioning on different controls
Such system is known as Event Delegation Model.
Examples of methods
ActionListener interface
public void actionPerformed(ActionEvent e)
Methods of ActionEvent class
public Object getSource()
public String getActionCommand()
ItemListener interface
public void itemStateChanged(ItemEvent e)
KeyListener interface
public void keyReleased(KeyEvent e)
public void keyPressed(KeyEvent e)
public void keyTyped(KeyEvent e)
Methods of KeyEvent class
char getKeyChar()
void consume()
WindowListener interface
public void windowDeactivated(WindowEvent e)
public void windowActivated(WindowEvent e)
public void windowIconified(WindowEvent e)
public void windowDeiconified(WindowEvent e)
public void windowOpened(WindowEvent e)
public void windowClosed(WindowEvent e)
public void windowClosing(WindowEvent e)
MouseMotionListener

public void mouseMoved(MouseEvent e)


public void mouseDragged(MouseEvent e)
Methods of MouseEvent class
int getX()
int getY()
boolean isPopupTrigger() to trap the right click
Placing a delegate on the controls
Use addXXXListener() method on the control by defining the object of the class where the
corresponding method is overridden.
cmdSquare.addActionListener(this);
cmdCube.addActionListener(this);
import java.awt.*;
import java.awt.event.*;
class SampleApp extends Frame implements ActionListener
{
Label lblNumber,lblResult;
TextField txtNumber,txtResult;
Button cmdSquare,cmdCube;
public SampleApp()
{
lblNumber=new Label("Number");
lblResult=new Label("Result");
txtNumber=new TextField();
txtResult=new TextField();
txtResult.setEditable(false); //read only
cmdSquare=new Button("Square");
cmdCube=new Button("Cube");
cmdSquare.addActionListener(this);
cmdCube.addActionListener(this);
setLayout(null);
lblNumber.setBounds(30,50,60,20);txtNumber.setBounds(100,50,100,20);
lblResult.setBounds(30,90,60,20);txtResult.setBounds(100,90,100,20);
cmdSquare.setBounds(60,130,60,20);cmdCube.setBounds(130,130,60,20);
add(lblNumber);add(txtNumber);

add(lblResult);add(txtResult);
add(cmdSquare);add(cmdCube);
setSize(250,250);
setResizable(false);
setVisible(true);
}
public static void main(String args[])
{
new SampleApp();
}
public void actionPerformed(ActionEvent e)
{
double num=Double.parseDouble(txtNumber.getText());
double result=0.0;
if(e.getSource()==cmdSquare)
result=num*num;
else
result=num*num*num;
txtResult.setText(Double.toString(result));
}
}
Using Color Class
-

Provides some built-in colors and also provides the way to create new colors upto
24 bit
o Color(int red, int green, int blue)
Every color ratio can be 0 to 255 only

Creating Random Numbers


Use Math.random() method to get a random number between 0 and 1
Example 2
import java.awt.*;
import java.awt.event.*;
class SampleApp extends Frame implements
ActionListener,KeyListener,WindowListener,MouseMotionListener
{
Label lblNumber,lblResult;
TextField txtNumber,txtResult;
Button cmdSquare,cmdCube;

public SampleApp()
{
lblNumber=new Label("Number");
lblResult=new Label("Result");
txtNumber=new TextField();
txtNumber.addKeyListener(this);
txtResult=new TextField();
txtResult.setEditable(false); //read only
cmdSquare=new Button("Square");
cmdCube=new Button("Cube");
cmdSquare.addActionListener(this);
cmdCube.addActionListener(this);
setLayout(null);
lblNumber.setBounds(30,50,60,20);txtNumber.setBounds(100,50,100,20);
lblResult.setBounds(30,90,60,20);txtResult.setBounds(100,90,100,20);
cmdSquare.setBounds(60,130,60,20);cmdCube.setBounds(130,130,60,20);
add(lblNumber);add(txtNumber);
add(lblResult);add(txtResult);
add(cmdSquare);add(cmdCube);
addWindowListener(this);
addMouseMotionListener(this);
setSize(250,250);
setResizable(false);
setVisible(true);
}
public static void main(String args[])
{
new SampleApp();
}
public void actionPerformed(ActionEvent e)
{
double num=Double.parseDouble(txtNumber.getText());
double result=0.0;
if(e.getSource()==cmdSquare)
result=num*num;
else
result=num*num*num;
txtResult.setText(Double.toString(result));

}
public void keyPressed(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
int num=(int) e.getKeyChar();
//System.out.println(num);
if(!(num==8 || num==46 || (num>=48 && num<=57)))
e.consume();
}
public void windowDeactivated(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowClosing(WindowEvent e){System.exit(0);}
public void mouseDragged(MouseEvent e){}
public void mouseMoved(MouseEvent e)
{
String s=e.getX()+","+e.getY();
setTitle(s);
//int r=e.getX()%256;
//int g=e.getY()%256;
//int b=(e.getX()+e.getY())%256;
int r=(int)(Math.random()*255);
int g=(int)(Math.random()*255);
int b=(int)(Math.random()*255);
String x=r+","+g+","+b;
System.out.println(x);
Color c=new Color(r,g,b);
setBackground(c);
}
}
Different places to override the listeners
1. Same class
2. Inner class

3. Outer class
4. Anonymous class
Inner classes
A class within is a class is called as inner class. An inner can access all the resources of
containing class.

Using Adapter classes


-

Special classes corresponding to listeners which contains pre-overridden methods of


listeners
All those listeners who have only one method do not have any corresponding
adapter
o KeyListener KeyAdapter
o WindowListener WindowAdapter
o MouseMotionLister MouseMotionAdapter
o Etc.

Example
Write a windows application to close the application when we press x button and show the
current mouse position using Inner class and adapters
import java.awt.*;
import java.awt.event.*;
class InnerTest extends Frame
{
public InnerTest()
{
addMouseMotionListener(new ME());
addWindowListener(new WE());
setSize(300,300);
setVisible(true);
}
public static void main(String args[])
{
new InnerTest();
}
class ME extends MouseMotionAdapter
{
public void mouseMoved(MouseEvent e)
{
String x=e.getX()+","+e.getY();
setTitle(x);
}
}

class WE extends WindowAdapter


{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
}
Outer class
When the methods are overridden in any general class, such method is called as outer class
import java.awt.*;
import java.awt.event.*;
class OuterTest extends Frame
{
public OuterTest()
{
addMouseMotionListener(new ME(this));
addWindowListener(new WE());
setSize(300,300);
setVisible(true);
}
public static void main(String args[])
{
new OuterTest();
}
}
class ME extends MouseMotionAdapter
{
Frame f;
public ME()
{
}
public ME(Frame f)
{
this.f=f;
}
public void mouseMoved(MouseEvent e)
{
String x=e.getX()+","+e.getY();
f.setTitle(x);
}
}
class WE extends WindowAdapter
{
public void windowClosing(WindowEvent e)

{
System.exit(0);
}
}
Anonymous class
-

When we define the working on event while registering the event, without create
any other class, a class get created automatically by the compiler, such class is
called as anonymous class

import java.awt.*;
import java.awt.event.*;
class AnonymousTest extends Frame
{
Button b;
public AnonymousTest()
{
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseMoved(MouseEvent e)
{
String x=e.getX()+","+e.getY();
setTitle(x);
}
});
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
b=new Button("Click Me");
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
javax.swing.JOptionPane.showMessageDialog(null,"You Clicked Me");
}
});
setLayout(new FlowLayout());
add(b);
setSize(300,300);
setVisible(true);
}
public static void main(String args[])
{
new AnonymousTest();

}
}

03.04.2011
Applets
Special Java classes which get merged into HTML and provide
dynamicity into HTML
A class to be called as Java Applet must be inherited from
java.applet.Applet class
Applet class provide pre-defined method that we need to override
1. public void init()
2. public void paint(Graphics g)
3. public void showStatus(String s)
a. To show the message on status bar of the Web Browser
4. Image getImage(URL path, String filename)
5. URL getCodeBase()
6. URL getDocumentBase()
The class get loaded into browser and execute at the client side
so it must be declared as public.
Example
Write an applet to input a number and print cube root it on status
bar of the browser.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class FirstApplet extends Applet
{
Button b;
TextField t;
Label l;
public void init()
{
t=new TextField(10);
l=new Label("Number");
b=new Button("Cube Root");
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
double num=Double.parseDouble(t.getText());
double cb=Math.pow(num,1.0/3);
showStatus("Cube root is "+cb);
}

});
add(l);add(t);add(b);
}
}
Creating HTML Code
Merge the Applet into an HTML using <applet></applet> tag
<applet></applet> tag provides various attributes
code="classname"
width="x"
height="y"
codebase="folder name of class files or jar files"
archive="jar file name"
Example: FirstApplet.htm
<applet code="FirstApplet" width="200" height="200">
</applet>
Running the Applet
Applet can run using any of two methods
1. Using AppletViewer tool of JDK
2. Use Web Browser
a. To use the web browser, the browser must be Java
Enabled (Java Plugin)
Example
appletviewer FirstApplet.htm

Placing class files in different folder


When HTML and class files are in different folder then we need to
define the folder name having the class files.
Use codebase attribute of <applet></applet> tag to define the
folder name having the class files
<applet code="FirstApplet" width="200" height="200"
codebase="classes">
</applet>
Placing the classes into JAR files
Create a jar file and place all the files into .jar file
JAR cvf test.jar *.class
Now provide the information about the .JAR file to <applet> using
archive attribute
<applet code="FirstApplet" width="200" height="200"
archive="test.jar" codebase="classes">
</applet>
Using Text into Applet
Applets are GUI based and everything is drawn on the applet.
Graphics class provides built-in methods for drawing
public void drawString(String s, int x, int y)
To print the string in different colors use method
public void setColor(Color c)
Drawing lines and shapes
Use methods like drawLine() and drawEllipse() method
Example
import java.applet.*;
import java.awt.*;
public class GraphicsTest extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.drawString("Welcome to Applet",20,20);
}
}
<applet code="GraphicsApplet" width="300" height="200">

</applet>
Using Images into Applets
Load the image into memory using getImage() method of Applet class
public Image getImage(URL path, String filename)
To get the URL of the image file use methods of Applet class
public URL getCodeBase()
returns the path of folder having class file
public URL getDocumentBase()
returns the path of folder having HTML file
To draw the image onto the applet use method of Graphics class
public void drawImage(Image img, int x, int y, ImageObserver or)
public void drawImage(Image img, int x, int y, int w, int h,
ImageObserver or)
Here ImageObserver is an interface. We can draw image on all the
components which are inherited from ImageObserver interface
Applet is a child of ImageObserver and can be used to draw the images
Example

import java.awt.*;
import java.applet.*;
public class ImageApplet extends Applet
{
Image img;
public void init()
{
img=getImage(getDocumentBase(),"images/2.jpg");
}
public void paint(Graphics g)
{
g.drawImage(img,0,0,this);
}
}
<applet code="ImageApplet" width="400" height="400">
</applet>

Passing parameters to the applets


-

We can pass the data to the applet class using the HTML code using <param> sub
tag of <applet></applet> tag
<param> tag provides two attributes
o Name="parameter name"
o Value="parameter value"

Example
<param name="photo" value="2.jpg">
To read the data send by the parameter using getParameter() method of Applet class
String getParameter(String paramname)
Example
import java.awt.*;
import java.applet.*;
public class ParamApplet extends Applet
{
Image img;
public void init()
{
String fname=getParameter("photo");
img=getImage(getDocumentBase(),"images/"+fname);
}
public void paint(Graphics g)
{
g.drawImage(img,0,0,this);
}
}
<applet code="ParamApplet" width="200" height="200">
<param name="photo" value="2.jpg">
</applet>
<applet code="ParamApplet" width="200" height="200">
<param name="photo" value="6.jpg">
</applet>
What is repaint()?
A method of Applet class that can re-invoke the paint() method
Example
Create an applet to show the current mouse position using the mouse pointer

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class RepaintApplet extends Applet
{
int x,y;
public void init()
{
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseMoved(MouseEvent e)
{
x=e.getX();
y=e.getY();
repaint();
}
});
}
public void paint(Graphics g)
{
String s="Mouse is on : "+x+","+y;
g.drawString(s,x,y);
}
public void update(Graphics gr)
{
int r=x%256;
int g=y%256;
int b=(x+y)%256;
Color c=new Color(r,g,b);
setBackground(c);
}
}
<applet code="RepaintApplet" width="300" height="300">
</applet>

Creating Menus
Menu can be of two types
1. Drop down menu
2. Popup Menu
Creating Drop down menus
MenuBar
Menu
MenuItem
Menu
Use ActionListener on Menu and MenuItem for programming
Place the MenuBar on the Frame using setMenuBar() method of Frame class
Example
Create a menu Colors having three colors Red, Green and Blue. On click on any these
menu items change the background color of the form.
Use ellipses () to indicate a dialog.
Use hypen (-) to a separator lines
import java.awt.*;
import java.awt.event.*;
class MenuTest extends Frame implements ActionListener
{
MenuBar mb;
Menu colors;
MenuItem red,green,blue,pt;
public MenuTest()
{
mb=new MenuBar();
colors=new Menu("Colors");
red=new MenuItem("Red");
green=new MenuItem("Green");
blue=new MenuItem("Blue");
pt=new MenuItem("Popup Test...");
red.addActionListener(this);
green.addActionListener(this);
blue.addActionListener(this);
pt.addActionListener(this);
colors.add(red);
colors.add("-");
colors.add(green);

colors.add(blue);
colors.add(pt);
mb.add(colors);
setMenuBar(mb);
setSize(300,300);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==red)
setBackground(Color.red);
else if(e.getSource()==blue)
setBackground(Color.blue);
else if(e.getSource()==green)
setBackground(Color.green);
else
new PopupMenuTest();
}
public static void main(String args[])
{
new MenuTest();
}
}
Creating PopupMenu
Create a PopupMenu and add the Menu and MenuItem into it
Use show() method of PopupMenu class to show the menu
public void show(Component c, int x, int y)
Use mouseReleased() event to check the release of mouse and use isPopupTrigger()
method of MouseEvent class to know about the right click
boolean isPopupTrigger()
import java.awt.*;
import java.awt.event.*;
class PopupMenuTest extends Frame implements ActionListener
{
PopupMenu pm;
MenuItem red,green,blue,pt;
public PopupMenuTest()

{
pm=new PopupMenu();
red=new MenuItem("Red");
green=new MenuItem("Green");
blue=new MenuItem("Blue");
red.addActionListener(this);
green.addActionListener(this);
blue.addActionListener(this);
pm.add(red);
pm.add(green);
pm.add(blue);
add(pm);
addMouseListener(new MouseAdapter()
{
public void mouseReleased(MouseEvent e)
{
if(e.isPopupTrigger())
pm.show(e.getComponent(),e.getX(),e.getY());
}
});
setSize(300,300);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==red)
setBackground(Color.red);
else if(e.getSource()==blue)
setBackground(Color.blue);
else if(e.getSource()==green)
setBackground(Color.green);
else
new PopupMenuTest();
}
public static void main(String args[])
{
new PopupMenuTest();
}
}
Creating Executable Jar

Create a manifest file (.mft) by defining the startup project class name
Use the entry as
o Main-Class: classname <Press Enter>

Now create a JAR file using cvmf options

Now double click on MenuTest.jar file


Closing the current form only
Use dispose() method of the Frame

Java Database Connectivity (JDBC)


Java is a front-end that can be connected with any kind of backend like Oracle, MySql, MS Access etc.
Java provides all related classes and interfaces in java.sql
package
Different classes and interfaces used for database programming are
1.
2.
3.
4.
5.
6.
7.
8.
9.

java.lang.Class class
java.lang.System class
java.sql.DriverManager class
java.sql.Connection interface
java.sql.Statement interface
java.sql.PreparedStatement interface
java.sql.CallableStatement interface
java.sql.ResultSet interface
java.sql.ResultSetMetaData class

Generally Used databases


1.
2.
3.
4.

MS Access
Oracle
MySql
MS SQL Server

Steps to use the JDBC


1. Create a database e.g. MS Access
a. Batch17.mdb
or
b. Batch17.accdb
2. Create your tables
a. Employee
i. empid Numeric Primary Key
ii. name - text
iii. email - text
3. Create a data entry form to save the data

4. Create INSERT Command and test it


5. Java provides a default driver to work with MS Access called
as JDBC-ODBC Bridge

a. sun.jdbc.odbc.JdbcOdbcDriver
6. Open Database Connectivity (ODBC) is a Software from
Microsoft to hide the database information from a Java
Program
a. It is provided under control panel
b. To use a database using ODBC we need to create a Data
Source Name (DSN)
7. To use the MS Access as database with Java, we need to create
a data source name (DSN) from control panel, administrative
tools, odbc
a. Select System DSN
b. Add
c. Select Driver as Microsoft Access Driver (*.mdb)
d. Select your database with Select button
e. Define the DSN Name e.g. batch17
8. Load the Driver into memory
a. Use any of three methods
i. Class.forName(drivername);
ii. System.setProperty(jdbc.drivers,drivername);
iii. DriverManager.registerDriver(new drivername());
b. Example
i. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Try to connect with database and get reference of it using
getConnection() method of DriverManager class. It returns the
reference as Connection type interface
a. Connection cn=DriverManager.getConnection(url,login,password);
b. Example

i.

Connection cn=DriverManager.getConnection("jdbc:odbc:batch17");

10. Create an object to run the statement pass the reference to some
Statement type reference. Use createStatement() method of
Connection reference.
a. Statement st=cn.createStatement();
11. Execute the methods of Statement based on type of it
a. executeUpdate(sql)
i. for all NON-SELECT commands
b. executeQuery(sql)
i. for SELECT command only
12. Close the connection
a. cn.close()

10.04.2011
Using MySql as Database
MySql in an Open Source RDBMS.
Create your database
CREATE DATABASE batch17;

Make the database as current database


USE batch17;
View the name of current database
Select database();
Show the number of tables in the database
Show tables;
Create your tables
create table employee(empid int primary key, name varchar(50), email varchar(50));
Database Information
Host Name or Server Name: localhost or IP Address
Port No: 3306
Database: batch17
User Id: root
Password: pass
Driver Name: com.mysql.jdbc.Driver
Connector JAR: mysql-connector-java-5.0.0-beta-bin.jar
URL: jdbc:mysql://localhost:3306/batch17
Create your data entry form using NetBeans
Setting the classpath for JAR file of MySql

Using Parameters or Place Holders in SQL Statements

While creating SQL statement we can leave the place holders for data using ? where data
can be provided later on.
String sql="INSERT INTO employee VALUES(?,?,?)";
Such command can never be executed using Statement but we need PreparedStatement or
CallableStatement
CallableStatement is used for stored procedures only.
Use prepareStatement() method of Connection interface
PreparedStatement ps=cn.prepareStatement(sql);
Passing data to the place holders
Use setXXX() methods to pass the data
Example
setInt(1,empid);
setString(2, name);
setString(3, email);
Full Code
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class MySqlTest extends Frame
{
TextField t1,t2,t3;
Button b;
public MySqlTest()
{
t1=new TextField(20);
t2=new TextField(20);
t3=new TextField(20);
b=new Button("Save");
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int empid=Integer.parseInt(t1.getText());
String name=t2.getText();
String email=t3.getText();
try
{
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection
cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/batch17","root","pass");
String sql="INSERT INTO employee VALUES(?,?,?)";

PreparedStatement ps=cn.prepareStatement(sql);
ps.setInt(1,empid);
ps.setString(2, name);
ps.setString(3, email);
ps.executeUpdate();
cn.close();
}catch(Exception ex)
{
System.out.println(ex);
}
}
});
setLayout(new FlowLayout());
add(t1);add(t2);add(t3);add(b);
setSize(300,300);
setVisible(true);
}
public static void main(String args[])
{
new MySqlTest();
}
}
Exception Handling
An exception is a runtime error that can be trapped at run time.
It is a system to send an error message from the place an error
has occurred to the place a method get called.
Java provides five keyword for exception handling
1.
2.
3.
4.
5.

try
catch
throw
throws
finally

try-catch is block of statements to execute some statements and


trap the runtime errors.
try
{
statements
}catch(classname refname)
{
decision
}
One try can have many catch statements.
finally is again a block to always execute some code irrespective
to the exception.

Every exception is a class inherited from Exception class and have


Exception word associated with it.
Examples
IOException
FormatException
Etc.
Exception class provides some common methods for all the exception
classes
String getMessage()
String toString()
void printStackTrace()
Test Example
Write a program to input two numbers and print division of those
numbers.
import java.io.*;
class Divide
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.print("Number 1 : ");
int a=Integer.parseInt(br.readLine());
System.out.print("Number 1 : ");
int b=Integer.parseInt(br.readLine());
int c=a/b;
System.out.println("Dividion is : "+c);
return;
}catch(IOException ex)
{
System.out.println("Error found :
"+ex.getMessage());
}
catch(NumberFormatException ex)
{
System.out.println("Sorry! Only numbers are
allowed");
}
catch(ArithmeticException ex)
{
System.out.println("Sorry! Denominator cannot be
zero");
}
catch(Exception ex)
{

on 889898989");

System.out.println("Some error found... Kinly call

//ex.printStackTrace();
}
finally
{
System.out.println("Thanks for using our system");
}
}

Note: If System.exit() is invoked then finally will not execute


throw statement is used to throw an object of some exception kind
of class.
Use throws keyword to mark that a method throws some exception
Creating Custom Exceptions
Every exception is a class inherited from Exception class. Create
your own class as exception class and inherit Exception class into
it. Override the getMessage() and toString() methods
Example
Create an exception class as LowBalanceException to give a message
as Sorry! Low Balance. Unable to withdraw.
class LowBalanceException extends Exception
{
public String getMessage()
{
return "Sorry! Low Balance. Unable to Withdraw";
}
public String toString()
{
return "LowBalanceException: Sorry! Low Balance. Unable to
Withdraw";
}
}

Create a Customer class and create deposit() and withdraw()


method. Throw an exception as LowBalanceException if the amount
asked is more than balance.

class Customer
{
int cid;
String name;
int balance;

public Customer(int cid, String name, int opamount)


{
this.cid=cid;
this.name=name;
this.balance=opamount;
}
public void deposit(int amount)
{
balance+=amount;
}
public void withdraw(int amount) throws LowBalanceException
{
if(amount>balance)
throw new LowBalanceException();
balance-=amount;
}
void showBalance()
{
System.out.println(balance);
}
}
Create another class for a bank like ICICI to use the customer services
class ICICI
{
public static void main(String args[])
{
Customer c=new Customer(45,"Rakesh Verma",9000);
c.deposit(5000);
try
{
c.withdraw(30000);
}catch(LowBalanceException ex)
{
System.out.println(ex.getMessage());
}
c.showBalance();
}
}
16.04.2011
Using Oracle as database
-

To connect with Oracle we must have


o Server Name e.g. ora
o User Id e.g. scott
o Password e.g. tiger

Create a data source for Oracle using Driver


o Microsoft ODBC for Oracle

Create your tables


1. Product
a. pid - numeric
b. pname - varchar
c. price numeric
Create an application to save data
Example
package batch17_1604;
import java.sql.*;
import java.util.*;
public class Main
{
public static void main(String[] args) throws Exception
{
Scanner sc=new Scanner(System.in);
System.out.print("Product Id : ");
int pid=sc.nextInt();
System.out.print("Product Name : ");
String pname=sc.next();
System.out.print("Price : ");
double price=sc.nextDouble();
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
Connection
cn=DriverManager.getConnection("jdbc:odbc:batch17ora","scott","tiger");
String sql="INSERT INTO product VALUES(?,?,?)";
PreparedStatement ps=cn.prepareStatement(sql);
ps.setInt(1, pid);
ps.setString(2,pname);
ps.setDouble(3,price);
ps.executeUpdate();
cn.close();

System.out.println("Record has been saved");


}
}
Using MS SQL Server as Database
An RDBMS from Microsoft.
Start your Server
Create your database
Create your tables
2. Product
a. pid - numberic
b. pname - varchar
c. price numberic
Create your DSN using Driver
1. SQL Server
To create a DSN you must have
1. Server Name e.g. IMPECCABLETRAIN
2. Database e.g. batch17
package batch17_1604;
import java.sql.*;
import java.util.*;
public class UsingSqlServer
{
public static void main(String[] args) throws Exception
{
Scanner sc=new Scanner(System.in);
System.out.print("Product Id : ");
int pid=sc.nextInt();
System.out.print("Product Name : ");
String pname=sc.next();
System.out.print("Price : ");
double price=sc.nextDouble();
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
Connection cn=DriverManager.getConnection("jdbc:odbc:batch17ss");
String sql="INSERT INTO product VALUES(?,?,?)";
PreparedStatement ps=cn.prepareStatement(sql);
ps.setInt(1, pid);

ps.setString(2,pname);
ps.setDouble(3,price);
ps.executeUpdate();
cn.close();
System.out.println("Record has been saved");
}
}
Creating Stored Procedures
A stored procedure is set of SQL statements given some name. It can be executed from the
client side using different languages like Java, C#, VB, PHP etc.
Creating stored procedures in SQL Server
Select your database
Select Programmability
Select Stored Procedure
CREATE PROCEDURE SP_SaveProduct
@pid numeric(18,0)
,
@pname varchar(50),
@price numeric(18,2)
AS
BEGIN
INSERT INTO product VALUES(@pid,@pname,@price);
END
GO

Select it and press F5


Calling a stored Procedure from Java
Use CallableStatement interface. To create a reference use prepareCall() method of
Connection
package batch17_1604;
import java.sql.*;
import java.util.*;
public class UsingStoredProcedure
{
public static void main(String[] args) throws Exception
{
Scanner sc=new Scanner(System.in);
System.out.print("Product Id : ");

int pid=sc.nextInt();
System.out.print("Product Name : ");
String pname=sc.next();
System.out.print("Price : ");
double price=sc.nextDouble();
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
Connection cn=DriverManager.getConnection("jdbc:odbc:batch17ss");
CallableStatement cs=cn.prepareCall("{call SP_SaveProduct(?,?,?)}");
cs.setInt(1, pid);
cs.setString(2,pname);
cs.setDouble(3,price);
cs.executeUpdate();
cn.close();
System.out.println("Record has been saved");
}
}
Reading Records from database
-

Create the SELECT statements


Use executeQuery() method to get the result into some ResultSet interface

ResultSet executeQurey()
-

Use methods of ResultSet to move record pointer on different records


o boolean first()
o boolean last()
o boolean next()
o boolean previous()
To read the data from current records use getters
o getInt(column index or column name)
o getString(column index or column name)
o getDouble(column index or column name)
o etc.

Example
Read data of all products from SQL Server
import java.sql.*;
public class ReadRecord
{
public static void main(String args[]) throws Exception

{
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
Connection cn=DriverManager.getConnection("jdbc:odbc:batch17ss");
String sql="Select * from product";
PreparedStatement ps=cn.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
while(rs.next())
{
System.out.println(rs.getInt(1)+","+rs.getString(2)+","+rs.getDouble(3));
}
cn.close();
}
}

17.04.2011
Using MetaData
Meta data provides data over the data. To know about a result set
use ResultSetMetaData. It provides various methods
int getColumnCount()
Returns the count of columns
int getColumnName(int index)
String getColumnTypeName(int index)
To fetch the meta data from result set use getMetaData() method of
ResultSet.
import java.sql.*;
import java.util.Scanner;
class MetaDataTest
{
public static void main(String args[]) throws Exception
{
String sql="Select * from product";
DriverManager.registerDriver(new
sun.jdbc.odbc.JdbcOdbcDriver());
Connection
cn=DriverManager.getConnection("jdbc:odbc:batch09sql");
PreparedStatement ps=cn.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
int n=rsmd.getColumnCount();
System.out.println("Total Columns : "+n);

for(int i=1;i<=n;i++)
System.out.println(rsmd.getColumnName(i)
+","+rsmd.getColumnTypeName(i));
cn.close();
}

Placing database information outside the class


-

Create a file having key/value pairs by provide the driver


name, user name , password etc.
o driver=sun.jdbc.odbc.JdbcOdbcDriver
o dsn=batch17ss
Generally the file is saved as .properties
Read this file using file handling with class FileInputStream
Pass this file to another class of java.util package called
as Properties. This class breaks the data into key/value
pairs. Now read data from the reference using getProperty()
method

Example
//database.properties file
driver=sun.jdbc.odbc.JdbcOdbcDriver
userid=scott
password=tiger
dsn=batch17ora
import java.io.*;
import java.util.*;
class ReadFileInfo
{
public static void main(String args[])
{
FileInputStream fis=new
FileInputStream("database.properties");
Properties p=new Properties();
p.load(fis);

throws Exception

System.out.println("Driver : "+p.getProperty("driver"));
System.out.println("User id : "+p.getProperty("userid"));
System.out.println("Password : "+p.getProperty("password"));
System.out.println("DSN : "+p.getProperty("dsn"));
}

Setting the Icon of the frame and making full screen windows
import java.awt.*;
class DynamicSize extends Frame
{

public DynamicSize()
{
Toolkit t=Toolkit.getDefaultToolkit();
Dimension d=t.getScreenSize();
Image g=t.getImage("cut.png");
setIconImage(g);
setSize(d.width,d.height);
setVisible(true);
}
public static void main(String args[])
{
new DynamicSize();
}
}
Running an application from Java Class
Use ProcessBuilder class of java.util package
import java.util.*;
import java.awt.*;
import java.awt.event.*;
class NewProcess extends Frame implements ActionListener
{
Button b1,b2;
public NewProcess()
{
b1=new Button("Calculator");
b2=new Button("Notepad");
b1.addActionListener(this);
b2.addActionListener(this);
add(b1);add(b2);
setLayout(new FlowLayout());
setSize(300,300);
setVisible(true);
}
public static void main(String args[])
{
new NewProcess();
}
public void actionPerformed(ActionEvent e)
{
ProcessBuilder pb;
if(e.getSource()==b1)
pb=new ProcessBuilder("calc.exe");
else

pb=new ProcessBuilder("notepad.exe");
try
{
pb.start();
}catch(Exception ex)
{
javax.swing.JOptionPane.showMessageDialog(this,ex.getMessage());
}
}
}
Passing variable number of arguments
We can create own function which can accept variable number of argument. Use with
the data type in the arguments
It create a dynamic size array for argument
Example
Write a program which accepts some numbers and returns sum of those numbers
class VarArgs
{
static int sum(int... num)
{
int sum=0;
for(int k : num)
sum+=k;
return sum;
}
public static void main(String... args)
{
System.out.println(sum(4,5,6));
System.out.println(sum(4,5,6,8,9,45));
System.out.println(sum(4,5,6,8,9,45,12,3,4,5,6));
}
}
Swing
Advance GUI Programming in Java. Most of the classes are part of Java Foundation
Classes (JFC) architecture and start with J

1.
2.
3.
4.
5.
6.
7.
8.

JFrame
JDialog
JApplet
JPanel
JButton
JTextField
JTextArea
etc.

Example
import javax.swing.*;
import java.awt.*;
class SwingTest extends JFrame
{
JButton b1,b2,b3;
public SwingTest()
{
b1=new JButton("Red");
b2=new JButton("Green");
b3=new JButton("Blue");
setLayout(new FlowLayout());
add(b1);add(b2);add(b3);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setVisible(true);
}
public static void main(String args[])
{
new SwingTest();
}
}
Swing components are light weight component where every component do not required as
internal pointer called widgets unlike AWT components. All components of swing are not
the light weight component. All contains need an internal pointer and become heavy
weights.
AWT components are created using operating system support while Swing components are
drawn. Swing can provide multiple look and feels on same operating system.
JTextArea control
-

To input multiline text


Do not provide any scrollbars
Use JScrollPane control

import javax.swing.*;
import java.awt.*;
class JTextAreaTest extends JFrame
{
JTextArea ta;
public JTextAreaTest()
{
ta=new JTextArea(10,20);
JScrollPane jp=new JScrollPane(ta);
add(jp);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setVisible(true);
}
public static void main(String args[])
{
new JTextAreaTest();
}
}
JLabel Class
import javax.swing.*;
import java.awt.*;
class JLabelTest extends JFrame
{
JLabel jl;
public JLabelTest()
{
jl=new JLabel(new ImageIcon("file2.jpg"));
JScrollPane jp=new JScrollPane(jl);
add(jp);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setVisible(true);
}
public static void main(String args[])
{

new JLabelTest();
}
}
23.04.2011
Swing components provide some additional facilities
1.
2.
3.
4.
5.
6.

Using Hot keys or Mnemonics


Using Images
Using tooltips
Using Key Strokes
Multiple Look and feels
Built-in dialog for different operations

Using Mnemonics
A kind of hot key used with Alt+ some character
Use setMnemonic() method
controlname.setMnemonic(char ch)
or
controlname.setMnemonic(KeyEvent vk)
We can also use the virtual keys. A virtual key is constant defined corresponding to some
key on the keyboard. Starts with VK
KeyEvent.VK_A
KeyEvent.VK_B
KeyEvent.VK_1
KeyEvent.VK_2
KeyEvent.VK_F1
KeyEvent.VK_F12
Example
cmdSave=new Button(Save);
cmdSave.setMnemonic(S);
or
cmdSave.setMnemonic(KeyEvent.VK_S);
Adding Tooltips
Use setToolTipText() method
Adding images

Use ImageIcon() class


JLabel lblPhoto=new JLabel(new ImageIcon(test.jpg));
JButton cmdSave=new JButton(Save, new ImageIcon(save.jpg));

Using JFileChooser control


-

Select a file to open or save


o int showSaveDialog(parent)
o int showOpenDialog(parent)
o File getSelectedFile()
It returns an integer values as
o JFileChooser.CANCEL_OPTION
o JFileChooser.APPROVE_OPTION
o JFileCHooser.ERROR_OPTION
if an error occurs or the dialog is dismissed

Adding the KeyStroke


To add a keystroke, first create it
Use getKeyStroke() method of KeyStroke to create a keystroke we need the masking keys
1. Event.SHIFT_MASK
2. Event.ALT_MASK
3. Event.CTRL_MASK
Keystroke k=KeyStroke.getKeyStroke(Event.CTRL_MASK, KeyEvent.VK_O); //Ctrl+O
To add a keystroke, use setAccelerator() method
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JButtonTest extends JFrame implements ActionListener
{
JButton b1,b2;
JMenuBar mb;
JMenu m;
JMenuItem open,save;
public JButtonTest()
{
b1=new JButton("Save",new ImageIcon("images/save.gif"));

b2=new JButton("Delete",new ImageIcon("images/delete.gif"));


b1.setMnemonic('S');
b2.setMnemonic('D');
b1.setToolTipText("Save Record");
b2.setToolTipText("Delete Record");
mb=new JMenuBar();
m=new JMenu("File");
m.setMnemonic(KeyEvent.VK_F);
KeyStroke
k=KeyStroke.getKeyStroke(KeyEvent.VK_O,Event.CTRL_MASK); //Ctrl+O
open=new JMenuItem("Open");
open.setAccelerator(k);
open.addActionListener(this);
open.setMnemonic('O');
save=new JMenuItem("Save", new ImageIcon("images/save.gif"));
save.setMnemonic('S');
save.addActionListener(this);
m.add(open);
m.add(save);
mb.add(m);
setJMenuBar(mb);
setLayout(new FlowLayout());
add(b1);add(b2);
setSize(300,300);
setVisible(true);
}
public static void main(String args[])
{
new JButtonTest();
}
public void actionPerformed(ActionEvent e)
{
JFileChooser d=new JFileChooser();
if(e.getSource()==open)
{
if(d.showOpenDialog(this)==JFileChooser.APPROVE_OPTION)
{
String fname=d.getSelectedFile().getAbsolutePath();
JOptionPane.showMessageDialog(this,fname);
}

}
else
d.showSaveDialog(this);
}
}
Select a color using JColorChooser class
public static Color showDialog(parent, String caption, defaultcolor)
Example
Color c=JColorChooser.showDialog(this,"Select a new Color",Color.white);
Creating Toolbar
Create an object of JToolBar class and add JButton objects
Add the toolbar in North direction
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class JColorChooserTest extends JFrame implements ActionListener
{
JButton b;
JColorChooserTest()
{
b=new JButton("Click to change Color");
b.addActionListener(this);
setLayout(new FlowLayout());
add(b);
setSize(300,300);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Color c=JColorChooser.showDialog(this,"Select a new Color",Color.white);
b.setBackground(c);
}
public static void main(String args[])
{
new JColorChooserTest();
}
}

Getting reference of the Content Pane


A content pane is the top most layer of the container which contains all the components on
the container. To get reference of the content pane use getContentPane() method
Container cn=getContentPane();
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class LookAndFeel extends JFrame implements ActionListener
{
JMenuBar mb;
JMenu mnuChangeLook;
JMenuItem miWindow,miMotif,miMetal;
JTextField t1,t2,t3;
JButton b1,b2,b3;
public LookAndFeel()
{
mb=new JMenuBar();
mnuChangeLook=new JMenu("ChangeLook");
miWindow=new JMenuItem("Window");
miMotif=new JMenuItem("Motif");
miMetal=new JMenuItem("Metal");
mnuChangeLook.add(miWindow);
mnuChangeLook.add(miMotif);
mnuChangeLook.add(miMetal);
mb.add(mnuChangeLook);
miWindow.addActionListener(this);
miMetal.addActionListener(this);
miMotif.addActionListener(this);
t1=new JTextField(10);
t2=new JTextField(10);
t3=new JTextField(10);
b1=new JButton("First");
b2=new JButton("Second");
b3=new JButton("Third");
setLayout(new FlowLayout());
add(t1);add(t2);add(t3);
add(b1);add(b2);add(b3);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setJMenuBar(mb);
setSize(300,300);
setVisible(true);

}
public void actionPerformed(ActionEvent e)
{
try
{
if(e.getSource()==miWindow)
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
else if(e.getSource()==miMetal)
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
else
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
SwingUtilities.updateComponentTreeUI(getContentPane());
}catch(Exception ex)
{
JOptionPane.showMessageDialog(this,ex.getMessage());
}
}
public static void main(String args[])
{
new LookAndFeel();
}
}

String Handling
Collections and Utilities
Generics
Auto Boxing and Un-boxing
File Handling
Socket Programming
Multi Threading
Annotations
Query Session
24.04.2011
String Handling
Java provides some classes for string operations
String
StringBuffer
StringBuilder (Java 5.0)
String class manages static size strings.
StringBuffer and StringBuilder manage data in dynamic size.
String class is used to manage the string
1. As Literal
2. As Object
Case 1
class StringTest1
{
public static void main(String args[])
{
String x="Amit";
String y="Amit";
if(x==y) //value comparison
System.out.println("Equal");
else
System.out.println("Unequal");
}
}
Case 2

class StringTest2
{
public static void main(String args[])
{
String x=new String("Amit");
String y=new String("Amit");
if(x==y) //object comparison
System.out.println("Equal");
else
System.out.println("Unequal");
}
}
Case 3
class StringTest3
{
public static void main(String args[])
{
String x=new String("Amit");
String y=new String("Amit");
if(x.equals(y)) //value of object comparison
System.out.println("Equal");
else
System.out.println("Unequal");
}
Methods of String class
boolean equals(String s)
boolean startsWith(String s)
boolean endsWith(String s)
int indexOf(String s)
Retruns the position the string in another string. Returns -1 if not found
char chatAt(int index)
String toUpperCase()
String toLowerCase()

Using StringBuffer or StringBuilder


Both of the methods provide append() method to append any kind of data in same memory
storage and without wasting any memory

append(Object x)
reverse()
class StringTest
{
public static void main(String args[])
{
String name="Vikas kumar verma";
int p=name.indexOf("verma");
if(p==-1)
System.out.println("Not found");
else
System.out.println("Found at "+p);
char ch=name.charAt(1);
System.out.println(ch);
System.out.println(name.toUpperCase());
System.out.println(name.toLowerCase());
StringBuilder sb=new StringBuilder();
sb.append("Amit");
sb.append(" Kumar");
System.out.println(sb);
System.out.println(sb.reverse());
}
}
Collections
Special type of classes to manage dynamic set of objects. Java provides two kinds of
collections
Legacy collections
Framework based collections
All collections are provided under java.util package.
Legacy classes are provided from Java 1.0 and have their own pre-defined methods
1. Vector class
2. Hashtable class
3. Enumeration interface
Using Vector class
To manage single set of objects.

Vector()
void addElement(Object x)
Object elementAt(int index)
int size()
Example
Create a Vector to hold multiple kind of data
import java.util.*;
class VectorTest
{
public static void main(String args[])
{
Vector v=new Vector();
v.addElement(new Integer(56));
v.addElement(new String("Hello"));
v.addElement(new Double(4.5));
v.addElement(new Date());
System.out.println("Total elements : "+v.size());
for(int i=0;i<v.size();i++)
System.out.println(v.elementAt(i));
}
}
Example 2
Show only int type data
Note: Use instanceof operator
\ import java.util.*;
class VectorTest
{
public static void main(String args[])
{
Vector v=new Vector();
v.addElement(new Integer(56));
v.addElement(new String("Hello"));
v.addElement(new Double(4.5));
v.addElement(new Date());
v.addElement(new Integer(34));
System.out.println("Total elements : "+v.size());
for(int i=0;i<v.size();i++)
{
if(v.elementAt(i) instanceof Integer)
System.out.println(v.elementAt(i));

}
}
}
Example 3
Show the numbers. Also show the sum of numbers
import java.util.*;
class VectorTest
{
public static void main(String args[])
{
Vector v=new Vector();
v.addElement(new Integer(56));
v.addElement(new String("Hello"));
v.addElement(new Double(4.5));
v.addElement(new Date());
v.addElement(new Integer(34));
System.out.println("Total elements : "+v.size());
int sum=0;
for(int i=0;i<v.size();i++)
{
if(v.elementAt(i) instanceof Integer)
{
System.out.println(v.elementAt(i));
Integer ig=(Integer) v.elementAt(i);
sum=sum+ig.intValue();
}
}
System.out.println("Sum is :" +sum);
}
}

Generics
Special collection classes which allow to hold different kind of data by different objects of
same class.
Examples
ArrayList
LinkedList
Using ArrayList class
Allows to work as generic and non-generic
Non-Generic Type
Methods
ArrayList()
void add(Object x)
Object get(int index)
int size()
import java.util.*;
class ArrayListTest
{
public static void main(String args[])
{
ArrayList v=new ArrayList();
v.add(new Integer(56));
v.add(new String("Hello"));
v.add(new Double(4.5));
v.add(new Date());
v.add(new Integer(34));
System.out.println("Total elements : "+v.size());
int sum=0;
for(int i=0;i<v.size();i++)
{
if(v.get(i) instanceof Integer)
{
System.out.println(v.get(i));
Integer ig=(Integer) v.get(i);
sum=sum+ig.intValue();
}
}
System.out.println("Sum is :" +sum);
}
}

Generic Style
import java.util.*;
class GenericTest
{
public static void main(String args[])
{
ArrayList<Integer> v=new ArrayList<Integer>();
v.add(new Integer(56));
v.add(new Integer(34));
System.out.println("Total elements : "+v.size());
int sum=0;
for(int i=0;i<v.size();i++)
{
System.out.println(v.get(i));
sum=sum+v.get(i).intValue();
}
System.out.println("Sum is :" +sum);
}
}
Auto Boxing and UnBoxing
Auto boxing means conversion from value type to reference type and auto unboxing means
conversion from reference type to value
Integer x=56; // auto boxing
int y=x+6; // auto unboxing
import java.util.*;
class BoxingUnboxig
{
public static void main(String args[])
{
ArrayList<Integer> v=new ArrayList<Integer>();
v.add(56); //auto boxing
v.add(34);
System.out.println("Total elements : "+v.size());
int sum=0;
for(int i=0;i<v.size();i++)
{

System.out.println(v.get(i));
sum=sum+v.get(i); //auto unboxing
}
System.out.println("Sum is :" +sum);
}
}
Using Hashtable class
A class to manage key/value pairs
Hashtable()
void put(Object key, Object value)
Object get(Object key)
Enumeration keys()
Enumeration interface
An interface used to hold reference of some keys
boolean hasMoreElements()
Object nextElement()
import java.util.*;
class HashtableTest
{
public static void main(String args[])
{
Hashtable t=new Hashtable();
t.put("in","India");
t.put("ch","China");
t.put("pk","Pakistan");
System.out.println(t.get("pk"));
Enumeration e=t.keys();
while(e.hasMoreElements())
{
Object key=e.nextElement();
System.out.println(key+"/"+t.get(key));
}
}
}
Framework based collections

A set of collections introduced in Java 1.2


All such collections are inherited from Collection interface. It has three child interfaces
1. List interface
a. Single set of elements with duplicate allowed
2. Set interface
a. Single set of element but not allow duplicates
3. Map interfere
a. To manage key/value pairs
LinkedList class
-

A class which provide additional methods single set of operations

import java.util.*;
class LinkedListTest
{
public static void main(String args[])
{
LinkedList <String>l=new LinkedList<String>();
l.add("Amit");
l.add("Vikas");
System.out.println(l);
l.addFirst("Neeraj");
l.addLast("Rahul");
System.out.println(l);
l.set(3,"Keshav");
System.out.println(l);
Collections.sort(l);
System.out.println(l);
}
}
Stack class
To manage the values on stack. Provides three methods
1. push()
2. pop()
3. peek()
import java.util.*;
public class StackTest{
public static void main(String args[])
{
Stack st=new Stack();

st.push(new Date());
st.push(new Integer(5));
st.push(new Float(67.55));
System.out.println(st.toString());
System.out.println(st.pop());
System.out.println(st.toString());
System.out.println(st.peek());
System.out.println(st.toString());
}
}

30.04.2011
File Input/Output
Java provides built-in classes for file handling inside java.io package
1.
2.
3.
4.
5.

File class
FileReader
FileWriter
FileInputStream
FileOutputStream

File class is used to work with exising files and folder and allows to create new folder,
remove a file or folder, rename a file or folder, get properties of files and folders.
File(String filename with path)
File(String foldername, String filename)
public static File[] listRoots()
- Returns the list of drives in our machine
boolean exists()
boolean isFile()
boolean isDirectory()
long lastModified()
o Returns a number. To convert in real data use java.util.Date class
boolean mkdir() create a single directory
boolean mkdirs() creates a diretory structure
String [] list()
Returns list of file in given directory

Example 1
Show all drivers in our machine
import java.io.*;
public class Main
{
public static void main(String[] args)
{
File []f=File.listRoots();
for(File x : f)
System.out.println(x);
}
}
Example 2
Write a program to give a path and check it to be file or folder. If file, then given the file
size and last modification date.
If folder, list all the files in folder
package batch17_3004;
import java.io.*;
import java.util.*;
public class FileInfo
{
public static void main(String args[])
{
File f=new File("c:/");
if(f.exists())
{
//System.out.println("found");
if(f.isFile())
{
System.out.println("File found");
System.out.println("File size is : "+f.length());
System.out.println("Last Modified : "+ new Date(f.lastModified()));
}
else
{
System.out.println("Folder found");
String []lst=f.list();
for(String fl : lst)
System.out.println(fl);
}

}
else
System.out.println("not found");
}
}
Example 3
Write a program to create folder
package batch17_3004;
import java.io.*;
public class CreateDirectory
{
public static void main(String args[])
{
File f=new File("c:/abc/pqr/xyz");
if(f.mkdirs())
System.out.println("Folder created");
else
System.out.println("Folder Not created");
}
}
Assignment
1. Write a program to list all drives and theirs files and folders.
Example
Information of Drive : C:\
File
Folder
2. Create a GUI application having all drives listed is a Choice
a. When we select a drive show all its files and folders in textbox
Creating a file in Text Mode
Java files two classes to work with files
1. FileReader
2. FileWriter
Writing contents into a file
FileWriter f=new FileWriter(filename);

f.write(content);
f.close();
Reading contents of a file
Open a file using FileReader and pass it to some BufferedReader or Scanner class object.
Now read data line by line using readLine() or next() method
import java.io.*;
public class CreateTextFile
{
public static void main(String args[]) throws IOException
{
FileWriter f=new FileWriter("c:/sample.txt");
f.write("Hello to all\n");
f.write("Kese Ho");
f.close();
}
}
package batch17_3004;
import java.io.*;
public class ReadTextFile
{
public static void main(String args[]) throws IOException
{
FileReader fr=new FileReader("c:/sample.txt");
BufferedReader br=new BufferedReader(fr);
String s;
while((s=br.readLine())!=null)
{
System.out.println(s);
}
fr.close();
}
}
Working with files in binary mode
Use the classes as
1. FileInputStream
2. FileOutputStream
Conversion from string to binary format
To convert a string into a byte array using method of String class
public [] byte getBytes()

To convert the byte array into a string again use constructor of String class
String(byte []ar, int start, int length)
package batch17_3004;
import java.io.*;
public class CreatingBinaryFile
{
public static void main(String args[]) throws Exception
{
String x="Hi\nHello\nNeeraj";
FileOutputStream fs=new FileOutputStream("c:/testing.txt");
byte []b=x.getBytes();
fs.write(b);
fs.close();
}
}

package batch17_3004;
import java.io.*;
public class ReadBinaryFile
{
public static void main(String args[]) throws Exception
{
FileInputStream fs=new FileInputStream("c:/testing.txt");
int n;
while((n=fs.read())!=-1)
{
System.out.print((char)n);
}
fs.close();
}
}
Multi Threading
A thread is a light weight process within a process. Java provides Thread class and
Runnable interface to implement the multi Threading.
Runnable interface provides a run() method to define the working of a thread
All Java classes are single threaded by default. One thread is always present called as main
thread.
Methods of Thread class

Thread(Runnanble r)
Thread(Runnanble r,String threadname)
static Thread currentThread()
String getName()
int getPriority()
void start() to send a thread in thread queue
void sleep(int ms) throws InterruptedException
void sleep(int ms, int ns) throws InterruptedException

Example 1
class ThreadTest
{
public static void main(String args[])
{
Thread t=Thread.currentThread();
if(t!=null)
System.out.println("Thread found : "+t.getName());
else
System.out.println("No thread found");
}
}
Life Cycle of Thread
1.
2.
3.
4.
5.

Born State
Ready State
Running State
Block State
Dead State

Creating threads without any name


class MyThread implements Runnable
{
public MyThread()
{
Thread t=new Thread(this);
t.start();
}
public void run()
{
String s=Thread.currentThread().getName();
for(int i=1;i<=10;i++)
System.out.println(s+" : "+i);

}
public static void main(String args[])
{
new MyThread();
new MyThread();
new MyThread();
}
}
Creating Thread with name
class MyThread implements Runnable
{
public MyThread(String tname)
{
Thread t=new Thread(this,tname);
t.start();
}
public void run()
{
String s=Thread.currentThread().getName();
for(int i=1;i<=10;i++)
System.out.println(s+" : "+i);
}
public static void main(String args[])
{
new MyThread("Pepsi");
new MyThread("Coke");
new MyThread("Fanta");
}
}
Providing Different task for different threads
class MyThread implements Runnable
{
public MyThread(String tname)
{
Thread t=new Thread(this,tname);
t.start();
}
public void run()
{
String s=Thread.currentThread().getName();
if(s.equals("Pepsi"))
{
for(int i=1;i<=10;i++)
System.out.println(s+" : "+i);
}
else if(s.equals("Coke"))

{
for(char ch='A';ch<='Z';ch++)
System.out.println(s+" : "+ch);
}
else
{
for(int n=5;n<=100;n+=5)
System.out.println(s+" : "+n);
}
}
public static void main(String args[])
{
new MyThread("Pepsi");
new MyThread("Coke");
new MyThread("Fanta");
}
}
Using sleep time
class MyThread implements Runnable
{
public MyThread(String tname)
{
Thread t=new Thread(this,tname);
t.start();
}
public void run()
{
String s=Thread.currentThread().getName();
if(s.equals("Pepsi"))
{
for(int i=1;i<=10;i++)
{
System.out.println(s+" : "+i);
try{Thread.sleep(5);}catch(Exception ex){}
}
}
else if(s.equals("Coke"))
{
for(char ch='A';ch<='Z';ch++)
{
System.out.println(s+" : "+ch);
try{Thread.sleep(1);}catch(Exception ex){}
}
}
else

{
for(int n=5;n<=100;n+=5)
{
System.out.println(s+" : "+n);
try{Thread.sleep(6);}catch(Exception ex){}
}
}
}
public static void main(String args[])
{
new MyThread("Pepsi");
new MyThread("Coke");
new MyThread("Fanta");
}
}
01.05.2011
Usage of Multi Threading
-

Create a thread and define the location of run()


Give working to the run()
Define the interval

Example 1
Create an applet to show the current date and time on status bar updated every second and
show some images one by one after every 3 seconds.
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class ThreadUse1 extends JApplet implements Runnable
{
int i;
public void init()
{
Thread t=new Thread(this);
t.start();
Thread photos=new Thread(new ShowPhoto());
photos.start();
i=1;
}
public void paint(Graphics g)
{
String fname=i+".jpg";
Image img=getImage(getDocumentBase(),fname);
g.drawImage(img,0,0,this);
i++;
if(i==4) i=1;

}
public void run()
{
for(;;)
{
Date d=new Date();
showStatus(d.toString());
try
{
Thread.sleep(1000);
}catch(Exception ex){}
}
}
class ShowPhoto implements Runnable
{
public void run()
{
for(;;)
{
repaint();
try
{
Thread.sleep(3000);
}catch(Exception ex)
{
}
}
}
}
}
Deadlocks
When two or more threads try to access the same resource then their could be a collision.
To manage the deadlocks, Java provides a keyword synchronized.
It can be used with a method or a block.
synchronized <method>()
{
}
<method>()
{
synchronized(this)
{
//statements
}
}

Inter Thread Communication


When one thread needs data from other thread the use inter thread communication. If data
is not available then thread has to wait. When data is available a notification should be
issued.
Use wait() method to send the thread in wait condition
Use notify() or notifyAll() methods to send the thread in running state
Note: wait(), notify() and notifyAll() are the methods provided under Object class
Example
Producer-Consumer Problem
Producer class (Thread)
Consumer class (Thread)
Stock class (items common resource need protection)
Networking or Socket Programming
Java provides communication between two or more computers using special classes under java.net
package
Java provides two kind of communication
1. TCP/IP Based Communication
2. UDP (User Datagram Protocol) based communication
TCP/IP communication need connected mode between client and server and it is counted as reliable
communication.
UDP is a connection less communication and counted as un-reliable communication.
Classes used for TCP/IP Communication
1. Socket class
2. ServerSocket class
ServerSocket class is used on server side to create a server that can interact with multiple clients.
Socket is used to lookup the ServerSocket and make the communication between client and server.
For client/server communication we need two things
1. IP Address or DNS (Domain Name Server)
2. Port Number
A port number is a logical number assigned to some application to provide client/server
communication. A machine can have 65536 (0-65535) ports.

Some ports are taken by default by different applications


1.
2.
3.
4.
5.
6.

HTTP 80
SMTP 25 (Simple Mail Transfer Protocol)
FTP 21
Java Server (Tomcat etc.) 8080
Oracle 1521
MySql 3306

Creating a Server
-

Create an object of ServerSocket class and define a port number


ServerSocket(int portno)

To wait for client and accept the reference of the client use accept() method
Socket accept()

Creating a client
-

Create an object of Socket class and lookup the server using IP address or DNS and the
port number
Socket(String ip address or dns, int port number) throws IOException

Example 1
import java.net.*;
import java.io.*;
class DemoServer
{
public static void main(String args[])
{
try
{
ServerSocket s=new ServerSocket(789);
System.out.println("Server is read and waiting for clients...");
Socket client=s.accept();
System.out.println("Client connected : "+client);
}catch(IOException ex)
{
System.out.println(ex.getMessage());
}
}
}
import java.io.*;
import java.net.*;
class DemoClient
{

public static void main(String args[])


{
try
{
Socket server=new Socket("localhost",789);
System.out.println("Server found : "+server);
}catch(IOException ex)
{
System.out.println("Server Not found");
}
}
}
To test the application open two command windows, run server in one window and client in another
window.
How Sockets communicate?
To send data to other machine get reference of OutputStream of other machine.
To read data from other machine, get reference InputStream of other machine
Use methods of Socket class
OutputStream getOutputStream()
InputStream getInputStream()
To send data from one machine to another machine in textual format, use PrintWriter class of
java.io package. It converts the string data into binary and passes to some OutputStream.
PrintWriter pw=new PrintWriter(OutputStream os, boolean send)
Make send as true for direct transfer and false for buffered transfer.
To read data from other machine use BufferedReader with InputStreamReader.
Test Case
Write an application to send welcome message from the server to the client when a client connects
with server.
import java.net.*;
import java.io.*;
class MyServer
{
public static void main(String args[]) throws IOException
{
ServerSocket s=new ServerSocket(5678);
System.out.println("Server is Ready...");
for(;;)
{
Socket client=s.accept();
System.out.println("Client connected : "+client);
PrintWriter pw=new PrintWriter(client.getOutputStream(),true);
pw.println("Welcome to my world");
}

}
}
import java.net.*;
import java.io.*;
class MyClient
{
public static void main(String args[])
{
try
{
Socket server=new Socket("localhost",5678);
BufferedReader br=new BufferedReader(new
InputStreamReader(server.getInputStream()));
System.out.println(br.readLine());
}catch(IOException ex)
{
System.out.println("Server Not found");
}
}
}
Using UDP Protocol
This protocol used using three classes
DatagramSocket
DatagramPacket
InetAddress
To send and receive data must have a data packet created using DatagramPacket class
DatagramPacket(byte []data, int size)
DatagramPacket(byte []data, int size, InetAddress ia, int port)
InetAddress class is used to get information about the machine to which data need to be send using
its static methods
public static InetAddress getLocalHost()
public static InetAddress getByName(String dns)
Note: When a static method of a class, returns reference of an object of its own class, such method
is called as factory method. Here getLocalHost(), getByName() are the examples of factory
methods.
To convert data from String type to byte array use getBytes() method of String class
String s=br.readLine();
byte []data=s.getBytes();
Creating Sockets
Create an object of DatagramSocket class in client and server application using a port number.

DatagramSocket(int port)
send(DatagramPacket p)
receive(DatagramPacket p)
Reading data from DatagramPacket
Use its methods
byte []getData()
int getLength()
Converting byte data back to string
Use constructor of String class
Sting s=new String(byte []data, start byte, length)

Servlet
A Java class that resides on some server to serve different client using a web browser. A
servlet is managed by a software called servlet containers or application server like

Tomcat
Web Logic
Web Sphare
JBoss
J2EE Server
Etc.

When a servlet container gets a request from a web client then it checks for the servlet and
then executes the class file and return the pure HTML code to the web client.
All classes related with the servlets are provides in two main packages
1. javax.servlet
2. javax.servlet.http
A class to be called as servlet must be inherited from javax.servlet.GenericServlet class or
javax.servlet.http.HttpServlet class
We need to override the methods provided in these classed to give custom functionality
GenericServlet class provides a method
public void service(ServletRequest req, ServletResponse res) throws ServletException
HttpServlet class also provides methods

public void doGet(HttpServletRequest req, HttpServletResponse res) throws


ServletException
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException
Reading data from Client
Use methods of ServletRequest or HttpServletRequest
String getParameter(String parametername)
Sending response to the client
To send the response to the client, we need to get reference of the client. Use getWriter()
method ServletResponse or HttpServletResponse class
PrintWriter out=res.getWriter();
Tomcat as Servlet Container
-

Install the Tomcat Server


Define your port number for Tomcat e.g. 8888
Give some password to admin e.g. pass

Test the server using following URL


http://localhost:8888
Default location for files
HTML/JSP
<tomcat>\webapps\ROOT
Class files
<tomcat>\webapps\ROOT\WEB-INF\classes
Example
<!-- emp.htm -->
<form action="/emp.bps" method="post">
Empid <input type="text" name="empid"><br>
Name<input type="text" name="name"><br>
Email<input type="text" name="email"><br>
<input type="submit" value="Save">
</form>
http://localhost:8888/emp.htm
Create the Servlet
package batch17;

import javax.servlet.*;
import java.io.*;
public class EmpServlet extends GenericServlet
{
public void service(ServletRequest req, ServletResponse res) throws
ServletException,IOException
{
String empid=req.getParameter("empid");
String name=req.getParameter("name");
String email=req.getParameter("email");
PrintWriter out=res.getWriter();
out.println("Welcome dear "+name);
}
}
Compiling the Servlet
Set the classpath by adding the servlet-api.jar file from
<tomcat>\common\lib
Example
set classpath=%classpath%;d:\Tomcat5.5\common\lib\servlet-api.jar;
Mapping inside the Deployment Descriptor (DD)
Tomcat provides a mapping configuration file as web.xml under
<tomcat>\webapps\ROOT\WEB-INF
Use <servlet> tag to define a servet name and map it with the class anme
Use <servlet-mapping> tag to map the web url with the servlet name
<servlet>
<servlet-name>e1</servlet-name>
<servlet-class>batch17.EmpServet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>e1</servlet-name>
<url-pattern>/emp.bps</url-pattern>
</servlet-mapping>

Introduction to JSP
Java Server Pages (JSP) is a text document having HTML and Java merged into same
document. Such pages get automatically converted into a servlet class by another container
called as JSP container.
In this model, Java get merged into HTML code. JSP also provides different components
for quick development

1.
2.
3.
4.
5.
6.

Scriptlet
Expression
Declaration
Intrinsic Objects
Directives
JSP Actions

Directives
Used to provide some instructions to the JSP container. Starts with <%@ and closes with
%>
Example
<%@ page language=java %>
<%@ page language=java import="java.sql.*,java.util.*" %>
<%@ include file="filename" %>
Intrinsic Objects
JSP provides some built-in objects
1.
2.
3.
4.
5.

out
request
response
session
application

Examples
out.println("Welcome");
response.sendRedirect("url");
Scriplets
Allows to merge Java code into HTML using <% and %> delimiters
Example
<h1>Testing for JSP</h1>
<%
out.println("Hello to JSP");
%>
Expressions
Used to show value of a variable or expression
Use <%= and %> delimiters
Example

<% double r=5.6; %>


Area is <%=Math.PI*r*r%>
JSP Actions
Special tags provided by JSP for advance operations. Such tags start with jsp:
<jsp:useBean/>
<jsp:setProperty/>
<jsp:getPropety/>
<jsp:include/>
<jsp:forward/>

Example
WAP to create a web application to show table of a give number using query string
http://localhost:8888/table.jsp?number=12
<%@ page language="java" %>
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
</head>
<body>
<table border="1" width="43%" id="table1">
<tr>
<td align="center"><b><font color="#FF0000">Number</font></b></td>
<td align="center"><b><font color="#FF0000">x</font></b></td>
<td align="center"><b><font color="#FF0000">Index</font></b></td>
<td align="center"><b><font color="#FF0000">=</font></b></td>
<td align="center"><b><font color="#FF0000">Product</font></b></td>
</tr>
<%
int n=5;
for(int i=1;i<=10;i++)
{
%>
<tr>

<td align="center"><%=n%>&nbsp;</td>
<td align="center">x&nbsp;</td>
<td align="center"><%=i%>&nbsp;</td>
<td align="center">=&nbsp;</td>
<td align="center"><%=n*i%>&nbsp;</td>
</tr>
<%
}
%>
</table>
</body>
</html>
08.05.2011
Working with RMI (Remote Method Invocation)
A client/server technology in Java to call the methods placed at server side and called as
client side.
It is based on another protocol called as RMI protocol (rmi://).
This protocol is understood by a software provided with JDK called as RMIREGISTRY
RMI Technology also provides special compiler called as RMIC to build the stub and
skelton of the methods to use the encryption while sending and receiving the data.
RMI technology uses port number 1099
Java RMI is provide in Java APIs
1. java.rmi
2. java.rmi.server
Such applications have different components
1. Interface declaring all possible method accessible to client
a. Such interface must inherit from java.rmi.Remote interface
b. All methods must throw an exception java.rmi.RemoteException
2. Implement this interface in some class
a. Such class must be inherited by another called as
java.rmi.server.UnicastRemoteObject
3. Create a server program to make the server ready to serve the clients
a. Such class must use rebind() method java.rmi.Naming class to bind the
implementation class with some user friendly server name
4. Create a client program to lookup the server
a. User lookup() method of java.rmi.Naming class to locate the server and get
response from the server.
5. Create stub and skelton classes using implementation class with RMIC tool
a. Stub is placed on client

b. Skelton is placed on server (optional after Java 5.0)


Naming Conventions
1.
2.
3.
4.

Project Name : interface name


Implementation class : <project name>Imp
Server Program : <project name>Server
Client Program : <project name>Client

Example
Create a distributed application for banking where an amount and period get passed and
return the total amount returned after that much of years.
Interface: Banking.java
Implementation class: BankingImp.java
Solution
import java.rmi.*;
public interface Banking extends Remote
{
double getTotalAmount(int amount, int years) throws RemoteException;
}
import java.rmi.*;
import java.rmi.server.*;
public class BankingImp extends UnicastRemoteObject implements Banking
{
public BankingImp() throws RemoteException
{
}
public double getTotalAmount(int amount, int years) throws RemoteException
{
double ta=amount*Math.pow(1.09,years) ;
return ta;
}
}
import java.rmi.*;
public class BankingServer
{
public static void main(String args[])
{
try
{

Naming.rebind("sbi", new BankingImp() );


System.out.println("Server is ready....");
}catch(Exception ex)
{
System.out.println("Error found : "+ex.getMessage());
}
}
}

import java.rmi.*;
import java.util.*;
public class BankingClient
{
public static void main(String args[])
{
try
{
Banking b= (Banking)Naming.lookup("rmi://localhost/sbi");
Scanner sc=new Scanner(System.in);
System.out.print("Total Amount to deposit : ");
int amount=sc.nextInt();
System.out.print("Years : ");
int years=sc.nextInt();
double amt=b.getTotalAmount(amount, years);
System.out.println("Total amount will be "+amt);
}catch(Exception ex)
{
System.out.println("Error : "+ex.getMessage());
}
}
}
Now create the Stub using the implementation class
RMIC BankingImp
Note: To view the contents of the Java file created before creation of stub file use following
option
RMIC keep BankingImp
Files to place to server
1. Interface
2. Implementation class
3. Server Program

Files to place on client


1. Interface
2. Stub
3. Client Program
Testing the application
Server Side
1. First start the RMIREGISTRY
2. Now run the server program
Client Side
1. Run the client program

Note:
Here Remote interface is called as Marker Interface. An interface used to mark something
for the compiler and do not provide any method to override is called as marker interface.
Reflection
A system to know about the meta information of a class/interface etc.
Java provides special set of class under java.lang.reflect package
Class
Method
Field
Constructor
First load the class into memory and get refernce of it
Class x=Class.forName("classname");
Use methods of Class class to get meta information
Method [] getMethods()
Field [] getFields()
Constuructor[] getConstuctors()
Example

Write a java program to get a class name at the command prompt and show all its fields,
methods and constuctors
import java.lang.reflect.*;
class ReflectionTest
{
public static void main(String args[]) throws Exception
{
if(args.length<1)
{
System.out.println("Syntax is : Java ReflectionTest <classname>");
return;
}
Class x=Class.forName(args[0]);
Constructor []c=x.getConstructors();
Method []m=x.getMethods();
Field []f=x.getFields();
System.out.println("Constructors");
for(Object t : c)
System.out.println(" ==>"+t);
System.out.println("\nFields");
for(Object t : f)
System.out.println(" ==>"+t);
System.out.println("\nMethods");
for(Object t : m)
System.out.println(" ==>"+t);
}
}
C C++ Core Java
Creating a stop watch
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class StopWatch extends JFrame implements ActionListener,Runnable
{
JButton start,pause,reset;
JLabel watch;
int counter;
Thread t;
public StopWatch()
{
start=new JButton("Start");
pause=new JButton("Pause");

reset=new JButton("Reset");
start.addActionListener(this);
pause.addActionListener(this);
reset.addActionListener(this);
pause.setEnabled(false);
reset.setEnabled(false);
watch=new JLabel();
setLayout(new FlowLayout());
add(start);
add(pause);
add(reset);
add(watch);
setSize(300,300);
setVisible(true);
t=new Thread(this);
}
public void actionPerformed(ActionEvent e)
{
String s=e.getActionCommand();
if(s.equals("Start"))
{
counter=0;
start.setEnabled(false);
pause.setEnabled(true);
reset.setEnabled(true);
t.start();
}
else if(s.equals("Pause"))
{
t.suspend();
pause.setLabel("Restart");
}
else if(s.equals("Restart"))
{
t.resume();
pause.setLabel("Pause");
}
else if(s.equals("Reset"))
{
counter=0;
}

}
public static void main(String args[])
{
new StopWatch();
}
public void run()
{
for(;;)
{
counter++;
watch.setText(Integer.toString(counter));
try
{
Thread.sleep(1000);
}catch(Exception ex){}
}
}
}