Sunteți pe pagina 1din 251
Copyright © 2008 by Patni 1
JAVA
JAVA
Day-wise Schedule Day 1 Introduction to Java Language Fundamentals OOP Concepts Applied to Java Day
Day-wise Schedule
Day 1
Introduction to Java
Language Fundamentals
OOP Concepts Applied to Java
Day 2
Important Classes and Keywords in Java
Packages and Interfaces
Eclipse, an IDE
Day-wise Schedule Day 3 Exception Handling Documenting in Java – javadoc Java Coding Conventions Code
Day-wise Schedule
Day 3
Exception Handling
Documenting in Java – javadoc
Java Coding Conventions
Code Reviews and Review Checklist
Day 4
Collections Framework in Java
Java Property files
Day 5
Files and Streams
Introduction to Multithreading in Java
Day-wise Schedule Day 6 Multithreading in Java (Contd.) Day 7 Java Applets Day 8,9 JDBC
Day-wise Schedule
Day 6
Multithreading in Java (Contd.)
Day 7
Java Applets
Day 8,9
JDBC
Day 10
Networking Concepts
Day 11
Security in Java 2
Introduction to Java
Introduction to Java
Java’s Lineage • C language was result of the need for structured, efficient, high-level language
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

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

Features of Java • Completely Object-Oriented • Simple • Distributed : full support for TCP/IP
Features of Java
• Completely Object-Oriented
• Simple
• Distributed : full support for TCP/IP protocol,
developing distributed applications is easy
• Robust : Strongly typed language
• Secure

Java is completely object oriented. In C++, being more compatible to C, allows code to exist outside classes too, but in Java, every line of code has to belong to some or other class. Thus it is closer to true object oriented language.

Java is simpler than C++, since concepts of pointers or multiple inheritance is not there.

Features of Java • Architecture Neutral : Platform independent • Interpreted and Compiled • Dynamic
Features of Java
• Architecture Neutral : Platform independent
• Interpreted and Compiled
• Dynamic
• Multithreaded : Concurrent running tasks
Features added in Java 1.1 • Java-Beans : Component Technology • Serialization • Remote Method
Features added in Java 1.1
• Java-Beans : Component Technology
• Serialization
• Remote Method Invocation
• JDBC
• Java Native Interface
• Inner classes
Features added in Java 2 (Java 1.2) • Java Swing • CORBA : Common Object
Features added in Java 2 (Java 1.2)
• Java Swing
• CORBA : Common Object Request Broker Architecture
• Digital Certificates : ensures security policies
• Collection API : e.g. linked list, dynamic array
Features added in Java 1.3 • XML Processing • JDBC 3.0 API • Swing Drag
Features added in Java 1.3
• XML Processing
• JDBC 3.0 API
• Swing Drag and drop
• Internationalization
• Performance Improvement in Reflection APIs
• JNDI
• Java Print service API
Features added in 1.4 • New Security certificates added • New Swing Features • New
Features added in 1.4
• New Security certificates added
• New Swing Features
• New I/O API
• Logging
• Secure Sockets
• Assertions

It should be mentioned to the participant that current version of Java is 1.5, although not covered as part of this training.

Platform Independence Unix on Pentium System Macintosh PowerPC system .java file Class Loader PowerPC Bytecode
Platform Independence
Unix on Pentium System
Macintosh PowerPC system
.java file
Class Loader
PowerPC
Bytecode
machine level
verifier
Java
instructions
JIT compiler
compiler
Class file
Windows Pentium PC system
containing
Bytecodes
Class Loader
Bytecode
Pentium
Class Loader
Verifier
machine level
Bytecode
JIT compiler
instructions
verifier
JIT compiler
Platform Independence (Contd.) • Platform independence primarily helps Java Applets to be executed on any
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
Difference between JRE and JDK • JRE is the ‘Java Runtime Environment'. It is responsible
Difference between JRE and JDK
• JRE 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

It should be noted that JRE is re-distributable but JDK is not re-distributable. JRE can be bundled along with your own software that you intend to sell commercially too. However, one can’t bundle JDK along with one’s own software. JDK is freely downloadable, but not freely redistributable.

Relation between Java and Sun • Sun Microsystems defined and published Java Language Specification •
Relation between Java and Sun
• Sun Microsystems defined and published Java
Language Specification
• Sun 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
First Simple Program //this is my first program class Example { /* the execution starts
First Simple Program
//this is my first program
class Example {
/* the execution starts here */
public static void main(String args[]) {
System.out.println(“Welcome to Java “);
}
}
Compile and Run Program • To compile the program: c:\javac Example.java • To run it:
Compile and Run Program
• To compile the program:
c:\javac Example.java
• To run it:
c:\java Example
Language Fundamentals
Language Fundamentals
Data types Type Size/Format Description byte 8-bit Byte-length integer short 16-bit Short Integer int 32-bit
Data types
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
Default Values • Integer : 0 • Character : ‘\u0000’ • Decimal : 0.0 •
Default Values
• Integer
:
0
• Character
:
‘\u0000’
• Decimal
:
0.0
• Boolean
:
false
• Object Reference
:
null
Variables • Basic unit of storage in a Java program • Three types of variables:
Variables
• Basic unit of storage in a Java program
• Three types of variables:
Instance variables
Static variables
Local variables
• Each variable type has different scope
• Formal parameters (i.e. arguments to function) are
similar to local variables
Operators • Arithmetic operators: +, - , * , / ,% ++, -- +-, -=,
Operators
• Arithmetic operators:
+, - , * , / ,%
++, --
+-, -=, *= , /= , %=
• Relational operators:
== , != , >=,>,<=,<
• assignment(=), ternary(?)
Please find additional inputs about in Appendix-H
Introduction to Classes The general form of a class class < class_name>{ type var1;… Type
Introduction to Classes
The general form of a class
class < class_name>{
type var1;…
Type method_name(arguments ){
body
}…
} //class ends.
Introduction to Classes A Simple Class class Box{ double width; double height; double depth; double
Introduction to Classes
A Simple Class
class Box{
double width;
double height;
double depth;
double volume(){
return width*height*depth;
} //method volume ends.
}//class box ends.
Declaring Objects class impl{ public static void main(String a[]){ //declare a reference to object Box
Declaring Objects
class 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(); }
}
Types of class members • default access members (No access specifier) • private members •
Types of class members
• default access members (No access specifier)
• private members
• public members
• protected members
Memory Management • Dynamic and Automatic • No delete operator • Implemented by Garbage Collector
Memory Management
• Dynamic and Automatic
• No delete operator
• Implemented by Garbage Collector
Garbage Collector is the Lowest Priority Daemon Thread
It runs in the background when JVM starts
Collects all the unreferenced objects
Frees the space occupied by these objects
System.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

There is a common misconception that system.gc() invokes the garbage collector, however that is not true. It just gives a request or hint to JVM to start garbage collector, but JVM may not start it immediately or even till end of the program execution. It is JVM implementation dependent issue, as to when it would start. It can even do some optimization by starting garbage collection, only when certain amount of memory is consumed etc.

Arrays • A group of like-typed variables referred by common name • Declaring an array
Arrays
• A group of like-typed variables referred by common
name
• Declaring 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
Arrays • Arrays of objects too can be created Example 1 : Box Barr[] =
Arrays
• Arrays of objects too can be created
Example 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”);
Casting of Variables • To convert one variable value to other, wherein two variables correspond
Casting of Variables
• To convert one variable value to other, wherein two
variables correspond to two different data types
Double d = 10.5;
float f = (float) b;
• Widening does not require casting
• Casting 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
UpCasting & DownCasting • Upcasting Object o = new String(“HELLO”); Serializable s = new String(“New”);
UpCasting & DownCasting
• Upcasting
Object o = new String(“HELLO”);
Serializable s = new String(“New”);
• DownCasting
String s1 = (String) o;
String s2 = (Serializable) s
Parameter Passing • Parameters or arguments passed to a function are passed by value for
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)

