Introduction to Java

287
Introduction to Java © Copyrights aurionPro Solutions Ltd.

description

Java Tutorial

Transcript of Introduction to Java

Page 1: Introduction to Java

Introduction to Java

© Copyrights aurionPro Solutions Ltd.

Page 2: Introduction to Java

Java’s Lineage

C language was result of the need for structured, efficient, high-level language replacing assembly language

C++, that followed C, became the common (but not the first) language to offer OOP features, winning over procedural languages such as C

Java, another object oriented language offering OOP features, followed the syntax of C++ at most places, but offered many more features

© Copyright aurionPro Solutions Ltd.

Page 3: Introduction to Java

Features of Java

Completely Object-Oriented

Simple

Distributed : full support for TCP/IP protocol, developing distributed applications is easy

Robust : Strongly typed language

Secure

© Copyright aurionPro Solutions Ltd.

Page 4: Introduction to Java

Features of Java

Architecture Neutral : Platform independent

Interpreted and Compiled

Dynamic

Multithreaded : Concurrent running tasks

© Copyright aurionPro Solutions Ltd.

Page 5: Introduction to Java

Features added in Java 1.1

Java-Beans : Component Technology Serialization Remote Method InvocationJDBCJava Native InterfaceInner classes

© Copyright aurionPro Solutions Ltd.

Page 6: Introduction to Java

Features added in Java 2 (Java 1.2)

Java SwingCORBA : Common Object Request Broker

ArchitectureDigital Certificates : ensures security policiesCollection API : e.g. linked list, dynamic array

© Copyright aurionPro Solutions Ltd.

Page 7: Introduction to Java

Features added in Java 1.3

XML ProcessingJDBC 3.0 APISwing Drag and dropInternationalizationPerformance Improvement in Reflection

APIsJNDIJava Print service API

© Copyright aurionPro Solutions Ltd.

Page 8: Introduction to Java

Features added in 1.4

New Security certificates addedNew Swing FeaturesRegular expressionsNew I/O APILoggingSecure SocketsAssertions

© Copyright aurionPro Solutions Ltd.

Page 9: Introduction to Java

Features added in 1.5

Ease of Development generic types, metadata, auto boxing, an enhanced for loop, enumerated types, static import, C style formatted input/output, variable arguments, concurrency utilities, and

simpler RMI interface generation Scalability and Performance Introduction of class data sharing in the Hot Spot JVM Monitoring and Manageability The JVM Monitoring & Management API specifies a comprehensive set of

instrumentation of JVM internals to allow a running JVM to monitored. Desktop Client

Miscellaneous Features Core XML Support Supplementary Character Support JDBC RowSets

© Copyright aurionPro Solutions Ltd.

Page 10: Introduction to Java

Platform Independence

© Copyright aurionPro Solutions Ltd.

Unix on Pentium System

Class file containing Bytecodes

Macintosh PowerPC system Class Loader

Bytecode verifier

JIT compiler

PowerPC machine

level instructions

Windows Pentium PC systemClass Loader

Bytecode Verifier

JIT compiler

Pentium machine

level instructions

Java compiler

.java file

Class Loader Bytecode verifier

JIT compiler

Page 11: Introduction to Java

Platform Independence (Contd.)

Platform independence primarily helps Java Applets to be executed on any platform

Allows execution of Applet class files compiled on remote system, downloaded over the internet

Typically, however, on Java based Web-applications (i.e. J2EE applications), Java classes are compiled and executed on the same platform

© Copyright aurionPro Solutions Ltd.

Page 12: Introduction to Java

Difference between JRE and JDKJRE is the ‘Java Runtime Environment'. It

is responsible for creating a Java Virtual Machine to execute Java class files (i.e run Java programs)

JDK is the ‘Java Development Kit'. It contains tools for Development of Java code (e.g. Java Compiler) and execution of Java code (e.g. JRE)

JDK is a superset of JRE. It allows you to both write and run programs

© Copyright aurionPro Solutions Ltd.

Page 13: Introduction to Java

Relation between Java and SunSun Microsystems defined and published

Java Language SpecificationSun also offers freely downloadable

reference implementation of Java Language in the form of Sun JDK and Sun JRE

Other companies can also provide implementation of Java Specification

Few examples of companies who provide their own JRE are: IBM, Microsoft, BEA

© Copyright aurionPro Solutions Ltd.

Page 14: Introduction to Java

Technologies (JDK, J2EE,J2ME,….)

Java SE - Java SE Development Kit (JDK) Java EE -Java EE 5 SDK Java ME

Connected Device Configuration (CDC) Sun Java Wireless Toolkit for CLDC,

JavaFX JavaFX Script JavaFX Mobile

© Copyright aurionPro Solutions Ltd.

Page 15: Introduction to Java

First Simple Program

//this is my first programclass Example {

/* the execution starts here */ public static void main(String args[]) {

System.out.println(“Welcome to Java “); }

}

© Copyright aurionPro Solutions Ltd.

Page 16: Introduction to Java

Compile and Run Program

To compile the program:c:\javac Example.java

To run it:c:\java Example

© Copyright aurionPro Solutions Ltd.

Page 17: Introduction to Java

Language Fundamentals

© Copyrights aurionPro Solutions Ltd.

Page 18: Introduction to Java

Variables

Basic unit of storage in a Java programThree types of variables:

Instance variablesStatic variablesLocal variablesParameters

Each variable type has different scopeFormal parameters (i.e. arguments to

function) are similar to local variables

© Copyright aurionPro Solutions Ltd.

Page 19: Introduction to Java

Data types

© Copyright aurionPro Solutions Ltd.

Type Size/Format Description

byte 8-bit Byte-length integer

short 16-bit Short Integer

int 32-bit Integer

long 64-bit Long Integer

float 32-bit IEEE 754 Single precision floating point

double 64-bit IEE 754 Double precision floating point

char 16-bit A single character

boolean 1-bit True or False

Page 20: Introduction to Java

Default Values

Integer : 0Character : ‘\u0000’Decimal : 0.0Boolean : falseObject Reference : null

© Copyright aurionPro Solutions Ltd.

Page 21: Introduction to Java

Operators

Arithmetic operators:+, - , * , / ,%++, -- +-, -=, *= , /= , %=

Relational operators: == , != , >=,>,<=,<

assignment(=), ternary(?)

© Copyright aurionPro Solutions Ltd.

Page 22: Introduction to Java

Operators Precedence

Postfix expr++ expr—Unary ++expr --expr +expr -expr ~ !Multiplicative * / %Additive + -Shift << >> >>>Relational < > <= >= instanceofEquality == !=bitwise & ^ |logical && ||Ternary ? :Assignment = += -= *= /= %= &= ^= |= <<=

>>= >>>=

© Copyright aurionPro Solutions Ltd.

Page 23: Introduction to Java

Control Flow Statements

if-then if-then-else switch while do-while for Branching Statements

break continue return

© Copyright aurionPro Solutions Ltd.

Page 24: Introduction to Java

Memory Management

Dynamic and AutomaticNo delete operatorImplemented by Garbage Collector

Garbage Collector is the Lowest Priority Daemon Thread

It runs in the background when JVM startsCollects all the unreferenced objectsFrees the space occupied by these objectsSystem.gc() method can be called to “hint”

the JVM that it should invoke garbage collector, however, there is no guarantee that it would be invoked. It is implementation dependent

© Copyright aurionPro Solutions Ltd.

Page 25: Introduction to Java

ArraysA group of like-typed variables referred by

common nameDeclaring an array

int arr [];arr = new int[10]int arr[] = {2,3,4,5};int two_d[][] = new int[4][5];

Java arrays are asymmetrical arrays

© Copyright aurionPro Solutions Ltd.

Page 26: Introduction to Java

Arrays

Arrays of objects too can be createdExample 1 :

Box Barr[] = new Box[3]; Barr[0] = new Box(); Barr[1] = new Box(); Barr[2] = new Box();

Example 2: String[] Words = new String[2]; Words[0]=new String(“Bombay”); Words[1]=new String(“Pune”);

© Copyright aurionPro Solutions Ltd.

Page 27: Introduction to Java

OOP Concepts

© Copyrights aurionPro Solutions Ltd.

Page 28: Introduction to Java

Encapsulation

Encapsulation describes the ability of an object to hide its data and methods from the rest of the world - one of the fundamental principles of OOP (Object Oriented Programming)

Encapsulation is implemented using different access specifiers such as private, protected, public etc

© Copyright aurionPro Solutions Ltd.

Page 29: Introduction to Java

Introduction to Classes

The general form of a classclass < class_name>{

type var1;…..

Type method_name(arguments ){ body }…..

} //class ends.

© Copyright aurionPro Solutions Ltd.

Page 30: Introduction to Java

Introduction to Classes

A Simple Classclass Box{

double width;double height;double depth;double volume(){

return width*height*depth;} //method volume ends.

}//class box ends.

© Copyright aurionPro Solutions Ltd.

Page 31: Introduction to Java

Declaring Objectsclass impl{

public static void main(String a[]){

//declare a reference to object

Box b;

//allocate a memory for box object.

b = new Box();

// call a method on that object.

b.volume(); }

} © Copyright aurionPro Solutions Ltd.

Page 32: Introduction to Java

Types of class members

default access members (No access specifier)

private memberspublic membersprotected members

© Copyright aurionPro Solutions Ltd.

Page 33: Introduction to Java

Inheritance

One of the major pillars of OO approachAllows creation of hierarchical classificationAdvantage is reusability of the code

Once a class is defined & debugged , same class can be used to create further derived classes

Already written code can be extended as and when required to adopt different situations

© Copyright aurionPro Solutions Ltd.

Page 34: Introduction to Java

Inheritance (Contd.)

Inherited members can be used with the super keywordsuper() ;// calls parent class constructorsuper.overriden() ;// calls an overriden

method of the base class

© Copyright aurionPro Solutions Ltd.

Page 35: Introduction to Java

Inheritance (Contd.)

Class Base { public void meth1() {

System.out.println(“Method1 of Base”);}

}Class Derived {

public void meth1() {super.meth1();System.out.println(“Method1 of Derived”);

}

}

© Copyright aurionPro Solutions Ltd.

Page 36: Introduction to Java

Inheritance (Contd.)

class Test{

public static void main(String args[]){Derived d1=new Derived();d1.meth1();}

}

© Copyright aurionPro Solutions Ltd.

Page 37: Introduction to Java

Inheritance (Contd.)

Output: Method1 of Base Method1 of Derived

© Copyright aurionPro Solutions Ltd.

Page 38: Introduction to Java

PolymorphismAn objects ability to decide what method to

apply to itself depending on where it is in the inheritance hierarchy

Can be applied to any method that is inherited from a super class

Allows to design & implement systems that are more easily extensible

© Copyright aurionPro Solutions Ltd.

Page 39: Introduction to Java

Abstract class

A class that provides common behavior across a set of subclasses, but is not itself designed to have instances that work

One or more methods are declared but may or may not be defined

Advantages:Reusability of codeHelp at places where implementation is not

available

© Copyright aurionPro Solutions Ltd.

Page 40: Introduction to Java

Abstract class (Contd.)

Any class that has even one method as abstract should be declared abstract

Abstract classes can’t be instantiatedAbstract modifier cant be used for

constructors & static methodsAny sub class of an abstract class should

implement all methods or declare itself to be abstract

An abstract class need not have only abstract methods; can have concrete methods too

© Copyright aurionPro Solutions Ltd.

Page 41: Introduction to Java

Important Classes and Keywords in Java

© Copyrights aurionPro Solutions Ltd.

Page 42: Introduction to Java

ConstantsUse the final keyword before the variable

declaration and include an initial value for that variable

Eg:- final float pi = 3.141592; final boolean debug = false; final int maxsize = 30000;

© Copyright aurionPro Solutions Ltd.

Page 43: Introduction to Java

Final Classes and Methods

Final ClassesFinal classes cannot be inheritedAll methods in a final class are implicitly final

Final Methodsfinal methods cannot be overriddenMethods declared as static are implicitly finalAlso methods declared private are implicitly

final

© Copyright aurionPro Solutions Ltd.

Page 44: Introduction to Java

Static Members

You can declare both methods and variables to be static

Static methods has got following restrictionsThey can call only static methodsThey can access static data onlyCannot refer to this or superStatic methods can access non-static

variables and non-static methods, provided explicit instance variable is made available to the method

© Copyright aurionPro Solutions Ltd.

Page 45: Introduction to Java

Nested classes

Class within another classThe scope of a nested class is bounded by

the scope of its enclosing classNested classes are of two types:

Static Non-static

Nested classes should be used to reflect and enforce the relationship between two classes

© Copyright aurionPro Solutions Ltd.

Page 46: Introduction to Java

Anonymous Inner classes

These classes do not have a nameAre defined at the location they are

instantiated using additional syntax with the new operator

Typically used to create objects “on the fly” in contexts such as return value of a method, an argument in a method call or in initialization of variables

© Copyright aurionPro Solutions Ltd.

Page 47: Introduction to Java

Object Superclass

Cosmic super classUltimate ancestor – every class in Java

implicitly extends Object A variable of type Object can be used to refer

to objects of any typeEg. Object obj = new Emp();

Methods in Object class are :void finalize() Class getClass()String toString()

© Copyright aurionPro Solutions Ltd.

Page 48: Introduction to Java

The System Class

The System class is the class used to interact with any of the system resources

It can not be instantiatedContains a lot of methods and variables to

handle system I/OAmong the facilities provided by the System

class are standard input, standard output, and error output streams

© Copyright aurionPro Solutions Ltd.

Page 49: Introduction to Java

The System ClassSome of the methods in System class:

System.gc(): is a suggestion and not a command

It is not guaranteed to cause the garbage collector to collecteverything

System.exit(0);

© Copyright aurionPro Solutions Ltd.

Page 50: Introduction to Java

String Handling

String is handled as an object of class String and not as an array of characters

String class is a better and a convenient way to handle any operation

But one main restriction with this class is that once an object of this class is created, the contents cannot be changed

© Copyright aurionPro Solutions Ltd.

Page 51: Introduction to Java

Some methods of String class

length() : length of StringindexOf() : searches for the occurrence of a

char, or String within other Stringsubstring() : retrieves substring from the

objecttrim() : to remove spacesvalueOf() : converts data to String

© Copyright aurionPro Solutions Ltd.

Page 52: Introduction to Java

The String Class

© Copyright aurionPro Solutions Ltd.

str1

String str = new String(“Pooja”);String str1 = new String(“Sam”);

Pooja

Sam

str

str1

String str = new String(“Pooja”);String str1 = str;

Pooja str

Heap Stack

Page 53: Introduction to Java

StringBuffer Class

Peer class of String class that represents fixed length, immutable char sequence

StringBuffer represents growable and writeable character sequence

Insertions at particular positions are possible through this class

© Copyright aurionPro Solutions Ltd.

Page 54: Introduction to Java

Wrapper ClassesPrimitives are not a part of object hierarchyPrimitives are passed by valueObject representation of primitives is

requiredWrapper classes provide a way to

encapsulate simple values as objectsInteger, Double, Float, Character are all

wrapper classes

© Copyright aurionPro Solutions Ltd.

Page 55: Introduction to Java

Casting of VariablesTo convert one variable value to other,

wherein two variables correspond to two different data typesDouble d = 10.5; float f = (float) b;

Widening does not require castingCasting of References can be done, if two

classes are related to each other by inheritance relationship

If the casting is not proper, it throws ClassCastException

© Copyright aurionPro Solutions Ltd.

Page 56: Introduction to Java

UpCasting & DownCasting

UpcastingObject o = new String(“HELLO”);Serializable s = new String(“New”);

DownCastingString s1 = (String) o;String s2 = (Serializable) s

© Copyright aurionPro Solutions Ltd.

Page 57: Introduction to Java

Parameter Passing

Parameters or arguments passed to a function are passed by value for primitive data-types (e.g. int, char)

Parameters or arguments passed to a function are passed by reference for non-primitive data-types (e.g. All Java objects)

Java does not have concept of passing parameters by address or pointers, similar to what we have in C or C++ (using * to denote a pointer to object)

© Copyright aurionPro Solutions Ltd.

Page 58: Introduction to Java

Packages and Interfaces

© Copyrights aurionPro Solutions Ltd.

Page 59: Introduction to Java

Interfaces – Their need

Interface defines a data-type without implementation

The interface approach is sometimes known as programming by contract

It’s essentially a collection of constants & abstract methods

An interface is used via the keyword "implements" Thus a class can be declared as class MyClass implements Sun, Fun{ ... }

© Copyright aurionPro Solutions Ltd.

Page 60: Introduction to Java

Interfaces

A Java interface definition looks like a class definition that has only abstract methods, although the abstract keyword need not appear in the definition

public interface Testable { void method1(); void method2(int i, String s);

}

© Copyright aurionPro Solutions Ltd.

Page 61: Introduction to Java

Declaring and Using Interfaces

public interface simple_cal { int add(int a, int b); int i=10;}//Interfaces are to be implemented.class calci implements simple_cal {

int add(int a, int b){return a+b;

}}

© Copyright aurionPro Solutions Ltd.

Page 62: Introduction to Java

Interfaces - rules

Methods in an interface are always public & abstract

Data members in a interface are always public, static & final

A sub class can only have a single super class in Java

But a class can implement any number of interfaces

Thus flexibility is introduced in usage of polymorphism

© Copyright aurionPro Solutions Ltd.

Page 63: Introduction to Java

Interfaces & Abstract classes

Abstract classes are used only when there is a “is-a” type of relationship between the classes

You cannot extend more than one abstract class

Abstract class can contain abstract as well as implemented methods

© Copyright aurionPro Solutions Ltd.

Page 64: Introduction to Java

PackagesAre a named collection of classesAre a way of grouping related classes &

interfacesA package can contain any number of classes

that are related in purpose, in scope or by inheritance

Convenient for organizing your work & separating your work from code libraries provided by others

© Copyright aurionPro Solutions Ltd.

Page 65: Introduction to Java

Packages : Their need

Allow to organize classes into unitsReduce problems with naming conflictsAllow to protect classes, variables &

methods in a larger way than on a class-to-class basis

© Copyright aurionPro Solutions Ltd.

Page 66: Introduction to Java

Using packagesTo use a public class of a package, simple use

the full package nameE.g. Java.util.Date = new java.util.Date();import statement: allows to import all the

public classes in a packageE.g. import java.awt.*;If the required class is in java.lang package,

it can be used directly

© Copyright aurionPro Solutions Ltd.

Page 67: Introduction to Java

Defining A Packagepackage com.patni.trg.demo;// import statements here.public class Balance {

String name;double bal;public Balance(String n, double b) {

name = n; bal = b;}

© Copyright aurionPro Solutions Ltd.

Page 68: Introduction to Java

Defining A Package

  public void show() {

if(bal<0) System.out.print("-->> ");System.out.println(name

+ ": $" + bal);}

}

© Copyright aurionPro Solutions Ltd.

Page 69: Introduction to Java

Compiling A Package

Specify the path of the directory, where com directory is to be created

Examplejavac –d . Balance.javajavac –d E:\JavaAss\MyAss Balance.java

© Copyright aurionPro Solutions Ltd.

Page 70: Introduction to Java

Package scope access

Default: features of a class having default scope can be accessed by all classes in the same package

Protected: enables a feature to be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared

© Copyright aurionPro Solutions Ltd.

Page 71: Introduction to Java

Access Specifiers

© Copyright aurionPro Solutions Ltd.

Private No Modifier Protected Public

Same class Y Y Y Y

Same Package Subclass N Y Y Y

Same Package non-sub class N Y Y Y

Different Package Subclass N N Y Y

Diffrent Package non-subclass N N N Y

Page 72: Introduction to Java

Access Specifiers

© Copyright aurionPro Solutions Ltd.

Package P2

Package P1

Class A

Class CClass B Class FClass G

Page 73: Introduction to Java

ClasspathFor java to be able to use a class, it has to