Trainer can demonstrate this by showing a code such as this:

void myFunction(int a) {

a++;

System.out.println(a);

}

….

int x = 45;

System.out.println(x);

myFunction(x);

System.out.println(x);

Output will be, “45 46 45”

This is an example of pass-by-value.

In above example, use “Integer” class, instead of int, and it becomes example of pass-by-reference.

The output should be “ 45 46 46”.

Java is Object Oriented
Java is Object Oriented
Inheritance • One of the major pillars of OO approach • Allows creation of hierarchical
Inheritance
• One of the major pillars of OO approach
• Allows creation of hierarchical classification
• Advantage 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
Inheritance (Contd.) • Inherited members can be used with the super keyword super() ;// calls
Inheritance (Contd.)
• Inherited members can be used with the super
keyword
super() ;// calls parent class constructor
super.overriden() ;// calls an overriden method of the base
class
Inheritance (Contd.) Class Base { public void meth1() { System.out.println(“Method1 of Base”); } } Class
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”);
}
}
Inheritance (Contd.) class Test { public static void main(String args[]){ Derived d1=new Derived(); d1.meth1(); }
Inheritance (Contd.)
class Test
{
public static void main(String args[]){
Derived d1=new Derived();
d1.meth1();
}
}
Inheritance (Contd.) Output: Method1 of Base Method1 of Derived
Inheritance (Contd.)
Output:
Method1 of Base
Method1 of Derived
Polymorphism • An objects ability to decide what method to apply to itself depending on
Polymorphism
• An 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

Need to give example of Polymorphism referring to sample Java class.

Abstract class • A class that provides common behavior across a set of subclasses, but
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 code
Help at places where implementation is not available

Example of Abstract class – Shape Hierarchy –

You have two hierarchies : Point-Circle-Cylinder and Line-Square-Cube

Here common method is area() – if I create an array that contains the objects of all these classes. How can I do it generically ? Can Point p = new Line() be valid ? of course not, no inheritance !!!!

So I force a super class Shape which would contain the method area(). Now what implementation I am going to write in that method. I don’t know, at runtime whose area() is going to be called. So the information that I don’t know I put it as “abstract”.

Important points about abstract class :

1. You cannot create object of abstract class : why ?

e.g. if a surgeon know how to perform an operation but he doesn’t know how to stitch back the cut stomach will I allow him to touch me?

2.An abstract class can contain concrete methods.

3.An abstract class may not contain any abstract methods.

4. In Java a pure virtual method is called as abstract method.

abstract class Shape{

public abstract float area();

}

Abstract class (Contd.) • Any class that has even one method as abstract should be
Abstract class (Contd.)
• Any class that has even one method as abstract
should be declared abstract
• Abstract classes can’t be instantiated
• Abstract modifier cant be used for constructors &
static methods
• Any 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

In C++, an abstract class is called a pure virtual function & is tagged with a trailing

0;

Eg :

Class MyClass

{

 

public:: virtual void area() = 0;

}

Encapsulation • Encapsulation describes the ability of an object to hide its data and methods
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

Need to mention to participants that access specifiers are discussed in detail in later.

Important Keywords and Classes in Java
Important Keywords and Classes in Java
Constants • Use the final keyword before the variable declaration and include an initial value
Constants
• Use 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;
Final Classes and Methods • Final Classes Final classes cannot be inherited All methods in
Final Classes and Methods
• Final Classes
Final classes cannot be inherited
All methods in a final class are implicitly final
• Final Methods
final methods cannot be overridden
Methods declared as static are implicitly final
Also methods declared private are implicitly final
Static Members • You can declare both methods and variables to be static • Static
Static Members
• You can declare both methods and variables to be
static
• Static methods has got following restrictions
They can call only static methods
They can access static data only
Cannot refer to this or super
Static methods can access non-static variables and non-
static methods, provided explicit instance variable is made
available to the method
Nested classes • Class within another class • The scope of a nested class is
Nested classes
• Class within another class
• The scope of a nested class is bounded by the scope
of its enclosing class
• Nested classes are of two types:
Static
Non-static
• Nested classes should be used to reflect and enforce
the relationship between two classes
Anonymous Inner classes • These classes do not have a name • Are defined at
Anonymous Inner classes
• These classes do not have a name
• Are 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
Object Superclass • Cosmic super class • Ultimate ancestor – every class in Java implicitly
Object Superclass
• Cosmic super class
• Ultimate ancestor – every class in Java implicitly
extends Object
• A variable of type Object can be used to refer to objects
of any type
Eg. Object obj = new Emp();
• Methods in Object class are :
void finalize()
Class getClass()
String toString()
The System Class • The System class is the class used to interact with any
The System Class
• The System class is the class used to interact with
any of the system resources
• It can not be instantiated
• Contains a lot of methods and variables to handle
system I/O
• Among the facilities provided by the System class are
standard input, standard output, and error output
streams
The System Class • Some of the methods in System class: System.gc(): is a suggestion
The System Class
• Some 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 collect
everything
System.exit(0);
String Handling • String is handled as an object of class String and not as
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
Some methods of String class • length() : length of String • indexOf() : searches
Some methods of String class
• length() : length of String
• indexOf() : searches for the occurrence of a char, or
String within other String
• substring() : retrieves substring from the object
• trim() : to remove spaces
• valueOf() : converts data to String
The String Class String str = new String(“Pooja”); String str1 = new String(“Sam”); Heap Stack
The String Class
String str = new String(“Pooja”);
String str1 = new String(“Sam”);
Heap Stack
Pooja
str
Sam
str1
String str = new String(“Pooja”);
String str1 = str;
str
Pooja
str1
StringBuffer Class • Peer class of String class that represents fixed length, immutable char sequence
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
Wrapper Classes • Primitives are not a part of object hierarchy • Primitives are passed
Wrapper Classes
• Primitives are not a part of object hierarchy
• Primitives are passed by value
• Object representation of primitives is required
• Wrapper classes provide a way to encapsulate simple
values as objects
• Integer, Double, Float, Character are all wrapper
classes
Packages and Interfaces
Packages and Interfaces
Interfaces – Their need • Interface defines a data-type without implementation • The interface approach
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{
}

But a var of type Object is useful only as a generic place holder for arbitrary values.

To do anything specific, you have to cast.

Eg. Emp e = (Emp)obj;

have an idea of the original type & apply a

Interfaces • A Java interface definition looks like a class definition that has only abstract
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);
}
Declaring and Using Interfaces public interface simple_cal { int add(int a, int b); int i=10;
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;
}}
Interfaces - rules • Methods in an interface are always public & abstract • Data
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