be able to find that class on the file systemOtherwise, the runtime flags an exception

that the class does not exist

Java uses 2 elements to find classes The package nameThe directories listed in classpath variable

© Copyright aurionPro Solutions Ltd.

Page 74: Introduction to Java

Classpath(Contd.)classpath : points to various places where

java classes liveThe specific location that Java compiler

considers as root of an package hierarchy is controlled by classpathe.g.classpath = c:\jdk1.2.2\bin; c:\jdk1.4.2_03; d:\java;

© Copyright aurionPro Solutions Ltd.

Page 75: Introduction to Java

How compiler locates a fileCompiler searches through all directories

specified in the classpath variableIf . is specified in classpath, then it also

checks current directoryIf compiler still does not locate the file, it

flags a ClassNotFound Exception

© Copyright aurionPro Solutions Ltd.

Page 76: Introduction to Java

Eclipse, an IDE

© Copyrights aurionPro Solutions Ltd.

Page 77: Introduction to Java

What is an IDE?

An application or set of tools that allows a programmer to write, compile, edit, and in some cases test and debug within an integrated, interactive environment

IDE combines the editor, compiler, runtime environment and debugger – all in the single integrated application.

(e.g. When one attempts to compile code with syntax errors, IDE shows the error messages, and lets one jump to that line by clicking on error message)

© Copyright aurionPro Solutions Ltd.

Page 78: Introduction to Java

Some examples of an IDE

EclipseJDeveloperWSAD (WebSphere Studio Application

Developer)JBuilder

© Copyright aurionPro Solutions Ltd.

Page 79: Introduction to Java

Using Eclipse as an IDE

The Eclipse Project is an open source software development project dedicated to providing a robust, full-featured, commercial-quality, industry platform for the development of highly integrated tools and rich client applications

 

© Copyright aurionPro Solutions Ltd.

Page 80: Introduction to Java

Using Eclipse as an IDE

Our objective is to code Java programs faster with Eclipse 3.0 as an IDE

Eclipse3.0 features include: Creation and maintenance of the Java project Developing Packages Debugging a java program with variety of

tools available Running a Java program

© Copyright aurionPro Solutions Ltd.

Page 81: Introduction to Java

Using Eclipse as an IDE

Developing the Java program will be easier as Eclipse editor will provide:

   Syntax highlighting    Content/code assist    Code formatting    Import assistance    Quick fix

© Copyright aurionPro Solutions Ltd.

Page 82: Introduction to Java

Eclipse-Plugins

LombozCheckstyleJDependPMDAnt

© Copyright aurionPro Solutions Ltd.

Page 83: Introduction to Java

Exception Handling

© Copyrights aurionPro Solutions Ltd.

Page 84: Introduction to Java

Exception Handling

Exception is an object that describes an exceptional condition

Java Exception handling is managed by 5 keywordstry, catchfinallythrowthrows

© Copyright aurionPro Solutions Ltd.

Page 85: Introduction to Java

Exception Handling

© Copyright aurionPro Solutions Ltd.

RunTime Exception

Compile Time Exception

Exception Error

Throwable

Unchecked ExceptionChecked Exception

Page 86: Introduction to Java

Some Examples

Checked Exceptions include:IOExceptionSQLExceptionClassNotFoundException

Unchecked Exceptions include:ArithmaticExceptionNullPointerExceptionArrayIndexOutOfBoundsException

© Copyright aurionPro Solutions Ltd.

Page 87: Introduction to Java

Using try and catchclass demo { public static void main(String a[]) {

try { int d = 0; int a = 42 /d; } catch(ArithmeticException ae) { System.out.println(ae);

}}}

© Copyright aurionPro Solutions Ltd.

Page 88: Introduction to Java

Throw and Throws clause

It is a way to throw an exception explicitlyMust be an object of Throwable or it’s

subclasses

Example:public void passgrade(int a, int total) {

if (a > total) throw new ArithmeticException();}

© Copyright aurionPro Solutions Ltd.

Page 89: Introduction to Java

Throws clauseIf method is capable of throwing an exception, then

caller needs to be informed, so that they can guard

themselves against the exception public void passgrade(int a, int total) throws

ArithmeticException {

if (a > total)

throw new ArithmeticException();

}

Throws clause is not commonly used for Exceptions

of type Error, RuntimeException, or its subclasses

© Copyright aurionPro Solutions Ltd.

Page 90: Introduction to Java

Finally clauseFinally clause creates a block of code that will be executed

whether or not an exception is thrown

Usage:

try {

int j = 0;

int i = d/j;

} catch (ArithmeticException ae) {

System.out.println(ae);

} finally {

System.out.println(“Always Executed”);

}

© Copyright aurionPro Solutions Ltd.

Page 91: Introduction to Java

Application Specific Exceptionsclass ApplicationException extends Exception { private int detail; ApplicationException(int a) { detail = a;}

ApplicationException(String args) {super(args); }

public String toString(){ return "ApplicationException["+detail+"]";}

}

© Copyright aurionPro Solutions Ltd.

Page 92: Introduction to Java

Documenting in Java - javadoc

© Copyrights aurionPro Solutions Ltd.

Page 93: Introduction to Java

What is javadoc?

Javadoc is a tool that parses the declarations and documentation comments in a set of source files and produces a set of HTML pages describing the classes, inner classes, interfaces, constructors, methods, and fields

To generate javadocs for the class some commenting styles must be followed in the program

© Copyright aurionPro Solutions Ltd.

Page 94: Introduction to Java

Javadoc Comments

A general javadoc comment /** * This is the typical format of a simple

documentation *comment that spans two lines

*/ Documentation comments are recognized

only when enclosed between /** and */ and placed immediately before class, interface, constructor, method, or field declarations

© Copyright aurionPro Solutions Ltd.

Page 95: Introduction to Java

Javadoc Comments (Contd.)

Class and interface Documentation tags@see,@deprecated,@author,@version and

moreExample:

/** * A class representing a window on the screen. * For example: * @author patni * @see java.awt.BaseWindow */ class Window extends BaseWindow { ... }

© Copyright aurionPro Solutions Ltd.

Page 96: Introduction to Java

Javadoc Comments (Contd.)

Field Documentation tags:@see,@deprecated,@since,@serial and

moreExample:

/** * The X-coordinate of the component. * * @see #getLocation() */ int x = 1263732;

© Copyright aurionPro Solutions Ltd.

Page 97: Introduction to Java

Javadoc Comments (Contd.)

Constructor and Method Documentation Tags@see,@param,@return,@since,@throws,@exce

ption and more /** * Returns the character at the specified index. An

index * @param index the index of the desired character

© Copyright aurionPro Solutions Ltd.

Page 98: Introduction to Java

Javadoc Comments (Contd.)

* @return the desired character. * @exception StringIndexOutOfRangeException * if the index is not in the range

<code>0</code> * to <code>length()-1</code>. * @see java.lang.Character#charValue() */ public char charAt(int index) { ... }

© Copyright aurionPro Solutions Ltd.

Page 99: Introduction to Java

© Copyrights aurionPro Solutions Ltd.

Page 100: Introduction to Java

Coding ConventionsEvery project in aurionPro MUST follow

consistent Java Coding Conventions, unless overridden by client for that project

Coding conventions (also known as “Coding Guidelines”) are set of suggestive guidelines defined for a project, that helps to enforce consistent coding style across developers within the project

For example, it ensures consistent and readable names of variables, classes or methods across application

© Copyright aurionPro Solutions Ltd.

Page 101: Introduction to Java

Coding Conventions (Contd.)Examples of Coding Conventions Guidelines

Class level member variable should be m_x<varname> where m indicates member variable,

x should be replaced with i for integer, s for String etc.

e.g. m_sUserName // String that stores User Name

Function Arguments variables (formal parameters) should be a_x<varname> where

a indicates argument variable, x should be replaced with i for integer, s for String etc.

e.g. a_iProjectCode // integer argument to hold proj-code

First letter of every class should always be in upper case.Variable names such as “String string1 = new String()”

should be avoided. Instead, sensible variable name should used

© Copyright aurionPro Solutions Ltd.

Page 102: Introduction to Java

Coding Conventions (Contd.)How do Coding Conventions help the project?

Helps to define the consistent ways of naming a variable or a class or a method within application

Improves readability of the codeHelps during defect fixing and maintenance phase,

since variable names are indicative of its scope, type etc

Makes debugging of code person-independentSaves efforts on documentation, since

variable/method or class names becomes self-describing

© Copyright aurionPro Solutions Ltd.

Page 103: Introduction to Java

Coding Conventions (Contd.)

How to use Coding Conventions on the project?Typically defined by client or senior team member or PL

before the start of the coding phaseIf not defined for a project, refer to conventions defined

by Sun (http://java.sun.com/docs/codeconv/index.html) Should be read and understood by every developer

before starting the code (to avoid rework later on)Should be adopted as part of the coding-culture itself,

and not as add-on activity applied after functional coding is done

Should come naturally to every developerShould get caught during code-reviews, if not followed

© Copyright aurionPro Solutions Ltd.

Page 104: Introduction to Java

Coding Conventions (Contd.)Coding Conventions can be found on our QMS -> 4.4 Tables -> GL 1 - Guidelines for Coding Conventions defined by Sun

http://java.sun.com/docs/codeconv/index.html that can be used for rest of the assignments

within this course

© Copyright aurionPro Solutions Ltd.

Page 105: Introduction to Java

© Copyrights aurionPro Solutions Ltd.

Page 106: Introduction to Java

ReviewsBeing ISO-9001:2000 company, reviews

are part of the life in aurionProReviews do take place for every work

product created in SDLC of a project (e.g. Design review, test case review, code review etc.)

Various types of reviews in PatniSelf-ReviewPeer-to-peer reviewPeer review

© Copyright aurionPro Solutions Ltd.

Page 107: Introduction to Java

Peer to Peer Code Reviews

Code is reviewed by Peer (colleague)Why Peer to Peer Reviews are required?

Everyone has a blind spot. Can’t catch one’s own mistake

Helps to catch the defect early in the life-cycleDefects found in reviews may be difficult or impossible

to find in testing (e.g. coding convention defects)It takes more efforts to find the same defect during

testing (Cost of finding defect in testing is higher than cost of finding defect in reviews)

Enforces consistency amongst developers and clarifies misunderstood points during review discussions

© Copyright aurionPro Solutions Ltd.

Page 108: Introduction to Java

Java Code Review Checklist

Code reviews should be done using a checklist, and should cover functional reviews too

Typically code-review checklists are created senior team member (GL) or PL or sometimes provided by client too

If not defined for a project, refer to checklists available on Patni KC

Should be read and understood by every developer before starting the code creation and code reviews

Checklist must be used by code-creator for self-review. This will reduce the efforts during peer-to-peer review

Should be adopted as part of the coding-culture itself

© Copyright aurionPro Solutions Ltd.

Page 109: Introduction to Java

Java Code Review Checklist (Contd.)

Typically Java Code Review checklist looks like this Sample Java Code review checklist

One of the important points that code-review checklist ensures is enforcing coding conventions (or coding guidelines) discussed in earlier slides

Review Findings of code-review should be captured as code-review defects. Defects should be fixed by code-creator, and re-verified by the person reporting the defect

© Copyright aurionPro Solutions Ltd.

Page 110: Introduction to Java

Java Property files

© Copyrights aurionPro Solutions Ltd.

Page 111: Introduction to Java

Java Property files

java.util.Properties is a platform-independent generalization of the DOS SET environment, or the Windows *.INI files. In Java, even each object could have its own list of properties. A program can determine if an entry is missing in the property file and provide a default to using it its place

© Copyright aurionPro Solutions Ltd.

Page 112: Introduction to Java

Java Properties

Java.util.Properties class:The Properties class represents a persistent

set of properties. The Properties can be saved to path from where the properties file would be picked up. Each key and its corresponding value in the property list is a string

© Copyright aurionPro Solutions Ltd.

Page 113: Introduction to Java

Types of properties

Property files provide a means of storing key-value pair,which could be used by the programs in execution

Properties can be categorized as:

User specific propertiesSystem properties

© Copyright aurionPro Solutions Ltd.

Page 114: Introduction to Java

Types of properties

 User specific properties: These properties are part of the

Application.properties containing a key value pair, which can be mentioned by the program in run

#application.properties file contents password=tiger url=jdbc:oracle:thin:@192.168.12.16:1521:oracle8idriver=oracle.jdbc.driver.OracleDriverusername=scott

© Copyright aurionPro Solutions Ltd.

Page 115: Introduction to Java

Types of properties

System properties: System properties give information about the

environment of the program ,in which it is running such as JVM it is running in, Operating System name and version, java home and many more properties

© Copyright aurionPro Solutions Ltd.

Page 116: Introduction to Java

System Properties

System properties are read from System class, which give information about the environment of the Java program in which it is running, such as:Java.vmJava.versionUser.languageJava.homeUser.region etc

© Copyright aurionPro Solutions Ltd.

Page 117: Introduction to Java

Files and Streams

© Copyrights aurionPro Solutions Ltd.

Page 118: Introduction to Java

StreamsFiles are necessary for persisting dataJava views each file as a sequential stream of

bytesStream is generic term for ‘flow of data’Different streams are used to represent

different kinds of data flowWhen a file is opened, an object is created

and a stream is associated with the object

© Copyright aurionPro Solutions Ltd.

Page 119: Introduction to Java

Streams(Contd.)Thus, an object from which we can read a

sequence of bytes is input streamThus, an object to which we can write a

sequence of bytes is output streamThe source or destination of data can be

files, network connections or even blocks of memory

The Java I/O class libraries allows user to handle any data in the same way

© Copyright aurionPro Solutions Ltd.

Page 120: Introduction to Java

Java.io packageProvides an extensive set of classes for

handling I/O to & from various devicesContains many classes each with a variety

of member variables & methodsIt is layered ie. It does not attempt to put

too much capability into 1 classInstead a programmer can get the features

he wants by layering one class over another

© Copyright aurionPro Solutions Ltd.

Page 121: Introduction to Java

I/O Handling

All Java programs automatically import java.lang package

This package defines a class called System, which encapsulates several aspects of run-time environment

It contains three predefined stream variables called in,out, and err (public static)

© Copyright aurionPro Solutions Ltd.

Page 122: Introduction to Java

Input streams

© Copyright aurionPro Solutions Ltd.

Page 123: Introduction to Java

Output streams

© Copyright aurionPro Solutions Ltd.

Page 124: Introduction to Java

InputStream classAn abstract class that defines methods for

performing I/pServes as base class for all other

InputStream classesDefines a basic interface for reading

streamed bytes of informationData in InputStream is transmitted one byte

at a time

© Copyright aurionPro Solutions Ltd.

Page 125: Introduction to Java

InputStream class : some methodsint read() : Returns an integer

representation of the next available byte of input

int read(byte buffer[]):int read(byte buffer[], int offset, int

numbytes) int available()void close() void mark(int numbytes)

© Copyright aurionPro Solutions Ltd.

Page 126: Introduction to Java

Using the Stream variables import java.io.*;

class ReadKeys {

public static void main (String args[]) {

StringBuffer sb = new StringBuffer();

char c;

try {

while((ch =(char)System.in.read()) != '\n')) { sb.append(c);

}

} catch (Exception e) { ... }

String s = new String(sb);

System.out.println(s); } }

© Copyright aurionPro Solutions Ltd.

Page 127: Introduction to Java

OutputStream

void write (int b): Writes a single byte to an output stream

void write(byte buffer[])void write(byte buffer[], int offset, int

noBytes)void flush()void close()

© Copyright aurionPro Solutions Ltd.

Page 128: Introduction to Java

FileInputStream

The FileInputStream class creates an InputStream that you can use to read the contents of a file. It has two constructors:FileInputStream(String filepath) throws

FileNotFoundExceptionFileInputStream(File fileobj) throws

FileNotFoundException

© Copyright aurionPro Solutions Ltd.

Page 129: Introduction to Java

FileOutputStream

The FileOutputStream class creates an OutputStream that you can use to read the contents of a file. It has two constructors:

FileOutputStream(String filepath)FileOutputStream(File fileobj)

© Copyright aurionPro Solutions Ltd.

Page 130: Introduction to Java

ByteArrayInputStreamByteArrayInputStream is an implementation of

an input stream that uses a byte array as the source. This class has two constructors , each of which requires a byte array to provide the data source

ByteArrayInputStream(byte array[])

ByteArrayInputStream(byte array[],int start,int

numbytes)

© Copyright aurionPro Solutions Ltd.

Page 131: Introduction to Java

Chaining of streams

Each class accesses the output of the previous class through the in variable

ExampleFileOutputStream fos = new

FileOutputStream(c:\a.txt”);DataOutputStream dos = new

DataOutputStream(fos);

© Copyright aurionPro Solutions Ltd.

Page 132: Introduction to Java

Character Streams: Readers/Writers

Reader and Writer classes are designed for character streams

Reader is an input character stream that reads a sequence of Unicode characters

Writer is an output character stream that writes a sequence of Unicode characters

© Copyright aurionPro Solutions Ltd.

Page 133: Introduction to Java

Reader hierarchy

© Copyright aurionPro Solutions Ltd.

Page 134: Introduction to Java

Writer hierarchy

© Copyright aurionPro Solutions Ltd.

Page 135: Introduction to Java

File classFile class doesn’t operate on streamsRepresents the pathname of a file or

directory in the host file systemUsed to obtain or manipulate the information

associated with a disk file, such as permissions, time, date, directory path etc

An object of File class provides a handle to a file or directory and can be used to create, rename or delete the entry

© Copyright aurionPro Solutions Ltd.

Page 136: Introduction to Java

File classSome methods

canRead()exists()isFile()isDirectory()getAbsolutePath()getName()

© Copyright aurionPro Solutions Ltd.

Page 137: Introduction to Java

File class methods (Contd.)

getPath()getParent()Length() : returns length of file in bytes as

longlastModified()Mkdir()List() : obtain listings of directory contents

© Copyright aurionPro Solutions Ltd.

Page 138: Introduction to Java

Serialization

Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable

© Copyright aurionPro Solutions Ltd.

Page 139: Introduction to Java

Object Serialization Allows an object to be transformed into a

sequence of bytes that can be later re-created into an original object

After deserialization, the object has the same state as it had when it was serialized(barring any data members that are not serialized)

For a object to be serialized, the class must implement the Serializable interface

© Copyright aurionPro Solutions Ltd.

Page 140: Introduction to Java

RandomAccessFileRandomAccessFile encapsulates a random-

access fileRandomAccessFile(String FileObj, String

access);RandomAccessFile(String filename, String

access)

access can be r or rwvoid seek( long newPos);

© Copyright aurionPro Solutions Ltd.

Page 141: Introduction to Java

Multithreading in Java

© Copyrights aurionPro Solutions Ltd.

Page 142: Introduction to Java

Multithreading

A multithreaded program contains two or more parts that can run concurrently. Each part of that program is called thread, and each thread defines a separate path of execution

There are two distinct types of multitasking: process based & thread based

Thread is also known as lightweight process

© Copyright aurionPro Solutions Ltd.

Page 143: Introduction to Java

MultithreadingThe Main thread

When a Java program starts up, there is already one thread running

It is the thread from which other “child” threads will be spawned

It must be the last thread to finish execution. When the main thread stops, your program terminates

If the main thread finishes before a child thread has completed, then the Java run-time system may hang

© Copyright aurionPro Solutions Ltd.

Page 144: Introduction to Java

Main ThreadAlthough the main thread is called automatically when

program starts, it can be controlled by a thread object

How? Obtain a reference to it by calling the method currentThread() (a public static member of Thread class)

static Thread currentThread(){ }

This returns a reference to the thread in which it is called. Once a reference to the main thread is obtained, it can be controlled just like any other thread

© Copyright aurionPro Solutions Ltd.

Page 145: Introduction to Java

MultithreadingCreating new Threads

java.lang.ThreadCreating a thread involves two steps: writing

the code that is executed in the thread and writing the code that starts the thread