C++ has multiple inheritance & all the complications that come with it, such as virtual base classes, dominance rules & transverse pointer casts.

Few C++ programmers use multiple inheritance, & some say it should never be used.

Interfaces & Abstract classes • Abstract classes are used only when there is a “is-a”
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
Packages • Are a named collection of classes • Are a way of grouping related
Packages
• Are a named collection of classes
• Are a way of grouping related classes & interfaces
• A 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

Consider a lib wwith a large no of unordered collection of books. Imagine the time you spend in searching for a book on java!!!

But suppose books are categorised & arranged in sections? Accessing would be a lot easier.

Packages : Their need • Allow to organize classes into units • Reduce problems with
Packages : Their need
• Allow to organize classes into units
• Reduce problems with naming conflicts
• Allow to protect classes, variables & methods in a
larger way than on a class-to-class basis

1. Like folders , subfolders, sub-sub-folders etc on your local directory system!!! Packages create groupings for related interfaces & classes. Eg. A set of lib classes for performing statistical analysis could be grouped together in a stats package.the package could be placed in a archive file together with a manifest describing the package & shipped to customers for use in their applications.

2. Packages create namespaces that help avoid naming conflicts between types. Interfaces & classes in a package can use popular public names like list & constants that make sense in one context but might conflict with the same name in another package.

3. Packages provide a protection domain for developing application frameworks. Code within a package can cooperate using access to identifiers that are unavailable to external code.

Package nesting

Packages can contain other packages.

The java class lib itself is distributed over a number of packages like java.lang, java.awt, java.net etc.

Nesting packages guarantees the uniqueness of package names

Using packages • To use a public class of a package, simple use the full
Using packages
• To use a public class of a package, simple use the full
package name
E.g. Java.util.Date = new java.util.Date();
• import statement: allows to import all the public
classes in a package
E.g. import java.awt.*;
• If the required class is in java.lang package, it can be
used directly

Diff between import & # include.:

Import is a statement; include is a directive.

Include bloats the size of the executable, import merely indicates where class can be found.thus, size of executable doesn’t increase.

Defining A Package package com.patni.trg.demo; // import statements here. public class Balance { String name;
Defining A Package
package com.patni.trg.demo;
// import statements here.
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
}
Defining A Package public void show() { if(bal<0) System.out.print("-->> ");
Defining A Package
public void show() {
if(bal<0)
System.out.print("-->> ");
System.out.println(name + ": $" +
bal);
}
}
Compiling A Package • Specify the path of the directory, where com directory is to
Compiling A Package
• Specify the path of the directory, where com directory
is to be created
• Example
javac –d . Balance.java
javac –d E:\JavaAss\MyAss Balance.java
Package scope access • Default: features of a class having default scope can be accessed
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
Access Specifiers Private NoModifier Protected Public Same class Y Y Y Y Same Package Subclass
Access Specifiers
Private
NoModifier
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 PackageSubclass
N
N
Y
Y
Diffrent Packagenon-subclass
N
N
N
Y
Access Specifiers Package P1 Class A Package P2 Class B Class C Class G Class
Access Specifiers
Package P1
Class A
Package P2
Class B
Class C
Class G
Class F
Classpath • For java to be able to use a class, it has to be
Classpath
• For java to be able to use a class, it has to be able to
find that class on the file system
Otherwise, the runtime flags an exception that the class
does not exist
• Java uses 2 elements to find classes
The package name
The directories listed in classpath variable
Classpath(Contd.) • classpath : points to various places where java classes live • The specific
Classpath(Contd.)
• classpath : points to various places where java
classes live
• The specific location that Java compiler considers as
root of an package hierarchy is controlled by
classpath
e.g.
classpath = c:\jdk1.2.2\bin; c:\jdk1.4.2_03; d:\java;
How compiler locates a file • Compiler searches through all directories specified in the classpath
How compiler locates a file
• Compiler searches through all directories specified in
the classpath variable
• If . is specified in classpath, then it also checks current
directory
• If compiler still does not locate the file, it flags a
ClassNotFound Exception
Eclipse, an IDE
Eclipse, an IDE
What is an IDE? • An application or set of tools that allows a programmer
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)
Some examples of an IDE • Eclipse • JDeveloper • WSAD (WebSphere Studio Application Developer)
Some examples of an IDE
• Eclipse
• JDeveloper
• WSAD (WebSphere Studio Application Developer)
• JBuilder
Using Eclipse as an IDE • The Eclipse Project is an open source software development
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
Using Eclipse as an IDE • Our objective is to code Java programs faster with
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
Using Eclipse as an IDE • Developing the Java program will be easier as Eclipse
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

Trainer should explain each of these features to participants.

Eclipse-Plugins • Lomboz • Checkstyle • JDepend • PMD • Ant
Eclipse-Plugins
• Lomboz
• Checkstyle
• JDepend
• PMD
• Ant
Exception Handling
Exception Handling
Exception Handling • Exception is an object that describes an exceptional condition • Java Exception
Exception Handling
• Exception is an object that describes an exceptional
condition
• Java Exception handling is managed by 5 keywords
try, catch
finally
throw
throws
Exception Handling Throwable Exception Error RunTime Exception Compile Time Exception Unchecked Exception Checked
Exception Handling
Throwable
Exception
Error
RunTime Exception
Compile Time Exception
Unchecked Exception
Checked Exception

Common misconception found in new programmers in Java is– “Compile- time exceptions are those that occur at compile time and runtime exception are those that occur at runtime”. This is misleading. They need to be explained clearly that -- Checked exceptions are sometime called Compile time exception, but they do not really occur at compile time. Rather, they are checked by complier at compile time, to ensure that programmer has caught them or specified them in ‘throws’ clause of the signature. For unchecked exceptions, also called Runtime exceptions, compiler does not insist to handle them in code.