There are two ways to create a threadImplementing Runnable interfaceExtending Thread class

© Copyright aurionPro Solutions Ltd.

Page 146: Introduction to Java

Runnable interface

Need to implement run() public abstract void run()

Instantiate an object of type Thread within that class Thread defines several constructorsThread ( Runnable threadOb, String

threadName );The new thread will not start running until its

start() method isn’t invokedIn turn, start() executes a call to run().

synchronized void start ( )

© Copyright aurionPro Solutions Ltd.

Page 147: Introduction to Java

Extending Thread class

The extending class must override the run() method, which is the entry point for the new thread

It must also call start() to begin execution of the new thread

© Copyright aurionPro Solutions Ltd.

Page 148: Introduction to Java

LifeCycle of Thread

© Copyright aurionPro Solutions Ltd.

Ready to run

Dead

Running

scheduling

Terminates

Start

Sleeping BlockedWaitingNon-runnable stateEntering

non-runnable

Leaving non-runnable

Page 149: Introduction to Java

States of Java Thread Not Runnable

Still alive, but it is not eligible for execution It can move to not runnable stage because of following

reasons: 1. The thread is waiting for an I/O operation to complete2. The thread has been put to sleep for a certain period of

time (using the sleep() method)3. The wait() method has been called4. The thread has been suspended (using suspend()

method)

© Copyright aurionPro Solutions Ltd.

Page 150: Introduction to Java

States of Java Thread

DeadWhen a thread terminates, it is DEAD. Threads can be DEAD in a variety of ways which include

1. When its run() method returns2. When stop() or destroy() method is called

© Copyright aurionPro Solutions Ltd.

Page 151: Introduction to Java

Methods invoked on Threadsinterrupt() : interrupts a thread

interrupted() : true if current thread has been interrupted and false otherwise

isInterrupted() : determines if a particular thread is interrupted

stop() : stops a thread by throwing a ThreadDeath object which is a subclass of error

© Copyright aurionPro Solutions Ltd.

Page 152: Introduction to Java

The Thread Class MethodsgetPriority(): Obtains thread priority

start(): To start the operation of a thread

sleep(): suspends the thread for some time

run(): body of the thread

suspend()/resume(): suspends a thread & resumes

© Copyright aurionPro Solutions Ltd.

Page 153: Introduction to Java

Methods invoked on ThreadsgetName(): returns the name of the threadtoString(): returns a string consisting of the

name of the thread, priority of the thread and the thread’s group

currentThread(): returns a reference to the current Thread

join(): waits for the thread to which the message is sent to die before the current thread can proceed

© Copyright aurionPro Solutions Ltd.

Page 154: Introduction to Java

Methods invoked on Threads

isAlive(): returns true if start has been called but stop has not

setName(): sets the name of the threadYield(): Causes the currently executing

thread object to temporarily pause and allow other threads to execute

© Copyright aurionPro Solutions Ltd.

Page 155: Introduction to Java

Pre-emptive VS Nonpre-emptive

Pre-emptive : The OS interrupts programs without consulting them

Non pre-emptive: The programs are interrupted only when they are ready to yield control

© Copyright aurionPro Solutions Ltd.

Page 156: Introduction to Java

Scheduling & PriorityThread-scheduling: A mechanism used to

determine how runnable threads are allocated CPU time

A Thread-scheduling mechanism is either preemptive or non preemptive

Scheduling can be controlled through priorities setPriority() getPriority()Three types of priorities can be set viz

MIN_PRIORITY, NORM_PRIORITY, MAX_PRIORITY

© Copyright aurionPro Solutions Ltd.

Page 157: Introduction to Java

Scheduling & Priority

The job of Java scheduler is to keep a highest priority thread running at all times

If timeslicing is available, it ensures that several equally high - priority threads execute for a quantum in a round - robin fashion

© Copyright aurionPro Solutions Ltd.

Page 158: Introduction to Java

Multithreading – JVM implementation dependentThe early Solaris Java platform runs a thread

of a given priority to completion or until a higher priority thread becomes ready

At that point preemption occurs, I.e the processor is given to the higher - priority thread while the previously running thread must wait

© Copyright aurionPro Solutions Ltd.

Page 159: Introduction to Java

Multithreading policiesIn 32-bit Java implementations for Win ‘95 &

Win NT, threads are time slicedEach thread is given a limited amount of

time to execute on a processorWhen that time expires the thread is made

to wait while other threads of equal priority get their chance to use their quantum in round - robin fashion

© Copyright aurionPro Solutions Ltd.

Page 160: Introduction to Java

Multithreading policies

Thus, on Win ‘95 and Win NT, a running thread can be pre - empted by a thread of equal priority

Whereas on the early solaris implementation, a running thread can only be pre-empted by a higher priority thread

© Copyright aurionPro Solutions Ltd.

Page 161: Introduction to Java

Thread SynchronizationImplemented using synchronized keywordsA method can be synchronized so that only

one thread at a time can access the methodThis is possible using a technique called as

object monitorEven an object can be synchronized

© Copyright aurionPro Solutions Ltd.

Page 162: Introduction to Java

Inter thread Communication final void wait(): tells the calling thread to give

up the monitor and go to sleep until some other thread enters the same monitor and calls notify()

final void notify(): wakes up the first thread that called wait() on the same object

final void notifyall(): wakes up all the threads that called wait() on the same object. The highest priority thread will run first

© Copyright aurionPro Solutions Ltd.

Page 163: Introduction to Java

Networking

© Copyrights aurionPro Solutions Ltd.

Page 164: Introduction to Java

Networking Basics

Computers running on the Internet communicate to each other using either the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP).

When you write Java programs that communicate over the network, you are programming at the application layer.

You can use the classes in the java.net package.

© Copyright aurionPro Solutions Ltd.

Page 165: Introduction to Java

TCP

When two applications want to communicate to each other reliably, they establish a connection and send data back and forth over that connection.

TCP guarantees that data sent from one end of the connection actually gets to the other end and in the same order it was sent. Otherwise, an error is reported.

The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of applications that require a reliable communication channel.

© Copyright aurionPro Solutions Ltd.

Page 166: Introduction to Java

UDP

UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-based like TCP.

e.g. An application which sends current time.

© Copyright aurionPro Solutions Ltd.

Page 167: Introduction to Java

Understanding Ports

A computer has a single physical connection to the network. All data destined for a particular computer arrives through that connection. However, the data may be intended for different applications running on the computer. So how does the computer know to which application to forward the data? Through the use of ports.

The computer is identified by its 32-bit IP address, which IP uses to deliver data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the right application.

Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such as HTTP and FTP and other system services.

© Copyright aurionPro Solutions Ltd.

Page 168: Introduction to Java

java.netThe URL, URLConnection, Socket, and

ServerSocket classes all use TCP to communicate over the network. The DatagramPacket, DatagramSocket, and MulticastSocket classes are for use with UDP.

© Copyright aurionPro Solutions Ltd.

Page 169: Introduction to Java

SocketA socket is one endpoint of a two-way

communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.

© Copyright aurionPro Solutions Ltd.

Page 170: Introduction to Java

Abstract Window Toolkit

© Copyrights aurionPro Solutions Ltd.

Page 171: Introduction to Java

Introduction to AWTAWT: Abstract Windows Toolkit packageNumber of classes and interfaces to create

and manage windowsA standard way to provide graphical user

interface(GUI) in JavaAWT supports even the GUI based

applications

© Copyright aurionPro Solutions Ltd.

Page 172: Introduction to Java

Window Fundamentals

The awt defines the various kinds of windows according to class hierarchy that adds functionality and specificity at each level

At the highest level of hierarchy is Component classAn abstract class encapsulating all attributes of

a visual componentAll methods regarding the painting displaying

the component, positioning, resizing, event handling are defined in this class

© Copyright aurionPro Solutions Ltd.

Page 173: Introduction to Java

Windows class hierarchy

© Copyright aurionPro Solutions Ltd.

Java.lang.object

Components(abstract)

Container(abstract)

Panel Window

Java.applet.Applet Dialog Frame

GUI control components areconcrete subclasses of this class.

Page 174: Introduction to Java

GUI Control Components

ButtonCanvasCheckboxChoiceLabelListScrollbarTextFieldTextArea

© Copyright aurionPro Solutions Ltd.

Page 175: Introduction to Java

Menu Components

© Copyright aurionPro Solutions Ltd.

Java.lang.object

Menu Component(abstract)

Menubar MenuItem

Menu CheckboxMenuItem

PopupMenu

Page 176: Introduction to Java

© Copyrights aurionPro Solutions Ltd.

Page 177: Introduction to Java

Layouts

FlowLayoutGridLayoutBorderLayoutCardLayoutBoxLayout

© Copyright aurionPro Solutions Ltd.

Page 178: Introduction to Java

BoxLayout

BoxLayout either stacks its components on top of each other (with the first component at the top) or places them in a tight row from left to right

Demo : ListDialog.javaUsing Fillers : Glue, RigidArea

© Copyright aurionPro Solutions Ltd.

Page 179: Introduction to Java

GridBagLayout

A GridBagLayout places components in a grid of rows and columns, allowing specified components to span multiple rows or columns

ConstraintsGridx,gridy: Specify the row and column at the

upper left of the componentgridwidth, gridheight: Specify the number of

columns (for gridwidth) or rows (for gridheight) in the component's display area

© Copyright aurionPro Solutions Ltd.

Page 180: Introduction to Java

GridBagLayoutFill: Used when the component's display area is larger than the component's requested size to determine whether and how to resize the component

© Copyright aurionPro Solutions Ltd.

Page 181: Introduction to Java

GridBagLayoutConstraints

ipadx, ipady : Specifies the internal padding: how much to add to the minimum size of the component

insets : specifies the external padding of the component -- the minimum amount of space between the component and the edges of its display area

anchor : used when the component is smaller than its display area to determine where (within the area) to place the component

weightx, weighty : Weights are used to determine how to distribute space among columns (weightx) and among rows (weighty)© Copyright aurionPro Solutions Ltd.

Page 182: Introduction to Java

Rendering graphicsGraphicsFontFontMetricsColorGraphicsEnvironment

GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();

String envfonts[] = gEnv.getAvailableFontFamilyNames();

© Copyright aurionPro Solutions Ltd.

Page 183: Introduction to Java

Rendering graphics

ToolkitImageDouble-buffering

© Copyright aurionPro Solutions Ltd.

Page 184: Introduction to Java

© Copyrights aurionPro Solutions Ltd.

Page 185: Introduction to Java

Java’s Event Handling Mechanisms

Ignore the eventHave the event handled by the component

from where the event originatedDelegate the event handling to some other

object or objects, called listeners

© Copyright aurionPro Solutions Ltd.

Page 186: Introduction to Java

Event Delegation

Event classes that can encapsulate information about different types of user interaction

Event source objects that inform event listeners about events when these occur and supply the necessary information about these events

Event listener objects that are informed by an event source when designated events occur, so that they can take appropriate action

© Copyright aurionPro Solutions Ltd.

Page 187: Introduction to Java

© Copyright aurionPro Solutions Ltd.

EventObject

AWT Event

ComponentEvent

ActionEvent

AdjustmentEvent

ItemEvent

TextEvent

InputEvent

ContainerEvent

FocusEvent

PaintEvent

WindowEvent

MouseEvent

KeyEvent

Inheritance diagram of the event classes

Page 188: Introduction to Java

Event sources,classes & interfaces

© Copyright aurionPro Solutions Ltd.

Event Type Event Source Listener registration and removal methods

provided by the source

Event listener interface

implemented by a listener

ActionEvent Button List MenuItem TextField

addActionListener removeActionListener

ActionListener

AdjustmentEvent

Scrollbar addAdjustmentListener removeAdjustmentListener

AdjustmentListener

ItemEvent Choice Checkbox CheckboxMenuItm List

addItemListener removeItemListener

ItemListener

TextEvent TextArea TextField

addTextListener removeTextListener

TextListener

Key Event Component addKeyListener removeKeyListener

KeyListener

Page 189: Introduction to Java

Event sources,classes & interfaces

© Copyright aurionPro Solutions Ltd.

MouseEvent Component addMouseListener removeMouseListener addMouseMotionLister removeMouseMotionListener

MouseListener MouseMotionListener

WindowEvent Window addWindowListener removeWindowListener

WindowListener

FocusEvent Component addFocusListener removeFocusListener

FocusListener

ComponentEvent

Component addComponentListener removeComponentListener

ComponentListener

ContainerEvent

Component AddContainerListener removeContainerListener

ContainerListener

Page 190: Introduction to Java

Event listeners and methods

© Copyright aurionPro Solutions Ltd.

Event Listener Interface

Event Listener Methods

ActionListener actionPerformed( ActionEvent evt) AdjustmentListener adjustmentValueChanged(AdjustmentEvent

evt) ItemListener itemStateChanged(ItemEvent evt) TextListener textValueChanged(TextEvent evt) WindowListener windowActivated(WindowEvent evt)

windowClosed(WindowEvent evt) windowIconified(WindowEvent evt) windowDeiconified(WindowEvent evt) windowDeactivated(WindowEvent evt) windowOpened(WindowEvent evt) windowClosing(WindowEvent evt)

MouseMotionListener mouseMoved(MouseEvent evt) mouseDragged(MouseEvent evt)

Page 191: Introduction to Java

Event listeners and methods

© Copyright aurionPro Solutions Ltd.

MouseListener mouseClicked(MouseEvent evt) mousePressed(MouseEvent evt) mouseReleased(MouseEvent evt) mouseEntered(MouseEvent evt) mouseExited(MouseEvent evt)

KeyListener keyPressed(Keyevent evt) keyReleased(Keyevent evt) keyTyped(Keyevent evt)

FocusListener focusGained(focusEvent evt) focusLost(focusEvent evt)

ContainerListener componentAdded( ComponentEvent evt) componentRemoved( ComponentEvent evt)

ComponentListener

componentHidden( ComponentEvent evt) componentMoved( ComponentEvent evt) componentResized( ComponentEvent evt) componentShown( ComponentEvent evt)

Page 192: Introduction to Java

© Copyright aurionPro Solutions Ltd.

Low level event listener interface

Low level event listener adapter

ComponentListener ComponentAdapter ContainerListener ContainerAdapter FocusListener FocusAdapter KeyListener KeyAdapter MouseListener MouseAdapter MouseMotionListener MouseMotionAdapter WindowListener WindowAdapter

• Event Listeners as anonymous inner classes

Page 193: Introduction to Java

© Copyrights aurionPro Solutions Ltd.

Page 194: Introduction to Java

What is Swing?Swing is advertised as a set of

customizable graphical components whose look-and-feel can be dictated at runtime

Swing is built on top of the core 1.1 and 1.2 AWT libraries

In JDK 1.1, the Swing classes must be down loaded separately and included as an archive file on the classpath (swingall.jar). JDK 1.2 comes with a Swing distribution

© Copyright aurionPro Solutions Ltd.

Page 195: Introduction to Java

Swing features:

Pluggable Look & Feel Swing is capable of emulating several look-and-

feels, and currently includes support for Windows 98 and Unix Motif

Lightweight ComponentsComponents are not dependent on native peers

to render themselves. Instead, they use simplified graphics primitives to paint themselves on the screen and can even allow portions to be transparent

© Copyright aurionPro Solutions Ltd.

Page 196: Introduction to Java

Swing Components

There are various swing components available

Some of them are mentioned below:JButton, JLabel, JTextfield, JComboBoxes etc.JTable, JList, JTree, JSliderPane, JOptionPane

etc.Containers – JFrame, JApplet, JPanel etc.

© Copyright aurionPro Solutions Ltd.

Page 197: Introduction to Java

Swing Hierarchy

© Copyright aurionPro Solutions Ltd.

Java.lang.object

JComponent(abstract)

JContainer(abstract)

JPanel JWindow

Java.applet.Applet Dialog Frame

GUI control components areconcrete subclasses of this class.

Page 198: Introduction to Java

JComponent Class

Tool tips: setToolTipText method Painting and borders: The setBorder method

allows you to specify the border that a component displays around its edges

Application-wide pluggable look and feel Double buffering: Double buffering smooths

on-screen paintingKey bindings

© Copyright aurionPro Solutions Ltd.

Page 199: Introduction to Java

JComponent API

Customizing Component Appearance: Border, Foreground, Background, Font etc.

Setting and Getting Component State Handling Events: add Listener methodsPainting Components: repaint, revalidate Dealing with the Containment Hierarchy:

add, remove Laying Out Components: getPreferedSize

© Copyright aurionPro Solutions Ltd.

Page 200: Introduction to Java

Top Level Container

Swing provides three generally useful top-level container classes: JFrame, JDialog, and JApplet

Points to rememberevery GUI component must be part of a

containment hierarchyEach GUI component can be contained only onceEach top-level container has a content pane

© Copyright aurionPro Solutions Ltd.

Page 201: Introduction to Java

Demo : First Swing Program

© Copyright aurionPro Solutions Ltd.

SwingApplication.java

Page 202: Introduction to Java

Demo : Top Level Container

© Copyright aurionPro Solutions Ltd.

FrameDemo.java

Page 203: Introduction to Java

Frames API

Creating and Setting Up a Frame : defaultOperations, IconImage etc.

Setting the Window Size and Location : pack, setSize, setBounds etc.

© Copyright aurionPro Solutions Ltd.

Page 204: Introduction to Java

Demo : Frame Demo

© Copyright aurionPro Solutions Ltd.

FrameDemo2.java

Page 205: Introduction to Java

What is an applet ?

Applets are small programs stored over web server

Transported over the netInstalled automaticallyRun as a part of web pageNeed an environment of web browser

© Copyright aurionPro Solutions Ltd.

Page 206: Introduction to Java

Applet basics

Any applet has to inherit from an Applet class

The methods in the Applet class areinit()start()paint(Graphics g)stop()destroy()

© Copyright aurionPro Solutions Ltd.

Page 207: Introduction to Java

Applet basics(Contd.)Adding an applet to html document

<html><applet code=“myapplet.class” width=400

height=400></applet> </html>

Running an Appletc:\appletviewer ex.html

© Copyright aurionPro Solutions Ltd.

Page 208: Introduction to Java

Applet basics(Contd.)

Applets do not have a main methodApplets must run under the environment of

web browserApplets do not have the right/permission to

access the file system on client machineThey can not perform any I/O operation

© Copyright aurionPro Solutions Ltd.

Page 209: Introduction to Java

A Simple Appletimport java.applet.Applet;import java.awt.*;public class simpleapp extends Applet

{public void init(){ //any initialization

setBackground(Color.black);setForeground(Color.yellow);

} public void paint(Graphics g){g.drawString(“Hello

World”,100,100);}

} © Copyright aurionPro Solutions Ltd.

Page 210: Introduction to Java

Other Applet methods

repaint(): to request painting againupdate() showStatus(String)getDocumentBase(): URL of HTML filegetCodeBase(): URL of applet filegetParameter(String): to retrieve the

parameter value from HTML document

© Copyright aurionPro Solutions Ltd.

Page 211: Introduction to Java

JAR files< applet archive=”appletbundle.jar”

code=”appletname.class” width=w height=h></applet>

JAR files can be made by using the jar toolJar cf appletbundle.jar *. class image.* ………

To display the content of the jar file Jar tf appletbundle.jar

To extract the content of the jar file Jar xvf appletbundle.jar

© Copyright aurionPro Solutions Ltd.

Page 212: Introduction to Java

Applets

Applet Life CycleFeatures

You add components to a Swing applet's content pane, not directly to the applet

The default layout manager for a Swing applet's content pane is BorderLayout

You should not put painting code directly in a JApplet object

© Copyright aurionPro Solutions Ltd.

Page 213: Introduction to Java

Applets (Contd.)

Threads in AppletIt's generally considered safe to create and

manipulate Swing components directly in the init method

© Copyright aurionPro Solutions Ltd.

Page 214: Introduction to Java

Applets (Contd.)

Embedding an Applet in an HTML Page <applet code="TumbleItem.class"