Some Examples • Checked Exceptions include: IOException SQLException ClassNotFoundException • Unchecked
Some Examples
• Checked Exceptions include:
IOException
SQLException
ClassNotFoundException
• Unchecked Exceptions include:
ArithmaticException
NullPointerException
ArrayIndexOutOfBoundsException
Using try and catch class demo { public static void main(String a[]) { try {
Using try and catch
class demo {
public static void main(String a[]) {
try {
int d = 0;
int a = 42 /d;
} catch(ArithmeticException ae) {
System.out.println(ae);
}
}}
Throw and Throws clause • It is a way to throw an exception explicitly •
Throw and Throws clause
• It is a way to throw an exception explicitly
• Must be an object of Throwable or it’s subclasses
Example:
public void passgrade(int a, int total) {
if (a > total)
throw new ArithmeticException();
}
Throws clause • If method is capable of throwing an exception, then caller needs to
Throws clause
• If 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
Finally clause • Finally clause creates a block of code that will be executed whether
Finally clause
• Finally 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”);
}
Application Specific Exceptions class ApplicationException extends Exception { private int detail;
Application Specific Exceptions
class ApplicationException extends Exception
{ private int detail;
ApplicationException(int a) {
detail = a;}
ApplicationException(String args) {
super(args); }
public String toString(){ return
"ApplicationException["+detail+"]";}
}
Documenting in Java - javadoc
Documenting in Java - javadoc
What is javadoc? • Javadoc is a tool that parses the declarations and documentation comments
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
Javadoc Comments • A general javadoc comment /** * This is the typical format of
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

At this stage, trainer may show how a typical Javadoc generated HTML page looks like. Visiting a framed version of Javadoc, with left-frame listing all the classes of a given package and right-frame showing documentation of a particular class would be good enough.

Javadoc Comments (Contd.) • Class and interface Documentation tags @see,@deprecated,@author,@version and more
Javadoc Comments (Contd.)
• Class and interface Documentation tags
@see,@deprecated,@author,@version and more
Example:
/** * A class representing a window on the screen.
* For example:
* @author patni
* @see java.awt.BaseWindow
*/
class Window extends BaseWindow {
}
Javadoc Comments (Contd.) • Field Documentation tags: • @see,@deprecated,@since,@serial and more • Example: /**
Javadoc Comments (Contd.)
• Field Documentation tags:
• @see,@deprecated,@since,@serial and more
• Example:
/**
*
The X-coordinate of the component.
*
*
@see #getLocation() */ int x = 1263732;
Javadoc Comments (Contd.) Constructor and Method Documentation Tags @see,@param,@return,@since,@throws,@exception and
Javadoc Comments (Contd.)
Constructor and Method Documentation Tags
@see,@param,@return,@since,@throws,@exception and more
/**
* Returns the character at the specified index. An index
* @param index the index of the desired character
Javadoc Comments (Contd.) * @return the desired character. * @exception StringIndexOutOfRangeException * if the index
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) {
*
}
Java Coding Conventions
Java Coding Conventions
Coding Conventions • Every project in Patni MUST follow consistent Java Coding Conventions, unless overridden
Coding Conventions
• Every project in Patni 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
Coding Conventions (Contd.) • Examples of Coding Conventions Guidelines Class level member variable should be
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

New fresh programmers (in Java or any other language) tend to name a variable such as this…

String string1 = new String();

int x = 45;

Later, once coding is completed, they search and replace variable “string1” with sensible name such “m_sUserName”, to comply with coding convention set in the project. This should be avoided. The culture should be developed to never ever name a variable without following its convention. Once it becomes a habit, it would never be forgotten and never need to be imposed

Coding Conventions (Contd.) • How do Coding Conventions help the project? Helps to define the
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 code
Helps during defect fixing and maintenance phase, since
variable names are indicative of its scope, type etc
Makes debugging of code person-independent
Saves efforts on documentation, since variable/method or
class names becomes self-describing
Coding Conventions (Contd.) • How to use Coding Conventions on the project? Typically defined by
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 phase
If 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 developer
Should get caught during code-reviews, if not followed

New fresh programmers (in Java or any other language) tend to name a variable such as this…

String string1 = new String();

int x = 45;

Later, once coding is completed, they search and replace variable “string1” with sensible name such “m_sUserName”, to comply with coding convention set in the project. This should be avoided. The culture should be developed to never ever name a variable without following its convention. Once it becomes a habit, it would never be forgotten and never need to be imposed

Coding Conventions (Contd.) • Coding Conventions can be found on Patni KC Patni KC Home
Coding Conventions (Contd.)
• Coding Conventions can be found on Patni KC
Patni KC Home -> Quality Processes -> Coding
Standards -> Java Coding Standards
• 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
• Coding Conventions

Trainer should open the attached PDF, and do a quick walk-through of Section 9 – which defines the naming conventions to be used. Rest of the sections should be left as reading exercise for participants. Trainer should insist on following these conventions for rest of the lab assignments within the course.

Code Reviews and Review Checklist
Code Reviews and Review Checklist
Reviews • Being SEI-CMMi Level 5 company, reviews are part of the life in Patni
Reviews
• Being SEI-CMMi Level 5 company, reviews are part
of the life in Patni
• Reviews 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 Patni
Self-Review
Peer-to-peer review
Peer review

SDLC stands for Software Development Life Cycle

Trainer can give high level understanding of what reviews mean to participant. Explain 3 different types of reviews at high level only.

Peer to Peer Code Reviews • Code is reviewed by Peer (colleague) • Why Peer
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-cycle
Defects 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
Java Code Review Checklist Code reviews should be done using a checklist, and should cover
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
Java Code Review Checklist (Contd.) Typically Java Code Review checklist looks like this Sample 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

There could be a walk-through of few bullets in this code review checklist, primarily for Section 2 – Core Java. Other sections can be skipped for now. This checklist may be used for code-reviews of rest or few of the code-assignments on this course.

Collections Framework in Java
Collections Framework in Java
What is Collections Framework? • A Collection is a group of objects • Collections framework
What is Collections Framework?
• A Collection is a group of objects
• Collections framework provide a a set of standard
utility classes to manage collections
• Collections Framework consists of three parts:
Core Interfaces
Concrete Implementation
Algorithms such as searching and sorting
Collections Hierarchy
Collections Hierarchy
Collection – Basic Operations • int size(); • boolean isEmpty(); • boolean contains(Object element); •
Collection – Basic Operations
• int size();
• boolean isEmpty();
• boolean contains(Object element);
• boolean add(Object element);
• boolean remove(Object element);
• Iterator iterator();
Collection – Bulk Operations • boolean containsAll(Collection c); • boolean addAll(Collection c); • boolean
Collection – Bulk Operations
• boolean containsAll(Collection c);
• boolean addAll(Collection c);
• boolean removeAll(Collection c);
• boolean retainAll(Collection c);
• void clear();
Collection –Array Operations • Object[] toArray(); • Object[] toArray(Object a[]);
Collection –Array Operations
• Object[] toArray();
• Object[] toArray(Object a[]);
Collection Interfaces Interfaces Description Collection Defines the operations that all classes that maintain
Collection Interfaces
Interfaces
Description
Collection
Defines the operations that all classes that maintain
collections typically implement
Set
Maintains a set of unique elements.
SortedSet
Maintains the elements in sorted order.
List
An ordered collection (i.e. sequence). Duplicates
and multiple null values allowed.
Map
For classes implementing key-value pair kind pf
mappings. Can not contain duplicate keys.
SortedMap
Map is in the sorted key order.
Concrete Implementations Interfaces Data Set SortedSet List Map SortedMap Structures Hashtable Hash Hash Set
Concrete Implementations
Interfaces
Data
Set
SortedSet
List
Map
SortedMap
Structures
Hashtable
Hash
Hash
Set
Map
Resizable
Array
Array
List
Balanced
TreeSet
TreeMap
Tree
Linked List
Linked
List
The Classes • Legacy classes Vector HashTable Stack
The Classes
• Legacy classes
Vector
HashTable
Stack
Java Property files
Java Property files
Java Property files • java.util.Properties is a platform-independent generalization of the DOS SET environment, or
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
Java Properties Java.util.Properties class: • The Properties class represents a persistent set of properties. The
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
Types of properties • Property files provide a means of storing key-value pair,which could be
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 properties
System properties
Types of properties • User specific properties: These properties are part of the Application.properties containing
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:oracle8i
driver=oracle.jdbc.driver.OracleDriver
username=scott
Types of properties • System properties: System properties give information about the environment of the
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
System Properties • System properties are read from System class, which give information about the
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.vm
Java.version
User.language
Java.home
User.region etc
Files and Streams
Files and Streams
Streams • Files are necessary for persisting data • Java views each file as a
Streams
• Files are necessary for persisting data
• Java views each file as a sequential stream of bytes
• Stream is generic term for ‘flow of data’
• Different streams are used to represent different kinds
of data flow
• When a file is opened, an object is created and a
stream is associated with the object
Streams(Contd.) • Thus, an object from which we can read a sequence of bytes is
Streams(Contd.)
• Thus, an object from which we can read a sequence of
bytes is input stream
• Thus, an object to which we can write a sequence of
bytes is output stream
• The 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
Java.io package • Provides an extensive set of classes for handling I/O to & from
Java.io package
• Provides an extensive set of classes for handling I/O
to & from various devices
• Contains many classes each with a variety of member
variables & methods
• It is layered ie. It does not attempt to put too much
capability into 1 class
• Instead a programmer can get the features he wants
by layering one class over another
I/O Handling • All Java programs automatically import java.lang package • This package defines a
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)
Input streams
Input streams
Output streams
Output streams
InputStream class • An abstract class that defines methods for performing I/p • Serves as
InputStream class
• An abstract class that defines methods for performing
I/p
• Serves as base class for all other InputStream classes
• Defines a basic interface for reading streamed bytes
of information
• Data in InputStream is transmitted one byte at a time

The typical scenario when using an input stream is to create an InputStream-derived object and then tell it you want to input information by calling an appropriate method. If no input information is currently available, the InputStream uses a technique known as blocking to wait until input data becomes available. An example of when blocking takes place is the case of using an input stream to read information from the keyboard. Until the user types information and presses Return or Enter, there is no input available to the InputStream object. The InputStream object then waits (blocks) until the user presses Return or Enter, at which time the input data becomes available and the InputStream object can process it as input.

InputStream class : some methods • int read() : Returns an integer representation of the
InputStream class : some methods
• int 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)

int read(byte buffer[]): Attempts to read up to buffer.length bytes into buffer and returns the actual number of bytes that were successfully read

int read(byte buffer[], int offset, int numbytes) :Skips over numbytes of input, returning the number of bytes actually skipped

Void mark(int numbytes) :Places a mark at the current point in the input stream that will remain valid until numbytes are read

int available() :returns the number of bytes of input currently available for reading

Using the Stream variables import java.io.*; class ReadKeys { public static void main (String args[])
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);
}
} }
OutputStream • void write (int b): Writes a single byte to an output stream •
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()
FileInputStream • The FileInputStream class creates an InputStream that you can use to read the
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 FileNotFoundException
FileInputStream(File fileobj) throws FileNotFoundException
FileOutputStream • The FileOutputStream class creates an OutputStream that you can use to read the
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)
ByteArrayInputStream • ByteArrayInputStream is an implementation of an input stream that uses a byte array
ByteArrayInputStream
• ByteArrayInputStream 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)
Chaining of streams • Each class accesses the output of the previous class through the
Chaining of streams
• Each class accesses the output of the previous class
through the in variable
• Example
FileOutputStream fos = new FileOutputStream(c:\a.txt”);
DataOutputStream dos = new DataOutputStream(fos);
Character Streams: Readers/Writers • Reader and Writer classes are designed for character streams • Reader
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
Reader hierarchy
Reader hierarchy
Writer hierarchy
Writer hierarchy
File class • File class doesn’t operate on streams • Represents the pathname of a
File class
• File class doesn’t operate on streams
• Represents the pathname of a file or directory in the
host file system
• Used 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
File class • Some methods canRead() exists() isFile() isDirectory() getAbsolutePath() getName()
File class
• Some methods
canRead()
exists()
isFile()
isDirectory()
getAbsolutePath()
getName()
File class methods (Contd.) getPath() getParent() Length() : returns length of file in bytes as
File class methods (Contd.)
getPath()
getParent()
Length() : returns length of file in bytes as long
lastModified()
Mkdir()
List() : obtain listings of directory contents
Serialization • Serializability of a class is enabled by the class implementing the java.io.Serializable interface.
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
Object Serialization • Allows an object to be transformed into a sequence of bytes that
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
RandomAccessFile • RandomAccessFile encapsulates a random-access file RandomAccessFile(String FileObj, String
RandomAccessFile
• RandomAccessFile encapsulates a random-access file
RandomAccessFile(String FileObj, String access);
RandomAccessFile(String filename, String access)
• access can be r or rw
void seek( long newPos);
Multithreading in Java
Multithreading in Java
Multithreading • A multithreaded program contains two or more parts that can run concurrently. Each
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
Multithreading • The Main thread When a Java program starts up, there is already one
Multithreading
• The 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
Main Thread • Although the main thread is called automatically when program starts, it can
Main Thread
• Although 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
Multithreading • Creating new Threads java.lang.Thread Creating a thread involves two steps: writing the code
Multithreading
• Creating new Threads
java.lang.Thread
Creating 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 thread
Implementing Runnable interface
Extending Thread class
Runnable interface • Need to implement run() public abstract void run() • Instantiate an object
Runnable interface
• Need to implement run()
public abstract void run()
• Instantiate an object of type Thread within that class
Thread defines several constructors
Thread ( Runnable threadOb, String threadName );
• The new thread will not start running until its start()
method isn’t invoked
• In turn, start() executes a call to run().
synchronized void start ( )
Extending Thread class • The extending class must override the run() method, which is the
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
LifeCycle of Thread Ready to run Start Leaving non-runnable scheduling Non-runnable state Entering Running Waiting
LifeCycle of Thread
Ready to run
Start
Leaving non-runnable
scheduling
Non-runnable state
Entering
Running
Waiting
Sleeping
Blocked
non-runnable
Terminates
Dead
States of Java Thread • Not Runnable Still alive, but it is not eligible for
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 complete
2. The thread has been put to sleep for a certain period of time
(using the sleep() method)
3. The wait() method has been called
4. The thread has been suspended (using suspend() method)
States of Java Thread • Dead When a thread terminates, it is DEAD. Threads can
States of Java Thread
Dead
When a thread terminates, it is DEAD. Threads can be DEAD in a
variety of ways which include
1. When its run() method returns
2. When stop() or destroy() method is called
Methods invoked on Threads • interrupt() : interrupts a thread • interrupted() : true if
Methods invoked on Threads
• interrupt() : 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
The Thread Class Methods • getPriority(): Obtains thread priority • start(): To start the operation
The Thread Class Methods
• getPriority(): 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
Methods invoked on Threads • getName(): returns the name of the thread • toString(): returns
Methods invoked on Threads
• getName(): returns the name of the thread
• toString(): 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
Methods invoked on Threads • isAlive(): returns true if start has been called but stop
Methods invoked on Threads
• isAlive(): returns true if start has been called but stop
has not
• setName(): sets the name of the thread
• Yield(): Causes the currently executing thread object
to temporarily pause and allow other threads to
execute
Pre-emptive VS Nonpre-emptive • Pre-emptive : The OS interrupts programs without consulting them • Non
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

With non preemptive scheduling, the scheduler runs the current thread forever, requiring that the thread explicitly to tell it when it is safe to start a different thread.

With preemptive time - slicing, the scheduler runs the current thread until it has used up a certain tiny fraction of a second, & then “preempts” it, suspends it, and resumes another thread for the next tiny fraction of a second

Scheduling & Priority • Thread-scheduling: A mechanism used to determine how runnable threads are allocated
Scheduling & Priority
• Thread-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
Scheduling & Priority • The job of Java scheduler is to keep a highest priority
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
Multithreading – JVM implementation dependent • The early Solaris Java platform runs a thread of
Multithreading – JVM
implementation dependent
• The 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
Multithreading policies • In 32-bit Java implementations for Win ‘95 & Win NT, threads are
Multithreading policies
• In 32-bit Java implementations for Win ‘95 & Win NT,
threads are time sliced
• Each thread is given a limited amount of time to
execute on a processor
• When 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
Multithreading policies • Thus, on Win ‘95 and Win NT, a running thread can be
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
Thread Synchronization • Implemented using synchronized keywords • A method can be synchronized so that
Thread Synchronization
• Implemented using synchronized keywords
• A method can be synchronized so that only one thread
at a time can access the method
• This is possible using a technique called as object
monitor
• Even an object can be synchronized
Inter thread Communication • final void wait(): tells the calling thread to give up the
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
Applets
Applets
What is an applet ? • Applets are small programs stored over web server •
What is an applet ?
• Applets are small programs stored over web server
• Transported over the net
• Installed automatically
• Run as a part of web page
• Need an environment of web browser
Applet basics • Any applet has to inherit from an Applet class • The methods
Applet basics
• Any applet has to inherit from an Applet class
• The methods in the Applet class are
init()
start()
paint(Graphics g)
stop()
destroy()
Applet basics(Contd.) • Adding an applet to html document <html> <applet code=“myapplet.class”
Applet basics(Contd.)
• Adding an applet to html document
<html>
<applet code=“myapplet.class” width=400 height=400>
</applet>
</html>
• Running an Applet
c:\appletviewer ex.html
Applet basics(Contd.) • Applets do not have a main method • Applets must run under
Applet basics(Contd.)
• Applets do not have a main method
• Applets must run under the environment of web
browser
• Applets do not have the right/permission to access the
file system on client machine
• They can not perform any I/O operation
A Simple Applet import java.applet.Applet; import java.awt.*; public class simpleapp extends Applet { public void
A Simple Applet
import 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);
}
}
Other Applet methods • repaint(): to request painting again • update() • showStatus(String) •
Other Applet methods
• repaint(): to request painting again
• update()
• showStatus(String)
• getDocumentBase(): URL of HTML file
• getCodeBase(): URL of applet file
• getParameter(String): to retrieve the parameter value
from HTML document
JAR files < applet archive=”appletbundle.jar” code=”appletname.class” width=w
JAR files
< applet archive=”appletbundle.jar”
code=”appletname.class” width=w
height=h></applet>
• JAR files can be made by using the jar tool
Jar 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
Applets • Applet Life Cycle • Features You add components to a Swing applet's content
Applets
• Applet Life Cycle
• Features
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
Applets (Contd.) • Threads in Applet It's generally considered safe to create and manipulate Swing
Applets (Contd.)
• Threads in Applet
It's generally considered safe to create and manipulate Swing
components directly in the init method
Applets (Contd.) • Embedding an Applet in an HTML Page <applet code="TumbleItem.class"
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">
Applets (Contd.) • Your browser is completely ignoring the • <applet> tag! </applet>
Applets (Contd.)
• Your browser is completely ignoring the
• <applet> tag! </applet>
Demo : Applet Demo HelloSwingApplet.java
Demo : Applet Demo
HelloSwingApplet.java
Java Database Connectivity
Java Database Connectivity
Java Database Connectivity • JavaSoft worked with D/B tool vendors to provide DBMS independent mechanism
Java Database Connectivity
• JavaSoft 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
Java Database Connectivity • A standard to write which takes all app. designs into account
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
What is JDBC • Java Database Connectivity (JDBC) is a standard SQL database access interface,
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
What does JDBC Do ? JDBC makes it possible to do three things: 1) Establish
What does JDBC Do ?
JDBC makes it possible to do three things:
1) Establish a connection with a database
2) Send SQL statements
3) Process the results
Why JDBC ? • Java is a write once, run anywhere language • Java based
Why JDBC ?
• Java is a write once, run anywhere language
• Java based clients are thin client
• Suited for network centric models
• It provide a clean , simple, uniform vendor
independent interface
• JDBC support all the advance features of latest
version ANSI SQL
• JDBC API provides a rich set of methods
Database Connectivity • JDBC • ODBC
Database Connectivity
• JDBC
• ODBC
ODBC Architecture Application Application Application ODBC API ODBC Driver Manager Oracle Service SQL Server DB
ODBC Architecture
Application
Application
Application
ODBC API
ODBC Driver Manager
Oracle
Service
SQL Server
DB 2
Driver
Provider
Driver
Driver
API
SQL * Net
Net Lib
ESQL/DRDA
Oracle
SQL
DB 2
Database
Server
JDBC Architecture JDBC API Application Application Application JDBC Driver Manager Oracle SQL Server JDBC -ODBC
JDBC Architecture
JDBC API
Application
Application
Application
JDBC Driver Manager
Oracle
SQL Server
JDBC -ODBC
Service
Driver
Driver
Driver
Provider
SQL * Net
Net Lib
API
ODBC Driver
Oracle
SQL Server
Database
Sybase
So why not just use ODBC from Java? • ODBC relies on the multiple use
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
Two-tier and Three-tier Models JDBC API supports both two-tier and three-tier models for database access
Two-tier and Three-tier Models
JDBC API supports both two-tier and three-tier models for database
access
JAVA Application
Client
Java Applet or
HTML browser
GUI
JDBC
HTTP,RMI,CORBA
Application
server (JAVA)
Business
Propriety
logic
protocol
Database
JDBC
server
Propriety protocal
DBMS
Two-tier JDBC
Three-tier JDBC
JDBC API - java.sql Driver ResultSet Connection Interfaces in java.sql DatabaseMetaData ResultSetMetaData
JDBC API - java.sql
Driver
ResultSet
Connection
Interfaces
in java.sql
DatabaseMetaData
ResultSetMetaData
Statement
CallableStatement
PreparedStatement
JDBC components Driver Driver Manager Manager Driver Connection PreparedStatement Statement CalllableStatement
JDBC components
Driver Driver Manager Manager
Driver
Connection
PreparedStatement
Statement
CalllableStatement
ResultSet
ResultSet
ResultSet
Database access from Java • Steps Involved Loading the Driver Establishing the connection Passing Sql
Database access from Java
• Steps Involved
Loading the Driver
Establishing the connection
Passing Sql Query
Loading Drivers Class.forName()throws ClassNotFoundException - sun.jdbc.odbc.JdbcOdbcDriver -
Loading Drivers
Class.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);}
Types of Driver • : Jdbc-Odbc Bridge Driver Type I • : Partly Java, partly
Types of Driver
• : Jdbc-Odbc Bridge Driver
Type I
• : Partly Java, partly native code
implementing Vendor specific API
Type II
• : Pure Java driver requesting either to
type I or II as another layer
Type III
• : Pure Java requesting directly to the
database
Type IV
Establishing Connection • A JDBC URL has the following syntax String url= jdbc:<subprotocol>:<subname>
Establishing Connection
• A JDBC URL has the following syntax
String url= jdbc:<subprotocol>:<subname>
// for odbc
String url= “jdbc:odbc:employee” ;
// for jdbc
String url= “jdbc:oracle:thin:@tech:1521:ORCL” ;
Connection con = DriverManager.getConnection
(“url,"myLogin", "myPassword")
Retrieving Data from Table • ResultSet executeQuery( String sql) throws SQLException ResultSet rs =
Retrieving Data from Table
• ResultSet executeQuery( String sql) throws
SQLException
ResultSet 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
Retrieving data from ResultSet String query = " SELECT name, age FROM student "; ResultSet
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
RowSets • A RowSet object contains a set of rows from a result set or
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
Types of RowSets • JdbcRowSet: A connected scrollable ,updatable RowSet • CachedRowset:A disconnected RowSet •
Types of RowSets
• JdbcRowSet: A connected scrollable ,updatable
RowSet
• CachedRowset:A disconnected RowSet
• WebRowSet:A connected RowSet that uses the HTTP
protocol internally to talk to a Java Servlet that
provides data access
Inserting Data into Tables executeUpdate( ) throws SQLException Statement stmt = con.createStatement();
Inserting Data into Tables
executeUpdate( ) throws SQLException
Statement 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' )");
Updating Tables executeUpdate() Statement stmt = con.createStatement(); stmt.executeUpdate( "UPDATE course”+
Updating Tables
executeUpdate()
Statement stmt = con.createStatement();
stmt.executeUpdate( "UPDATE course”+
“SET fees =
fees+2000.00" );
Using PreparedStatement PreparedStatement prep = con.prepareStatement( "UPDATE"+ " course values set fees =
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 ( );
DataSource and Connection Pooling • DataSource:The JDBC 2.0 extension API introduced the concept of data
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
What is a DataSource? • A DataSource object is the representation of a data source
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
What is a DataSource? • Applications access a data source using a connection, and a
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
Comparison between DriverManager and DataSource • While directly creating a connection by calling
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
Comparison between DriverManager and DataSource(Contd.) • It is always better to use a connection pool
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
Using Callable Statement String sql=“execute getEmployes ? ”; CallableStatement call=con.prepareCall(sql);
Using Callable Statement
String 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”);
Using Transactions con.setAutoCommit(boolean commit) con.commit() con.rollback() try { con.setAutoCommit(false); //
Using Transactions
con.setAutoCommit(boolean commit)
con.commit()
con.rollback()
try {
con.setAutoCommit(false);
// perform transactions
con.commit()
con.setAutoCommit(true);
} catch (SQLException e) {
con .rollback() ;}
Java Networking
Java Networking
Course Objectives • Understand basic networking concepts and Java Networking API • Develop simple Java
Course Objectives
• Understand basic networking concepts and Java
Networking API
• Develop simple Java Applications using some commanly
used classes from java.net package in Java SDK

Objective of the session is to understand the new features as brought in by Java 5 as listed below.

J2SE 5.0 Design Themes

Language Changes

Generics & Metadata

Library API Changes

Concurrency utilities

Conclusions and Resources

Networking Basics
Networking Basics
Networking Basics • Computers communicate over internet using protocols … Transmission Control Protocol (TCP)
Networking Basics
• Computers communicate over internet using protocols …
Transmission Control Protocol (TCP)
User Datagram Protocol (UDP)

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

Transmission Control Protocol (TCP) • A connection-based protocol that provides a reliable flow of data
Transmission Control Protocol (TCP)
• A connection-based protocol that provides a reliable
flow of data between two computers
• Guarantees data delivery from one end of the
connection to the other , an error is reported otherwise
• Provides a point-to-point channel for applications that
require reliable communications
• Hypertext Transfer Protocol (HTTP), File Transfer
Protocol (FTP), and Telnet are examples of applications
that require a reliable communication channel

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

User Datagram Protocol (UDP) • Provides for communication that is not guaranteed between two applications
User Datagram Protocol (UDP)
• Provides for communication that is not guaranteed
between two applications on the network
• Is not connection-based like TCP
• Order of delivery of message is not important , and each
message is independent of any other
• An example of a service that doesn't need the guarantee
of a reliable channel is the ping command
• A reliable channel would invalidate this service
altogether since it is to test the communication

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

Understanding Ports • A complete destination network address for connection is made up of
Understanding Ports
• A complete destination network address for connection
is made up of <ipaddress>:<port no.>
• Port number defines a virtual cannel for connecting to
an application on the sever, where as the IP address
merely defines which server to connect
• The computer is identified by its IP address, which IP
uses to deliver data to the right computer on the
network
• Ports are identified by a number, which TCP and UDP
use to deliver the data to the right application

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

Understanding Ports • In connection-based communication such as TCP, a server application binds a socket
Understanding Ports
• In connection-based communication such as TCP, a server
application binds a socket to a specific port number
• This has the effect of registering the server with the system to
receive all data destined for that port
• In datagram-based communication such as UDP, the datagram
packet contains the port number of its destination and UDP routes
the packet to the appropriate application
• The TCP and UDP protocols use ports to map incoming data to a
particular process running on a computer

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

Understanding Ports • Port numbers range from 0 to 65,535 because ports are represented by
Understanding Ports
• 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
• These ports are called well-known ports
• Your applications should not attempt to bind to them

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

Networking in Java
Networking in Java
java.net package for networking • The ‘java.net’ Package defines the java classes for networking •
java.net package for networking
• The ‘java.net’ Package defines the java classes for
networking
• Through these classes in java.net, Java programs can
use TCP or UDP to communicate over the Internet
• The 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

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

java.net.URL The java.net.URL class represents Uniform Resource Locator URL javasoft = new URL
java.net.URL
The java.net.URL class represents Uniform Resource
Locator
URL javasoft = new URL ("http://www.javasoft.com/");
the above line , creates an java object for the url
URL javasoft = new URL ("http://www.javasoft.com/pages/");
URL javasoftGames = new URL (javasoft, "Javasoft.game.html");
create URL object for the page
http://www.javasoft.com/pages/javasoft.game.html

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

java.net.URL • Each of the four URL constructors throws a MalformedURLException if the arguments refer
java.net.URL
• Each of the four URL constructors throws a
MalformedURLException if the arguments refer to a null
or unknown protocol
try { URL myURL = new
.)}
catch (MalformedURLException e) {
handler}
// exception
• URLs are "write-once" objects, once you've created a
URL object, you cannot change any of its attributes
(protocol, host name, filename, or port number)

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

java.net.URL The URL class provides several methods that let you query URL objects • String
java.net.URL
The URL class provides several methods that let you query URL
objects
• String getProtocol() Returns the protocol identifier of the URL
• String getHost() Returns the host name of the URL
• int getPort() Returns the port number of the URL, –1 if not set
• String getRef() Returns the reference of the URL
• String getFile() Returns the filename of the URL
These getXXX methods are used to get information about the URL
regardless of the constructor that you used to create the URL
object

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

java.net.InetAddress • The InetAddress class encapsulates Internet addresses • It supports both numeric IP addresses
java.net.InetAddress
• The InetAddress class encapsulates Internet addresses
• It supports both numeric IP addresses and host names
• The InetAddress class has no public variables or
constructors
• Its methods support for common operations on Internet
addresses
static InetAddress getLocalHost()
static InetAddress getByName(String host)
byte[] getAddress()
String getHostName()
String getHostAddress()

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

Socket • A socket is one endpoint of a two-way communication link between two programs
Socket
• A 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 on the server so that the TCP
layer can identify the application that data is destined to be sent
• The server just waits, listening to the socket for a client to make a
connection request
• The client knows the hostname of the machine on which the server
is running and the port number to which the server is connected
and makes the connection request accordingly

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

Socket 1 2 If connection is accepted, a new socket is created on the client
Socket
1
2
If connection is accepted, a new socket is created on the client
side
• The client can use this socket to communicate with the server
• The client and server can now communicate read/write from
their sockets

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

Socket and ServerSocket class • java.net.Socket class implements client side of the connection •
Socket and ServerSocket class
• java.net.Socket class implements client side of the
connection
• java.net.ServerSocket class implements server side of
connection
• URLs are a relatively high-level connection to the Web
and use sockets as part of the underlying
implementation
• Reading from and writing to a socket --- code example
client,server

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

Socket and ServerSocket class java.net.Socket class methods for read/write InputStream getInputStream() Returns an
Socket and ServerSocket class
java.net.Socket class methods for read/write
InputStream getInputStream()
Returns an input stream for this socket
OutputStream getOutputStream()
Returns an output stream for this socket
java.net.ServerSocket class method to listen to client
Socket accept()
Listens for a connection to be made to this socket and accepts it

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

Datagram • The DatagramPacket and DatagramSocket classes in the java.net package implement system-independent
Datagram
• The DatagramPacket and DatagramSocket classes in the
java.net package implement system-independent
datagram communication using UDP
• These classes help write Java programs that use
datagrams to send and receive packets over the network
• DatagramPackets can be broadcast to multiple
recipients all listening to a MulticastSocket

Programs developed in Procedural languages such as C become too difficult reuse and maintain as the size of the application grows. So, a new approach called “OOP” was introduced, which amongst other things offered the concept of Objects. C++ became one of the most common languages (but not the first language) to offer OOP features, and got popularity. Later, need was felt by Sun Microsystem for a language, that follows the paths of C and C++, but with many more features (discussed on other slides). That gave birth to a language called “Java”

Security in Java 2
Security in Java 2
Course Objectives • Introduce basic security concepts on Java platform
Course Objectives
• Introduce basic security concepts on Java platform

Objective of the session is to understand the new features as brought in by Java 5 as listed below.

J2SE 5.0 Design Themes

Language Changes

Generics & Metadata

Library API Changes

Concurrency utilities

Conclusions and Resources

Java Security • The original security model provided by the Java platform, known as the
Java Security
• The original security model provided by the Java platform,
known as the "sandbox" model.
• JDK 1.1 introduced the concept of a "signed applet“.
• JDK 1.2 introduces a number of improvements over JDK 1.1
All code, regardless of whether it is local or remote, can be
subject to a security policy.
The security policy defines the set of permissions available for
code from various signers or locations and can be configured by
a user or a system administrator .
The runtime system organizes code into individual domains.
JDK 1.2 Security Model
JDK 1.2 Security Model
Cryptography Architecture • The first release of the JDK Security API in JDK 1.1 introduced
Cryptography Architecture
• The first release of the JDK Security API in JDK 1.1 introduced the
Java cryptography architecture (JCA)
• JDK 1.1 Cryptography services
an implementation of one or more digital signature algorithms
message digest algorithms
key-generation algorithms
Cryptography Architecture • Java cryptography architecture (JCA) JDK 1.2 adds five more types of services
Cryptography Architecture
• Java cryptography architecture (JCA)
JDK 1.2 adds five more types of services
Keystore creation and management
Algorithm parameter management
Algorithm parameter generation
Key factory support to convert between different key
representations
Certificate factory support to generate certificates and certificate
revocation lists (CRLs) from their encodings
Cryptography Architecture • JDK 1.2 introduces certificate interfaces and classes for parsing and managing
Cryptography Architecture
• JDK 1.2 introduces certificate interfaces and classes
for parsing and managing certificates
• Certificate Interfaces and Classes
Certificate - is an abstraction for certificates that have
various formats but important common uses
CertificateFactory - is used to generate certificate and
certificate revocation list (CRL) objects from their
encodings
X509Certificate - This abstract class for X.509 certificates
provides a standard way to access all the attributes of an
X.509 certificate.
Cryptography Architecture • Key Management Classes and Interfaces KeyStore class - supplies well-defined interfaces
Cryptography Architecture
• Key Management Classes and Interfaces
KeyStore class - supplies well-defined interfaces to access and
modify the information in a keystore, which is a repository of
keys and certificates
Key specification interfaces - which are used for "transparent"
representations of the key material that constitutes a key
Cryptography- Security Related Tools • JDK 1.2 introduces three new tools: The keytool is used
Cryptography- Security Related Tools
• JDK 1.2 introduces three new tools:
The keytool is used to create pairs of public and private
keys, to import and display certificate chains, to export
certificates, and to generate X.509 v1 self-signed
certificates and certificate requests that can be sent to a
certification authority.
The jarsigner tool signs JAR (Java ARchive format) files and
verifies the authenticity of the signature(s) of signed JAR
files.
The Policy Tool creates and modifies the policy
configuration files that define your installation's security
policy
Applet Restrictions • Most of the browsers installs a security manager, applets typically run under
Applet Restrictions
• Most of the browsers installs a security manager,
applets typically run under the scrutiny of a security
manager
• Applets are not allowed to access resources unless it
is explicitly granted permission to do so by the
security policy in effect.
• To access system resources from an Applet, set up a
Policy File to Grant the Required Permission using
policytool command.
Code and Document Security • If you electronically send someone an important document (or documents),
Code and Document Security
• If you electronically send someone an important
document (or documents), or an applet or application
to run, the recipient needs a way of verifying that the
document or code came from you and was not
modified in transit.
• Digital signatures, certificates, and keystores all help
ensure the security of the files you send.
Code and Document Security (Contd ) • Digital Signatures - The basic idea in the
Code and Document Security (Contd
)
Digital Signatures - The basic idea in the use of digital
signatures is as follows
You "sign" the document or code using one of your private
keys, which you can generate by using keytool or security API
methods. That is, you generate a digital signature for the
document or code, using the jarsigner tool or API methods.
You send to the other person, the "receiver,"
You also supply the receiver with the public key corresponding
to the private key used to generate the signature
The receiver uses the public key to verify the authenticity of
the signature and the integrity of the document/code.
Code and Document Security (Contd ) • A receiver needs to ensure that the public
Code and Document Security (Contd )
• A receiver needs to ensure that the public key itself is
authentic before reliably using it to check the
signature's authenticity
• It is more typical to supply a certificate containing the
public key rather than just the public key itself
Code and Document Security (Contd ) • Certificates -A certificate contains A public key The
Code and Document Security (Contd )
• Certificates -A certificate contains
A public key
The "distinguished-name" information of the entity (person,
company, or so on) whose certificate it is
A digital signature. A certificate is signed by one entity, the
issuer, to vouch for the fact that the enclosed public key is the
actual public key of another entity, the owner.
The distinguished-name information for the signer (issuer).
• Keystores - Private keys and their associated public key
certificates are stored in password-protected databases called
keystores
Thank you
Thank you