codebase="example-1dot4/" archive="tumbleClasses.jar tumbleImages.jar" width="600" height="95">

<param name="maxwidth" value="120"> <param name="nimgs" value="17"> <param name="offset" value="-57"> <param name="img" value="images/tumble">

© Copyright aurionPro Solutions Ltd.

Page 215: Introduction to Java

Applets (Contd.)

Your browser is completely ignoring the <applet> tag! </applet>

© Copyright aurionPro Solutions Ltd.

Page 216: Introduction to Java

Demo : Applet Demo

© Copyright aurionPro Solutions Ltd.

HelloSwingApplet.java

Page 217: Introduction to Java

Painting

JFrame- Content Pane – JPanel – JButton, JLabelThe top-level container, JFrame, paints itselfThe content pane first paints its background

and it paints its border, it then tells the JPanel to paint itself, finally the panel asks its children to paint themselves

© Copyright aurionPro Solutions Ltd.

Page 218: Introduction to Java

© Copyrights aurionPro Solutions Ltd.

Page 219: Introduction to Java

Design GoalsTo build a set of extensible GUI components

to enable developers to more rapidly develop powerful Java front ends for commercial applications

Be implemented entirely in Java to promote cross-platform consistency and easier maintenance

© Copyright aurionPro Solutions Ltd.

Page 220: Introduction to Java

Design Goals

Provide a single API capable of supporting multiple look-and-feels so that developers and end-users would not be locked into a single look-and-feel

Enable the power of model-driven programming without requiring it in the highest-level API

Adhere to JavaBeans design principles to ensure that components behave well in IDEs and builder tools

© Copyright aurionPro Solutions Ltd.

Page 221: Introduction to Java

Roots in MVCMVC architecture calls for a visual application to

be broken up into three separate parts:A model that represents the data for the applicationThe view that is the visual representation of that dataA controller that takes user input on the view and

translates that to changes in the model

© Copyright aurionPro Solutions Ltd.

Page 222: Introduction to Java

The delegate

Different view and controller became a difficult proposition

So the three entities collapsed into two with a single UI (user-interface) object

Component and UI delegate object

© Copyright aurionPro Solutions Ltd.

Page 223: Introduction to Java

What MVC facilitates?

Separating the model definition from a component facilitates model-driven programming in Swing

The ability to delegate some of a component's view/controller responsibilities to separate look-and-feel objects provides the basis for Swing's pluggable look-and-feel architecture

© Copyright aurionPro Solutions Ltd.

Page 224: Introduction to Java

Separable model architecture

© Copyright aurionPro Solutions Ltd.

Model Interface

Component

ButtonModel Jbutton, JCheckBox, JRadioButton, JMenuItem

BoundedRangeModel

JProgressBar, JScrollBar, JSlider

Document JTextField, JTextArea, JTextPane etc.

Page 225: Introduction to Java

Types of Models

GUI-state models define the visual status of a GUI controlrelevant only in the context of a graphical user

interface (GUI)Useful if multiple GUI controls are linked to a

common state e.g. shared white board programs

E.g ButtonModel, BoundedRangeModel

© Copyright aurionPro Solutions Ltd.

Page 226: Introduction to Java

Types of Models(Contd.)Application-data models

represents some quantifiable data that has meaning primarily in the context of the application

Like the value of a cell in a tableE.g. TableModel, Document, ListModel,

ComboBoxMdel

© Copyright aurionPro Solutions Ltd.

Page 227: Introduction to Java

The separable model API

Implemented as a JavaBeans bound property for the component

If you don't set your own model, a default is created and installed internally in the component

For more complex models like Jlist or Jtable abstract model implementations are provided

© Copyright aurionPro Solutions Ltd.

Page 228: Introduction to Java

Model change notification

Models must be able to notify any interested parties (such as views) when their data or value changes

Swing models use the JavaBeans Event modelTwo Approaches for notification

Lightweight Notification a single event instance can be used for all

notifications from a particular model

© Copyright aurionPro Solutions Ltd.

Page 229: Introduction to Java

Model change notification

Stateful Notification describes more precisely how the model has

changed

© Copyright aurionPro Solutions Ltd.

Page 230: Introduction to Java

© Copyrights aurionPro Solutions Ltd.

Page 231: Introduction to Java

Demos

Button, CheckBox, RadioButtonLabelsComboBoxesMenusProgressBars, Sliders, Spinners

© Copyright aurionPro Solutions Ltd.

Page 232: Introduction to Java

© Copyrights aurionPro Solutions Ltd.

Page 233: Introduction to Java

Split and Scroll Pane Pane

SplitPlaces 2 or more components side by side in

a single framePane can horizontal or vertical

ScrollProvide automatic scrolling facilityHorizontal and vertical headers are possible

© Copyright aurionPro Solutions Ltd.

Page 234: Introduction to Java

List Component

List component consists of three partsList data is assigned to a model i.e. ListModelUser Selection : User Selection ModelVisual Appearance : Cell RendererDemo : SimpleList.java

List model is a simple interface used to access data in the listDemo : ListModelExample.java

© Copyright aurionPro Solutions Ltd.

Page 235: Introduction to Java

List Component

Cell Rendering ListExample.java. BookCellRenderer.java

© Copyright aurionPro Solutions Ltd.

Page 236: Introduction to Java

Table Component

JTable class : demo SimpleTable.javaThe classes and interfaces involved are

TableColumn, TableColumnModelTableModelTableCellEditorTableCellRenderer

© Copyright aurionPro Solutions Ltd.

Page 237: Introduction to Java

Table Columns

The basic unit in swing table is a column and not a cell

Classes involved : TableColumn , TableColumnModel

TableColumn : It’s a starting point for building columns in the tableProperties : cellEditor,

cellRenderer,HeaderRendererTableColumnModel manages the column

selections and column spacing Demo of TableColumnModel :

ColumnExample.java,SortinColumnModel.java

© Copyright aurionPro Solutions Ltd.

Page 238: Introduction to Java

Table Data

The actual data that’s displayed in JTable is stored in a TableModel

TableModel interface : has access to all cell values in a tablecolumnCount, rowCountCell methods

Object getValueAt(int, int) boolean isCellEditable(int,int) void setValueAt(Object,int,int)

© Copyright aurionPro Solutions Ltd.

Page 239: Introduction to Java

Table Data

SubClasses : AbstractTableModel, DefaultTableModel

© Copyright aurionPro Solutions Ltd.

Page 240: Introduction to Java

Editing and Rendering

Possible to build customized editors and renderers for the cell

Default are:Boolean - JCheckBoxNumber - right aligned JTextFieldObject - JTextFieldImageIcon

© Copyright aurionPro Solutions Ltd.

Page 241: Introduction to Java

Editing and Rendering (contd..)

TableCellRendererComponet getTableCellRendererComponent(..)Demo : FileTable2.java, FileModel.java,

BigRenderer.javaTableCellEditor

Componet getTableCellEditorComponent(..)Selecting Table Entries

Uses ListSelectionModelRow and Column selection models are different

objects

© Copyright aurionPro Solutions Ltd.

Page 242: Introduction to Java

Tree TerminologyPath : A list of nodes leading from one

node to anotherCollapsed : Invisible childrenExpanded : Visible children

© Copyright aurionPro Solutions Ltd.

Page 243: Introduction to Java

Tree Models

Two interfaces are particularly importantTreeModel : describes how to work with tree

dataTreeSelectionModel : describes how to select

the modesDefaultTreeModel class puts together a basic

tree model using TreeNode objectsEach node’s data is really just an Object

reference, pointing to just about any object

© Copyright aurionPro Solutions Ltd.

Page 244: Introduction to Java

Tree Models (contd.)

MutableTreeNode defines the requirements for a tree node object that can change -- by adding or removing child nodes, or by changing the contents of a user object stored in the node

DefaultMutableTreeNode Mutation Methods: insert, remove etcStructure Methods : provides methods to

modify and querying the structureEnumeration Methods

© Copyright aurionPro Solutions Ltd.

Page 245: Introduction to Java

Tree SelectionsSelections are based on rows and pathsPath contains the list of nodes from the root

of the tree to another nodeRows are completely dependent on the visual

display of the treeDepending on the application the row or

path selection can be used

© Copyright aurionPro Solutions Ltd.

Page 246: Introduction to Java

Demo : Tree Demo

© Copyright aurionPro Solutions Ltd.

TreeDemo.java

Page 247: Introduction to Java

Java Database Connectivity

© Copyrights aurionPro Solutions Ltd.

Page 248: Introduction to Java

Java Database ConnectivityJavaSoft worked with D/B tool vendors to

provide DBMS independent mechanism to write client side applications

The result is JDBC API JDBC API is designed to allow developers to

create database front ends without having to continually rewrite the code

An API that is D/B independent and uniform across databases

© Copyright aurionPro Solutions Ltd.

Page 249: Introduction to Java

Java Database Connectivity

A standard to write which takes all app. designs into account

This is possible through a set of interface that are implemented by the driver

Driver is responsible for converting a standard JDBC call to a native call

© Copyright aurionPro Solutions Ltd.

Page 250: Introduction to Java

What is JDBC

Java Database Connectivity (JDBC) is a standard SQL database access interface, providing uniform access to a wide range of relational databases

JDBC provides a common base on which higher level tools and interfaces can be built

© Copyright aurionPro Solutions Ltd.

Page 251: Introduction to Java

What does JDBC Do ?JDBC makes it possible to do three things:

1) Establish a connection with a database2) Send SQL statements3) Process the results

© Copyright aurionPro Solutions Ltd.

Page 252: Introduction to Java

Why JDBC ?Java is a write once, run anywhere languageJava based clients are thin clientSuited for network centric modelsIt provide a clean , simple, uniform vendor

independent interfaceJDBC support all the advance features of

latest version ANSI SQLJDBC API provides a rich set of methods

© Copyright aurionPro Solutions Ltd.

Page 253: Introduction to Java

Database Connectivity

JDBCODBC

© Copyright aurionPro Solutions Ltd.

Page 254: Introduction to Java

ODBC Architecture

© Copyright aurionPro Solutions Ltd.

ODBC API

ODBC Driver Manager

Application Application

Oracle Driver

SQL Server Driver

DB 2 Driver

SQL * Net Net Lib ESQL/DRDA

Oracle Database

SQL Server

DB 2

Application

Service Provider API

Page 255: Introduction to Java

JDBC Architecture

© Copyright aurionPro Solutions Ltd.

JDBC Driver Manager

Application Application

Oracle Driver

SQL Server Driver

JDBC -ODBC Driver

SQL * Net Net Lib

Oracle Database

Sybase

Application

ODBC Driver

SQL Server

JDBC API

Service Provider API

Page 256: Introduction to Java

So why not just use ODBC from Java?

ODBC relies on the multiple use of void * pointers and other C features that are not natural in java

ODBC driver manager and drivers must be manually installed on every client machine. JDBC code is automatically installable, portable, and secure

ODBC is procedure oriented, while JDBC is object oriented

© Copyright aurionPro Solutions Ltd.

Page 257: Introduction to Java

Two-tier and Three-tier Models

© Copyright aurionPro Solutions Ltd.

JDBC API supports both two-tier and three-tier models for database access

Java Applet or HTML browser

Application server (JAVA)

JDBC

HTTP,RMI,CORBA

Propriety protocal

Client GUI

Database server

Business logic

JAVA Application

JDBC

DBMS

Propriety protocol

Three-tier JDBCTwo-tier JDBC

Page 258: Introduction to Java

JDBC API - java.sql

© Copyright aurionPro Solutions Ltd.

Statement PreparedStatement CallableStatement

Connection

Driver

ResultSet

DatabaseMetaData ResultSetMetaData

Interfaces in java.sql

Page 259: Introduction to Java

JDBC components

© Copyright aurionPro Solutions Ltd.

Driver ManagerDriver Manager

Driver

Connection

Statement

ResultSet

PreparedStatement CalllableStatement

ResultSet ResultSet

Page 260: Introduction to Java

Database access from Java

Steps InvolvedLoading the DriverEstablishing the connectionPassing Sql Query

© Copyright aurionPro Solutions Ltd.

Page 261: Introduction to Java

Loading DriversClass.forName()throws

ClassNotFoundException- sun.jdbc.odbc.JdbcOdbcDriver - jdbc.driver.oracle.OracleDriver

try {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver

");}catch(ClassNotFoundException e) {

System.out.println(“Exception : “ + e);}

© Copyright aurionPro Solutions Ltd.

Page 262: Introduction to Java

Types of Driver

Type I : Jdbc-Odbc Bridge DriverType II : Partly Java, partly native code

implementing Vendor specific API

Type III : Pure Java driver requesting either to type I or II as another layer

Type IV : Pure Java requesting directly to the database

© Copyright aurionPro Solutions Ltd.

Page 263: Introduction to Java

Establishing ConnectionA JDBC URL has the following syntax

String url= jdbc:<subprotocol>:<subname>// for odbcString url= “jdbc:odbc:employee” ;// for jdbcString url= “jdbc:oracle:thin:@tech:1521:ORCL” ;Connection con = DriverManager.getConnection

(“url,"myLogin", "myPassword")

© Copyright aurionPro Solutions Ltd.

Page 264: Introduction to Java

Retrieving Data from TableResultSet executeQuery( String sql) throws

SQLExceptionResultSet rs = stmt.executeQuery("SELECT

name, age FROM student"); Retrieving data from Resultset

boolean next( ) throws SQLException void Close ( ) throws SQLException XXX getXXX( int index ) throws SQLException

© Copyright aurionPro Solutions Ltd.

Page 265: Introduction to Java

Retrieving data from ResultSet

String query = " SELECT name, age FROM student "; ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String s = rs.getString("name"); BigDecimal n =

rs.getBigDecimal("age"); System.out.println(s + " " + n); }

The output will look something like this: Smith 20 Rahul 19

© Copyright aurionPro Solutions Ltd.

Page 266: Introduction to Java

RowSets

A RowSet object contains a set of rows from a result set or some other source of tabular data, like a file or spreadsheet. Because a RowSet object follows the JavaBeans model for properties and event notification, it is a JavaBeans component that can be combined with other components in an application

© Copyright aurionPro Solutions Ltd.

Page 267: Introduction to Java

Types of RowSets

JdbcRowSet: A connected scrollable ,updatable RowSet

CachedRowset:A disconnected RowSetWebRowSet:A connected RowSet that uses

the HTTP protocol internally to talk to a Java Servlet that provides data access

© Copyright aurionPro Solutions Ltd.

Page 268: Introduction to Java

Inserting Data into Tables

executeUpdate( ) throws SQLExceptionStatement stmt = con.createStatement();stmt.executeUpdate("INSERT INTO student " +

"VALUES (1, 'Smith', ' Bombay' , 20, 7646234 ) )";stmt.executeUpdate("INSERT INTO st_ course " + "VALUES (1, 1, 01-01-1999, 'Very Good' )");

© Copyright aurionPro Solutions Ltd.

Page 269: Introduction to Java

Updating TablesexecuteUpdate()Statement stmt = con.createStatement();stmt.executeUpdate( "UPDATE course”+ “SET

fees = fees+2000.00" );

© Copyright aurionPro Solutions Ltd.

Page 270: Introduction to Java

Using PreparedStatement

PreparedStatement prep = con.prepareStatement( "UPDATE"+ " course values set fees = ? WHERE c-id = ?");

prep.setInt(1, 2);prep.setBigDecimal(2, 8000.00);prep.executeUpdate ( );prep.setInt(1, 4);prep.setBigDecimal(2,

9000.00);prep.executeUpdate ( );

© Copyright aurionPro Solutions Ltd.

Page 271: Introduction to Java

DataSource and Connection Pooling

DataSource:The JDBC 2.0 extension API introduced the concept of data sources, which are standard, general-use objects for specifying databases or other resources to use

© Copyright aurionPro Solutions Ltd.

Page 272: Introduction to Java

What is a DataSource?

A DataSource object is the representation of a data source in the Java programming language. In basic terms, a data source is a facility for storing data. It can be as sophisticated as a complex database for a large corporation or as simple as a file with rows and columns. A data source can reside on a remote server, or it can be on a local desktop machine

© Copyright aurionPro Solutions Ltd.

Page 273: Introduction to Java

What is a DataSource?

Applications access a data source using a connection, and a DataSource object can be thought of as a factory for connections to the particular data source that the DataSource instance represents

© Copyright aurionPro Solutions Ltd.

Page 274: Introduction to Java

Comparison between DriverManager and DataSource

While directly creating a connection by calling DriverManager.getConnection(..) , you are creating a connection by yourself and when closing close() on it, the link to database is lost. On the other hand we get a connection from a datasource, when you call the close() on it, it will not close the link to database, but will return to a connection pool where it can be reused by some other classes

© Copyright aurionPro Solutions Ltd.

Page 275: Introduction to Java

Comparison between DriverManager and DataSource(Contd.)

It is always better to use a connection pool because creating connections are expensive. DataSource has its usability in the distributed computing environment,as it can be used with JNDI lookups

Another major advantage is that the DataSource facility allows developers to implement a DataSource class to take advantage of features like connection pooling and distributed transactions

© Copyright aurionPro Solutions Ltd.

Page 276: Introduction to Java

Using Callable StatementString sql=“execute getEmployes ? ”;CallableStatement call=con.prepareCall(sql);

call.registerOutParameter(1,Types.INTEGER);call.execute();int val=call.getInt(1);System.out.println(“There are ” +val + “ employees”);

© Copyright aurionPro Solutions Ltd.

Page 277: Introduction to Java

Using Transactionscon.setAutoCommit(boolean commit)

con.commit() con.rollback()

try {

con.setAutoCommit(false);

// perform transactions

con.commit()

con.setAutoCommit(true);

} catch (SQLException e) {

con .rollback() ;}

© Copyright aurionPro Solutions Ltd.

Page 278: Introduction to Java

Collections Framework in Java

© Copyrights aurionPro Solutions Ltd.

Page 279: Introduction to Java

What is Collections Framework?

A Collection is a group of objectsCollections framework provide a a set of

standard utility classes to manage collections

Collections Framework consists of three parts:Core InterfacesConcrete ImplementationAlgorithms such as searching and sorting

© Copyright aurionPro Solutions Ltd.

Page 280: Introduction to Java

Collections Hierarchy

© Copyright aurionPro Solutions Ltd.

Page 281: Introduction to Java

Collection – Basic Operations

int size();boolean isEmpty();boolean contains(Object element);boolean add(Object element); boolean remove(Object element); Iterator iterator();

© Copyright aurionPro Solutions Ltd.

Page 282: Introduction to Java

Collection – Bulk Operations

boolean containsAll(Collection c); boolean addAll(Collection c); boolean removeAll(Collection c); boolean retainAll(Collection c); void clear();

© Copyright aurionPro Solutions Ltd.

Page 283: Introduction to Java

Collection –Array Operations

Object[] toArray(); Object[] toArray(Object a[]);

© Copyright aurionPro Solutions Ltd.

Page 284: Introduction to Java

Collection Interfaces

© Copyright aurionPro Solutions Ltd.

Map is in the sorted key order.SortedMap

For classes implementing key-value pair kind pf mappings. Can not contain duplicate keys.

Map

An ordered collection (i.e. sequence). Duplicates and multiple null values allowed.

List

Maintains the elements in sorted order.SortedSet

Maintains a set of unique elements.Set

Defines the operations that all classes that maintain collections typically implement

Collection

DescriptionInterfaces

Page 285: Introduction to Java

Concrete Implementations

© Copyright aurionPro Solutions Ltd.

LinkedList

Linked List

TreeMapTreeSetBalancedTree

ResizableArray

HashMap

HashSet

Hashtable

SortedMapMapListSortedSetSetDataStructures

Interfaces

Array List

Page 286: Introduction to Java

The Classes

Legacy classes Vector HashTable Stack

© Copyright aurionPro Solutions Ltd.

Page 287: Introduction to Java

Thank you

© Copyright aurionPro Solutions Ltd.