Programming in Java
Programming in Java
Books
1. Java 2 - The Complete Reference, Herbert Schildt (Seventh Edition).
2. The Java Programming Language, Ken Arnold, James Gosling & David
Holmes (Third Edition).
3. Core Java Volume I – Fundamentals, Eigth Edition, C S Horstmann & G.
Cornell
4. Java.sun.com/docs/books/tutorial, javaworld.com
-------------------------------------------------------------------------------------------------------
JAVA
Just Another Vague Acronym
A language is called research language if it has untested features (i.e. features that had
not been tested in its predecessor languages)
A language is called production language if it does not have any untested features.
Because of all these reasons, it is easier to write bug free code and
this reduces the program development time.
(iv) Java is architecture-neutral. Even if you upgrade the operating system and hardware,
the Java program written in the older operating system and previous hardware will continue
to run. This scenario is known as `Write Once Run Everywhere`.
Uses of Java
Simple – Java has eliminated many rarely used, poorly understood and confusing features of C++. It is easy
to achieve fluency in Java.
Architecture-neutral – Java program written for a specific operating system and hardware can run in other
operating system and hardware. This is necessary because Java codes are downloaded from the Internet to
run on a variety of CPU and operating system.
Portable – All primitive types take the same amount of storage on all architectures.
Robust – Java provides early error checking facility and so it is easy to develop bug-free code.
Java Buzzwords
Network-savvy – Java has support for TCP/IP protocols and remote method invocation (RMI).
Session management – There are API classes for session management and cookies.
High performance – In C++, you include files (header files e.g.) for using built-in functions and
after compilation, these functions find their place in the compiled code even if a few of them
only are actually used in the source code. This is not so with Java. Consequently, the size of
the java compiled code is small and so the space requirement and time of execution is low and
hence the performance is high.
Interpreted – Java compiler converts the Java source code into bytecodes and these are
interpreted by the Java interpreter also known as the Java Virtual Machine (JVM). The JVM
differs from architecture to architecture.
Dynamic – A Java program written using API classes need not be recompiled when the API
classes are modified and/or upgraded.
Coding Style
Java developers follow coding style in writing the name of an identifier depending upon
what it stands for.
The classes and interfaces are named using words in title case (e.g. Employee, String,
Thread, Runnable). If a class name need to consist of more than a single word then each
word is written in title case and words are concatenated without using underscore (e.g.
FinanceDepartment).
The method and variable names are written in lower case. If you need more than a single
word to construct such a name then the first word is written in title case and the rest of
the words are written in lower case and the words are concatenated (dailyTemperature).
The name of the constants are written in uppercase and if such a name need more than
one word then the words are joined using underscore (e.g.
GRAVITATIONAL_CONSTANT).
Basic (primitive) data types
char (unsigned and 16 bits),
boolean having only two possible values true and false (unlike zero and non-zero) and it
requires no storage.
• The true and false are not converted into numeric representation.
• The true and false are known as boolean literals
• Can be assigned to boolean variables only
• Can be used in expressions with boolean operators.
Arithmetic operators
Arithmetic operators can be applied only on numeric types and character type
not on boolean type
Bitwise operators
Perform bit operations on its operands and can be applied on long, int, short,
char and byte types only.
Operators
~ (negation), & (bitwise and), | (bitwise or), ^ (exclusive or), >>> (unsigned right
shift), << (left shift), >> (right shift), &= (bitwise and followed by assignment), ~= (bitwise
(bitwise right shift followed by assignment), >>>= (bitwise unsigned right shift
Relational operators
== (for testing equality of numbers or characters or object references returned
by an expression), <= (less than or equal to), >= (greater than or equal to), !=(
not equal to), < (less than), >(greater than)
N.B. In short circuit or if the first expression is true than the second expression
will not be evaluated. In short circuit and if the first expression is false then
the second expression will not be evaluated.
Operator precedence
() []
++ -- ~ !
* / %
+ -
== !=
&
&&
||
?:
= operator=
Code example involving >>>
Type casting
The automatic type conversion takes place in such a way that data
widening is permitted but shortening is not.
char
↓
byte → short → int → long (data widening)
float → double
• Keywords
Keywords
type[ ] arrayname;
Array is not created, only a reference is declared and it points to nothing (null).
The array is created i.e. the memory is allocated for the array and all the
elements of the array are initialized by their default values.
• You can`t have negative index, or an index out of the bound of the
array. Java provides bound checking of arrays.
Example code:
int sum(int[ ] a) {
int result = 0;
for(int i =0; i < a.length; i++) result += a[i];
return result;
}
2D arrays
Java arrays, even of basic types, are objects. (Array names are
references)
The array index may have type short, int, byte, char, but it cannot be
long, float, double or boolean
return
for-each version of for loop
Code example:
first: for(,,,) { //label is defined and can be referred to
//inside this block
//code
if( condition) break first; // label is used
//code
}
Labeled break
You cannot break to a label which is not defined for the enclosing
block.
Labeled continue
Code example:
You cannot continue to a label which is not defined for the enclosing
block.
Usage of labeled break & labeled continue
• Static fields are called class fields because they belong to the class
and do not belong to the object.
• There exists only one (the original) copy of a class field. Each object
of a class has a copy of each of its instance field, but a class field is
shared by all the objects of a class.
• The class fields receive their share of memory when the class file is
loaded and instance fields receive their share of memory when an
object is created.
• Every Java source file is converted into a class file (.class file) by
the Java compiler
Classes
• The type and number of arguments of the function are considered for
overload resolution. Return type is not used for overload resolution
Classes
• Methods can be static or non-static.
• A static method can access only static fields, call only other static
methods and does not have `this` reference.
• Though field of class (if it is not final) has default value but local variables
do not have default values and they must be initialized at the point of
declaration.
The `this` reference
• The `this` reference refers to the current object (invoking object i.e.
object currently in use).
• Members of `this` are accessed by . (the period operator). i.e.
this.member
Example code
class X {
int m, n;
X(int m, int n) {
this.m = m;
this.n = n;
}
}
???
What operators are not found in Java but
found in C++???
::
->
What is the most unfortunate construct of
programming languages??
The `this` reference
Example code:
class X {
int m, n;
X(int m) {
this.m = m;
}
X(int m, int n) {
this(m); // must be the first non-comment statement in this definition.
this.n = n;
}
}
Object creation
X x1 = new X ( );
X x2 = new X(4);
X x3 = new X(10,20);
X x4;
Object not yet created, only a reference has been declared
x4 = x3;
No new object has been created, x4 points to the same object as x3
points to. If you test the return value of x3 == x4 you will get true
because the object pointed to by x3 and x4 are the same.
All objects are created on the heap at the run time. There is no compile
time object
Objects equality
• Two objects are said to be equal if they have the same state.
e.g. X (X ob) {
m = ob.m; n = ob.n;
}
X x1 = new X(5, 10); X x2 = new X(x1);
class HelloWorld {
public static void main(String[ ] args) {
System.out.println(“Welcome to the world of Computing”);
System.out.println(“Computing powered by Java”);
double x = 27;
System.out.print("The value of x is " + x);
} //main
} // HelloWorld
The name of the class file is exactly the same as the name of class
in the source code (no change of case).
class BoxTest {
public static void main(String[ ] args) {
Box b1 = new Box (12,14,17);
System.out.println(b1.volume( ));
Box b2 = new Box(b1);
Box b3 = b2;
System.out.println(b1.equals(b2));
System.out.println(b1 == b2);
}
}//BoxTest
Some observations
After compilation of this code two class files are created by the java
compiler,
Box.class & BoxTest.class.
If you incorporate a main method inside the Box class you can execute
it using the command java Box.
Comments
How many main methods you may have in a Java source file?
You may have one main method in each of the classes that the
source file has.
This is useful for unit testing (Developing and testing each class
separately).
Code Example
class CommandLine {
public static void main(String[ ] args) {
for(int i=0; i<args.length; i++)
System.out.println(args[i]);
}
}
Remarks
In C++ you may have variables and methods outside class, but in
Java everything & everything must be inside a class.
You may write a C++ program without using classes, but you can`t
write a Java program without using classes.
Creating an array of objects
class BoxTest1 {
public static void main(String[ ] args) {
Box [ ] barray = new Box[10] ;
for(int i=0; i<5; i++) barray[i] = new Box( );
for(int i=5; i<10; i++) barray[i] = new Box(10,30,50);
}
}
• You may use `this` reference, you may use `super` inside
initialization block but you cannot use return statement.
class Employee {
int id;
e.g. static {
//code;
}
class X {
static {
System.out.println(“run”);
}
}
Answer
When you try to execute it, it displays the string “run” and will terminate
with an error message saying that `main is not found`.
class X {
static {
System.out.println(“run”);
System.exit(0);
}
}
Code example using initialization block
& static initialization block
class Employee {
int id;
static int nextId;
static { // this is a static IB
nextId = (int) (Math.random( )*1000);
}
{ // this is an IB
id = nextId++;
}
}
Generating prime numbers at the load time
class Primes {
static int [ ] knownPrimes = new int[10];
static {
knownPrimes[0] = 2;
for(int i=1; i<10; i++) knownPrime[i] = nextPrime( );
}
// code to define the nextPrime() method
}
Abstract class
An incomplete class is called an abstract class.
Incomplete class
A class is called incomplete if its specification either has not been
implemented completely or implementation is unknown.
Concrete class
A class that is complete is called a concrete class.
Abstract classes
e.g.
abstract class X {
//code
}
Abstract classes
• If you do not declare a class abstract then you must give the
definition of all of its methods. This does not make the methods
inline.
• A class which is not declared abstract cannot have abstract
methods.
Abstract methods
Partial syntax:
interface InterfaceName {
//field declarations
//method declarations
//classes
//interfaces
}
Interfaces
Example of an interface
interface I {
int m = 10;
double x = 3.14;
}
implements
Interfaces
A partial syntax for implementing an interface:
interface Shape {
double area( );
}
e.g.
class Rectangle implements Shape {
double d1, d2;
Rectangle( ) { }
Rectangle (double d1, double d2) {
this.d1 = d1; this.d2 = d2;
}
public double area ( ) {
return d1*d2;
}
double perimeter( ) {
return d1*d2;
}
}
Interface reference can receive class object but
converse is not true
class ShapeTest {
public static void main(String[ ] args) {
Shape sh; //declare a reference of Shape. But cannot create object
Triangle ob = new Triangle(3,4,5);
Rectangle ob1 = new Rectangle (10,20);
sh = ob; //interface reference can receive object
System.out.println(sh.area( ));//calls area()@Triangle
sh = ob1;
System.out.print(sh.area( )); //calls area()@Rectangle
//but objects cannot receive interface reference
ob = sh; //compile time error
ob1 = sh; //compile time error
ob = (Triangle)sh; ob1 = (Rectangle)sh;
}
}
Interfaces
e.g.
abstract class Rectangle1 implements Shape {
double d1, d2;
Rectangle( ) { }
Rectangle (double d1, double d2) {
this.d1 = d1; this.d2 = d2;
}
}
An interface with data only
interface DataOnly {
int YES = 1; int NO = 0;
double DONT_KNOW = 0.5;
}
class Test {
public static void main(String[ ] args) {
System.out.println(DataOnly.YES);
}
}
X x;
Y y = new Y( );
JAVA QUIZ I
Scheduled on Jan. 22, 2010
(This FRIDAY)
PORTIONS
Up to Dynamic method dispatch
Object class
Constructor
public Object( )
Object class
Methods
public boolean equals (Object ob)
To test whether two objects have the same state, override this method.
Object class
public String toString( )
Converts the current (invoking) object into its String representation.
The print and println methods call the toString( ) method to convert its
argument into string before sending it to the console.
e.g.
class X /* class X extends Object */ {
public String toString( ) {
return “Inside toString method”;
}
}
class Y {
public static void main(String[ ] args) {
X x = new X( );
System.out.println(x) //output: Inside toString method
}
}
Exercise :Do not override tooString. Create an object of Object class and pass it to println method
Exercise
Do not override toString. Create an
object of Object class and pass it to
println method
Object class
class ArrayTest {
public static void main(String[ ] args) {
int [ ] m = new int[10];
System.out.println(m.getClass( )); //op: class [I
}
}
Exercise:Try with arrays of other type
Object class
protected Object clone( ) throws ClassNotSupportedException.
It makes an exact copy of an object.
Object class has only declared methods and it has no inherited methods because it
is not inherited from any other class and so it is called the cosmic super class.
extends & implements
e.g.
class Y extends X implements I1[,I2,I3,…] {
body of the class
}
Extending interfaces
interface I1 {
int f(int n);
double g(double d);
}
interface I3 extends I1 {
// void f(int n); compile time error
int f(int n);
//void g(double d); compile time error
double g(double d);
}
Extending interfaces
interface A {
int f( );
String g ( );
}
interface C {
void f( );
void g( );
}
interface A {
int f( );
String g ( );
}
interface D extends A {
int f ( ); //overriding
String g ( ); //overriding
}
Extending interfaces
interface A {
int f( );
String g ( );
}
interface D extends A {
int f (); //overriding
String g (); //overriding
}
class X implements D {
public int f( ) { return 0;}
public String g() { return "" ; }
}
Will it compile??
YES
Inheriting constants
interface I1 {
double PI = 3.14;
}
interface I2 extends I1 {
double SPEED_OF_LIGHT = 3e10;
}
Inheriting and hiding constants
interface A {
int m = 1;
double x = 3.14;
}
interface B extends A {
int m = 10; //m@B. This value of m hides the value m = 1
int n = 20 + A.m; // accessing m@A
}
Number of class files
• For each class declared in the source code a class file is created.
• You may have any number of levels of nesting (i.e. deep nesting is
possible) but nesting up to level two is recommended.
• A nested class can extend some other class and can itself be
extended.
Nested classes
class X { //A top level class - X is the enclosing (outer) class of Y and Z
//code
//code
//code
}// Z
//code
}//Y
//code
}//X
Nested classes
• Inner classes cannot have static members. They cannot have final
fields.
• From the code of outer class direct access to the members of the
inner class is not possible, but it is possible to do so using an object
of the inner class.
Features
A local inner class
is a non-static nested class,
is completely inaccessible outside the block it is declared,
is not a member of the enclosing class and so it cannot be declared public,
private or protected.
The only class modifier that can be used with a local inner class is final.
}
int f(double d) {
int n = 6; double x = 4.5;
class Y { //a local inner class
//body of Y
void display() {
System.out.println(m); show( ); //you can directly access members of X
// System.out.println(x); -- error x is not final
}
}// local inner class Y ends here
return 0;
}//f
}//X
If d,n, x are declared final then they can be accessed from within Y.
After compilation, the class files that are created are
X.class &
X$1Y.class
Anonymous inner class
Definition
An Anonymous Inner class (AIC) is an inner class that does not have a
name.
Feature
Since it does not have a name so it cannot have a constructor.
Usage
If you want to create object of a class only once during an execution
of a program then use AIC.
The AICs are extensively used in event handling.
Anonymous inner class (an example)
class X {
X(int n, double d) {
this.n = n; this.d = d;
}
X( ) { }
}
class Y {
//X x = new X( );
X x = new X( ) { //AIC starts here
//code of AIC
}/*AIC ends here*/;
X x = new X( 10, 9.8) { //AIC starts here
//code of AIC
}/*AIC ends here*/;
//other code of Y
}//Y
The class files created after compilation of this code are
X.class, Y.class,
Y$1.class & Y$2.class.
Anonymous inner class
The numbers of lines of code within an AIC should not be too many
(i.e. at the most six statements are recommended). If there are too
many statements, readability becomes a problem.
Anonymous Inner class (another example)
class A {
Object ob = new Object( ) { //AIC starts
//body of AIC
}/* AIC ends here */ ;
//other code
}
}
class Y {
I i = new I( ) { //AIC starts here
//code of AIC
}/*AIC ends here*/;
}//Y
The class files created after compilation are
I.class, Y.class &
Y$1.class.
Modifiers of AIC
None
Modifier strictfp
The only modifiers that can be used for a top level class are public,
final/abstract and strictfp.
The class modifiers can be used in any order but the above order is
recommended.
Modifiers of top-level interface
Constructors
• public String ( ) -- creates an empty string.
Constructors
• public String(char[ ] value, int offset, int count)
Constructs a new String that contains characters, picking up count number
of characters from the position offset of the array value.
e.g.
byte [ ] bytes = {67, 68, 69, 70};
String str = new String(bytes, 0, 4, "ASCII");
System.out.println(str + " " + str.length( )); //output: ABCD 4
String class
• public String(StringBuffer buffer)
Constructs a new string that contains the sequence of characters
currently contained in the string buffer argument.
String class
Methods
• public int length()
Returns the length of this string. The length is equal to the number of
16-bit Unicode characters in the string.
Up to String class
StringBuffer class
Constructors
public StringBuffer( )
Constructs a string buffer with no characters in it and an initial
capacity of 16 characters.
StringBuffer class
public StringBuffer(int capacity)
Constructs a string buffer with no characters in it and an initial
capacity specified by the capacity argument.
If the capacity argument is less than 0,
NegativeArraySizeException is thrown.
public StringBuffer(String str)
Constructs a string buffer so that it represents the same sequence
of characters as the string argument. The initial capacity of the
string buffer is
length of the string argument + 16.
If you pass null as argument, NullPointerException is thrown
StringBuffer class
Methods
sb.ensureCapacity(20);
System.out.print(sb.capacity( )); //output capacity = max(20, 2*16 + 2);
StringBuffer class
A compilation unit may have at the most one top-level public class
or interface. You may have other classes and interfaces in the
same compilation unit, but they cannot be declared public. These
other classes and interfaces present in the compilation unit act as
helper classes and interfaces.
Definition of package
A package is a software unit that can be distributed independently
and be combined with other packages to form application.
Members
Classes, interfaces, other packages and resource files (e.g. image,
audio, video).
package
package pkg1;
public class Example {
}
//other classes and interfaces
You may also compile this file from some other directory specifying
the full path e:\java\08mca\pkg1\Example.java
At present the only source file which is inside the package pkg1 is
Example.java.
Create another Java source file say, Example1.java with the package
statement package pkg1; as the first non-comment statement of the
file and store it inside the sub directory …\pkg1
and compile.
In this way you may add more classes and interfaces to the package
pkg1.
Base directory & class path
You may have any number of base directories in your file system.
Telling the run time environment where the class files are stored, is
referred to as setting the classpath.
How to set classpath?
Setting the classpath depends on the environment you are working
in.
On UNIX/Linux,
if you use C shell, add the following line to the .cshrc file:
setenv CLASSPATH name of base dirs separated by ;
If you use BASH shell, add the following line to the .bashrc file or
in the bash-profile file:
export CLASSPATH = name of base dirs separated by ;
Base directory & class path
Some of the library classes declared inside the java.util package are
Date, Calendar, GregorianCalendar
say, X, Y, Z, I1, I2 and if you use the import statement import pkg1.*;
and use only the class X inside the source file then the class file of the
i.e. you may use wild card (*) for members of a package, but not for the
package name.
import statement
You can import types (classes and interfaces) but you cannot import
objects.
But you cannot access the Date class without qualifying it by its
package name
i.e. you can write either java.util.Date or java.sql.Date
import statement
import java.util.*;
import java.sql.Date;
OR
import java.util.Date;
import java.sql.*;
import statement
#include incorporates the entire content of the header file into the
compiled code.
This is the reason why the size of a Java compiled code is smaller
than that of C++ code.
}
public double h( ) { //visible everywhere
}
}//X
Access protection (Example)
package pkg2;
import pkg1.*;
public class Y {
//can access public members of X
//cannot access protected members of X, members without modifier
// & the private members
}
class Z extends X {
//can access public and protected members of X
//cannot access members without modifier & private members of X
}
Class modifier access
private No modifier protected public
The members of a Java class are by default not private. The default
scope is package.
i.e. by default (in absence of any access modifier), the members of
a Java class are visible everywhere inside the package the class is
declared.
Exception handling
Object
Throwable
Error Exception
IOException RuntimeExeption
Exception class hierarchy
Error
NoClassDefFoundError -- OutOfMemoryError
--StackOverflowError
--UnknownError
--InternalError
Exception class hierarchy
RuntimeException
---- StringIndexOutOfBoundsException
---- ArrayIndexOutOfBoundsException
---- IllegalArgumentException
---- IllegalThreadStateException
---- NumberFormatException
---- ConcurrentThreadException
Exception class hierarchy
IOException
---- InterruptedException
---- FileNotFoundException
---- EOFException
Exception handling
Exception handling is performed using the keywords try, catch, finally, throw
and throws.
Format of try-catch-finally:
try {
//code to be monitored for exception
}catch(ExceptionType1 ob) {
// code to be executed when exception occurs (known as exception handler)
}catch(ExceptionType2 ob) {
// code to be executed when exception occurs (known as exception handler)
}
.
.
.
finally{
//code that must be executed before try block ends
}
Exception handling
If there is no catch block then there has to be a finally block
It will compile
On execution you will find the following output:
hello there
Exception in thread “main” java.lang.ArithmeticException: / by zero
at ExceptionTest.main (ExceptionTest.java:5)
The string in italic is called stack trace
Exception handling
If exception is handled then it is possible to recover from error and resume
execution.
Output:
hello there
Exception in thread “main” java.lang.ArithmeticException: / by zero
at ExceptionTest.main (ExceptionTest.java:5)
hello
Exception handling
Reason
Super class reference can receive sub class object. The
ArithmeticException and ArrayIndexOutOfBoundsException being a
subclass of Exception, all exception objects will be caught at the catch
block that handles Exception object and control never reaches the
ArithmeticException block leading to unreachable code which is a
compile time error.
}catch(ExceptionType1 ob) {
//exception handler
} catch(ExceptionType2 ob) {
//exception handler
}//inner try ends
} catch(ExceptionType3 ob) {
//exception handler
} catch(ExceptionType4 ob) {
//exception handler
}//outer try ends
Throw statement
The throw statement has the following form:
throw expression;
Constructor
NullPointerException()
Constructs a NullPointerException with no detail message.
NullPointerException(String s)
Constructs a NullPointerException with the specified detail
message.
Announcement
Quiz II
March 8, 2010 (Monday)
Portions
Nested classes, String class, StringBuffer
class, interfaces, packages, exception
handling.
Exception handling
throws clause
class ThrowsTest1 {
static void f( ) {
//code
throw new RuntimeException( );
}//f
public static void main(String[ ] args) {
try {
f( );
}catch(RuntimeException e) {
e.printStackTrace( );
}
System.out.println("hello");
}//main
} //ThrowsTest1
Exception handling
class ThrowsTest {
static void f( ) {
//code
try {
throw new Exception( );
}catch(Exception e) {
e.printStackTrace( );
}
}
public static void main(String[ ] args) {
try {
f( );
}catch(Exception e) {
e.printStackTrace( );
}
System.out.println("hello");
}
}
Exception handling
class ThrowsTest {
static void f( ) throws Exception {
//code
throw new Exception( );
}
public static void main(String[ ] args) {
try {
f( );
}catch(Exception e) {
e.printStackTrace( );
}
System.out.println("hello");
}
}
Exception handling
class X {
static void f( ) throws IllegalAccessException {
//code
throw new IllegalAccessException( );
}
public static void main(String[ ] args) {
try {
f( );
}catch(IllegalAccessException e) {
e.printStackTrace( );
}
}
}
Exception handling
Chained exception
If one exception is the cause of the other then they are said to form a
chain of exceptions.
Throwable class
Constructors
public Throwable( )
public Throwable(String msg)
public Throwable(Throwable cause)
public Throwable(String msg, Throwable cause)
Exception handling
Some Methods
Example code
When multiple threads share the same CPU among themselves they
are said to execute concurrently (i.e. in an inter leaving fashion).
Multithreaded programming
Thread models
Cooperative thread model
A running thread relinquishes the CPU. It is under the control of the
JVM (and hence under the control of the Java application
developer).
Running Terminated
Multithreaded programming
If you implement Runnable interface then you must give the definition
of the run( ) method of Runnable interface.
The definition of the run method describes the work done by the thread.
Multithreaded programming
Constructors
public Thread ( )
public Thread(String name)
public Thread(Runnable work)
public Thread(Runnable work, String name)
public Thread(ThreadGroup group, Runnable work)
public Thread(ThreadGroup group, String name)
public Thread(ThreadGroup group, Runnable work, String name)
Multithreaded programming
A thread with higher priority executes more often than a thread with lower
priority.
Changing the priority and name of a thread is called configuring the thread.
Multithreaded programming
Static methods
public static Thread currentThread( ) returns a reference to the running
thread. e.g. Thread.currentThread( )
public static void yield( ) Causes the currently executing thread object
to temporarily pause and allow other threads to execute.
public static void sleep (long ms, int ns) throws InterruptedException
Final methods
public final boolean isAlive( ) returns true if this thread has not been
terminated.
public final void setName(String name) alters the name of this thread
object.
public final String getName( ) returns the name of this thread object.
Multithreaded programming
Final methods
}
}
Multithreaded programming
Extending Thread class
public class Thread11 extends Thread {
private String word;
private int delay;
public Thread11(String str, int d) {
word = str; delay = d;
}
public void run( ) {
for(; ;) {
System.out.print(word+ " ");
try {
Thread.sleep(delay);
}catch(InterruptedException e) {
}
}//for
}//run
public static void main(String[ ] args) {
Thread11 t1 = new Thread11("Java", 50);
Thread11 t2 = new Thread11("Programming", 50)
t1.start( ); t2.start( )
/* new Thread11("Java", 50).start( );
new Thread11(“Programming", 50).start( ); */
}
}
Multithreaded programming
Using Runnable interface
}
}
}
public static void main(String[ ] agrs) {
new Thread13("Java", 50);
new Thread13("Programming", 100);
}
}
Multithreaded programming
using start method inside constructor
public class Thread13 extends Thread {
private String word;
private int delay;
public Thread13(String str, int d) {
word = str; delay = d;
start();
}
public void run( ) {
for(; ;) {
System.out.print(word+ " ");
try {
Thread.sleep(delay);
}catch(InterruptedException e) {
}
}
}
Multithreaded programming
Thread synchronization
synchronized method
synchronized(this) {
//doing something on the current object one at a time by different
//threads
}
Multithreaded programming
Synchronized method and synchronized block are called
synchronized codes.
Associated with every object (e.g. bank account object) there exists
a lock. In order to execute synchronized code on the object, a thread
must acquire the lock of the object. Before entering into
synchronized code a thread requests the OS for the lock. If the lock
of the object is already held by some other thread then this thread
has to wait. If the lock is available then the thread acquires the lock,
enters into the synchronized code, and after it returns from the
synchronized code it releases the lock.
Banking example
class BankAccount {
private double balance;
public BankAccount(double d) { balance = d; }
public synchronized void setBalance(double d) {
balance = balance + d;
}
public synchronized void getBalance( ) {
return balance;
}
}
Multithreaded programming
public class Teller implements Runnable {
private BankAccount ba; private double d;
public Teller(BankAccount ba, double d) {
this.ba = ba; this.d = d;
}
public void run( ) {
ba.setBalance(d);
}
public static void main(String[ ] agrs) {
BankAccount ba = new BankAccount(1000);
Thread t1 = new Thread (new Teller(ba, 2000);
Thread t2 = new Thread (new Teller(ba, 3000);
t1.start( ); t2.start( );
try {
t1.join( ); t2.join( );
}catch(InterruptedException e) { }
System.out.println(ba.getBalance( )); // o/p should be 6000
}//main
}Teller
Portions
CAT II
Interfaces
StringBuffer class
Package
Access protection
Exception handling
Multithreaded programming (up to thread
synchronization)
Multithreaded programming
These are the declared methods of the Object class, inherited by the
Thread class.
These methods are useful in establishing communication
among threads (called inter-thread communication).
Inter-thread communication
Can be achieved using wait, notify and notifyAll methods.
Producer-consumer problem is an example of inter-thread
communication where producer and consumer are threads.
Producer produces items and keep the items in a buffer whereas
the consumer picks up the items one at a time from the buffer.
As long as the buffer is full the producer thread cannot produce
items (i.e. it waits indefinitely until the buffer is empty)
The consumer too waits until there is at least one item in the buffer.
For simplicity we assume that the buffer size is one i.e. the producer
has to wait after producing an item until the consumer picks up the
item.
Multithreaded programming
How will the consumer know that the item has been produced?
After producing the item the producer has to wait until the item is
picked
up (assuming that the buffer size is one).
How will the producer know that the item has been picked up?
After picking up the item the consumer issues notification using the
notify method.
Implementation of producer-consumer problem (buffer size = 1)
class Data {
private int data; //this can be an array when the buffer size > 1
private boolean found = false; //no item found in the buffer
synchronized int pickup( ) { //executed by the consumer thread
while(!found) {
try {
wait( );
}catch(InterruptedException e) { }
}//while
found = false;
notify( );
return data;
}
Implementation of producer-consumer problem (buffer size = 1)
}//drop
}//Data
Implementation of producer-consumer problem (buffer size = 1)
class InterThreadCommunication {
public static void main(String [ ] args) {
Data dt = new Data( );
new Thread(new Producer(dt)).start( );
new Thread(new Consumer(dt)).start( );
}
}
Deadlock
Code example
class A {
synchronized void h( ) { //h( ) @ A
//code
}
synchronized void f(B b) {
try {
Thread.sleep(1000);
}catch(InterruptedException e) { }
b.h( ); //h( ) @ B
}
}
Deadlock
class B {
synchronized void h( ) { //h( ) @ B
//code
}
synchronized void g(A a) {
try {
Thread.sleep(1000);
}catch(InterruptedException e) { }
a.h( ); //h( ) @A
}
}//B
Deadlock
class X implements Runnable {
A a = new A( );
B b = new B( );
Thread t;
X(){
t = new Thread(this);
t.start( );
a.f(b);
}
public void run( ) {
b.g(a);
}
public static void main(String[ ] args) {
new X( );
}
}
Deadlock
Trace
1. Main thread comes into existence and calls X( ) using new X( );
2. Thread t (a child thread of the main thread) is created using t =
new Thread(this) and started using t.start( )
3. start calls run method which in turn execute (child thread is
executing) b.f(a). Since f is a synchronized method, the lock of b
is required and so it is allocated to the child thread t.
4. After entering into the method f, since it contains sleep so the
child thread t is suspended and CPU is switched to the main
thread.
5. When the main thread was suspended last it had already
executed t.start( ) and so now it executes a.g(b).
Deadlock
So the main thread and the child thread are in a deadlock situation.
Modifier ‘volatile`
When two or more threads share the same instance field, a private
copy of the field is given to each thread and the threads modify this
private copy.
Apart from these private copies there is also maintained a master copy.
If you want to keep the values of the master copy always updated
whenever the private copy is updated then use the modifier volatile.
When bits are interpreted as bytes the stream is called byte stream.
Every input stream has a source and it reads data from the source.
Every output stream has a destination and it writes data to the destination
Stream classes
Methods
public abstract int read( ) throws IOException
Reads the next byte of data from this input stream.
The value of byte is returned as an integer in the range 0 to 255.
If no byte is available because the end of the stream has been
reached, the value -1 is returned.
The method blocks until input data is available, the end of the
stream is detected, or an exception is thrown.
A subclass must provide an implementation of this method.
InputStream class
Methods
public abstract void write(int b) throws IOException
Writes the specified byte to this output stream. The byte to be
written is the eight low-order bits of the argument b.
Methods
public int read( ) throws IOException
Read a single character and returns it as an integer between 0 to
65535 and returns -1 when there is no character to read.
This method will block until a character is available, an I/O error
occurs, or the end of the stream is reached.
Reader class
Methods
public void write(int c) throws IOException
Write a single character.
The character to be written is contained in the 16 low-order bits of
the given integer value; the 16 high-order bits are ignored.
Inside the System class there are declared public static final stream
objects called
in, out and err
in is of type InputSteam
out and err are of type PrintStream.
If you want to perform I/O on byte data (e.g. image, audio, video), use
byte stream class.
If you want to perform I/O on character data (text based), use character
stream class.
InputStreamReader class
Constructors
public InputStreamReader(InputStream in)
Creates an InputStreamReader that uses the default charset.
Methods
Constructor
public PrintStream(OutputStream out)
Create a new print stream. This stream will not flush automatically.
public PrintStream(OutputStream out, boolean autoFlush)
Create a new print stream.
Parameters:
out - The output stream to which values and objects will be printed
autoFlush - A boolean; if true, the output buffer will be flushed
whenever a byte array is written, one of the println methods is
invoked, or a newline character or byte ('\n') is written
PrintStream class
Methods
public void flush( ) Flush the stream.
public void close( ) Close the stream.
public void write(int b) Write the specified byte to this stream.
public void write(byte[ ] buf, int off, int len)
public void print(boolean b) Print a boolean value.
public void print(char c) Print a character.
PrintStream class
public void println(boolean x) Print a boolean and then terminate the line.
public void println(char x) Print a character and then terminate the line.
public void println(int x) Print an integer and then terminate the line.
public void println(long x) Print a long and then terminate the line.
public void println(float x) Print a float and then terminate the line.
public void println(double x) Print a double and then terminate the line.
public void println(char[ ] x) Print an array of characters and then terminate
the line.
public void println(String x) Print a String and then terminate the line.
Constructors
PrintWriter(File file)
PrintWriter(File file, String csn)
PrintWriter(OutputStream out)
PrintWriter(OutputStream out, boolean autoFlush)
PrintWriter(String fileName)
PrintWriter(String fileName, String csn)
PrintWriter(Writer out)
PrintWriter(Writer out, boolean autoFlush)
Methods
Overloaded print and println similar to PrintStream class, printf method
and append method
BufferedWriter class
Constructor
BufferedWriter(Writer out)
BufferedWriter(Writer out, int sz)
BufferedWriter class
e.g.
Writer out = new BufferedWriter(new OutputStreamWriter(System.out));
OutputStreamWriter class
Constructors
OutputStreamWriter(OutputStream out)
OutputStreamWriter(OutputStream out, Charset cs)
OutputStreamWriter(OutputStream out, CharsetEncoder enc)
OutputStreamWriter(OutputStream out, String charsetName)
OutputStreamWriter class
Methods
void close()
void flush()
String getEncoding()
void write(char[ ] cbuf, int off, int len)
void write(int c)
void write(String str, int off, int len)
ByteArrayInputStream class
ByteArrayInputStream(byte[ ] buf)
ByteArrayInputStream(byte[] buf, int offset, int length)
CharArrayReader(char[ ] buf)
CharArrayReader(char[ ] buf, int offset, int length)
CharArrayWriter( )
CharArrayWriter(int initialSize)
FileOutputStream(File file)
FileOutputStream(File file, boolean append)
FileOutputStream(String name)
FileOutputStream(String name, boolean append)
If you want read characters from a file and write these characters to
another file then use the following code.
FileReader fr = new FileReader(“Inputfile”);
FileWriter fw = new FileWriter(“outputfile”);
int ch;
while((ch = fr.read( )) != -1) fw.write((char)ch);
If you want to read lines from a file and write to another file then??
Try it out
File class
File(String path)
File(String name, String relativePath)
File(URI uri)
e.g. File f = new File(“e:\dir1\dir2\prog.java”);
File [ ] listFiles( )
boolean mkdir( )
boolean mkdirs( )
e.g.
File f = new File(“e:\dir1”);
f.mkdir( );
Instances of this class support both reading and writing to a random access file.
There is a kind of cursor, called the file pointer; input operations read bytes
starting at the file pointer and advance the file pointer past the bytes read. If the
random access file is created in read/write mode, then output operations are also
available; output operations write bytes starting at the file pointer and advance the
file pointer past the bytes written.
Mode
"r“
Open for reading only. Invoking any of the write methods of the resulting object
will cause an IOException to be thrown.
"rw“
Open for reading and writing. If the file does not already exist then an attempt
will be made to create it.
"rws“
Open for reading and writing, as with "rw", and also require that every update to
the file's content or metadata be written synchronously to the underlying
storage device.
"rwd"
Open for reading and writing, as with "rw", and also require that every update to
the file's content be written synchronously to the underlying storage device.
Java Networking
A computer that has resource to share is called a host. The host name
can be expressed by its domain name or by numeric IP address.
TCP Connection
A socket is an abstraction of the end point of a connection.
These are the streams to read data from and write data to the socket.
Methods
public InetAddress getInetAddress()
Returns the address to which the socket is connected.
Inside the server program you create a server socket using constructor
of ServerSocket class
ServerSocket(int portno);
It encapsulates IP address
Methods
public String getHostName()
Gets the host name for this IP address
DatagramSocket(int port, InetAddress laddr)
Creates a datagram socket, bound to the specified local address.
Develop a class that implements this interface and extends the API
class UnicastRemoteObject (java.rmi.server) in the remote
machine. This class facilitates export of object from the remote
machine to the local machine. A public default constructor in this
class is mandatory.
Develop a class inside the local machine that looks for the desired
service using lookup method of the Naming class.
Create the class files from the source files in the local & remote
machine.
start rmiregistry
java Addition
References
java.sun.com
In 1995, Sun tried to expand the Java library for accessing SQL
database.
In 1996, they came out with two group of interfaces namely, JDBC API
and JDBC driver API.
The JDBC driver manager (written in pure Java) manages the database
drivers.
JDBC
Connection conn =
DriverManager.getConnection(“protocol:subprotocol:data source
name”, “user”, “pwd”);
url = protocol:subprotocol:dsn
DriverManager class is declared in java.sql
Connection is an interface declared in java.sql
JDBC
Statement interface
Connection interface
You will find setXxx(int index, Xxx value) methods that assign a
value to a parameter.
If the parameter is of type int then use
setInt method, if it is of type double then use setDouble method.
JDBC
ResultSet interface
public boolean next() throws SQLException
public String getString(int colindex) throws SQLException
public String getString(String colName) throws SQLException
public int getInt(int colindex) throws SQLException
public int getInt(String colName) throws SQLException
public double getDouble(int colindex) throws SQLException
public double getDouble(String colName) throws SQLException
public float getFloat(int colindex) throws SQLException
public float getFloat(String colName) throws SQLException
JDBC
DML statement
DDL statement
java.sun.com
Portions
Multithreaded programming
Java I/O
QUIZ IV
Scheduled on
April 19, 2010
Portions
Java Networking
JDBC
RMI
Console-based program vs. Window-based program
A console-based program can prompt its user for input but a window-
based program cannot. All window-based programs are event-driven.
When there is no event it waits for an event to occur. Whenever an
event occurs, the program catches the event, takes necessary actions
and immediately returns control to the runtime system. It cannot keep
control with itself for a prolonged interval. This is why if you want a
window-based program to do a job repeatedly (e.g. animation) then
you
need to run an additional thread of execution.
Applets
Definition
An applet is a window-based small program that can run inside a
browser / appletviewer.
Every applet that you develop must a sub class of Applet class
(java.applet) and this class must be declared public
e.g.
pubic class Applet1 extends Applet {
Body of the class
}.
Applets
Object
Component
Container
Panel
Applet
The default back ground color of a component is light grey and fore
ground color is black.
Component class
public void repaint(long ms, int top, int left, int w, int h)
Component class
public Applet( )
URL getCodeBase( )
returns the base directory of the applet class file.
URL getDocumentBase( )
returns the URL of the document in which this applet is embedded.
Applet class
String getAppletInfo( )
returns the author`s name, version etc. of the applet. The
default implementation returns null.
AppletContext getAppletContext( )
returns the context the applet is running.
Image getImage(URL url)
Returns an Image object that can then be painted on the screen. The
url that is passed as an argument must specify an absolute URL.
• AudioClip getAudioClip(URL url)
– Returns the AudioClip object specified by the URL argument.
• void play(URL url)
– Plays the audio clip at the specified absolute URL
Applet tag
</applet>
Applet tag
In case the browser is Java enabled but currently cannot display the
applet then the alternate text (alt) is displayed.
Component
Container
Panel Window
Component
TextField TextArea
Label class
Label( )
Label(String text)
Label(String text, int align)
Value of align may be Label.LEFT, Label.RIGHT, Label.CENTER
String getText( )
void setText(String newText)
int getAlignment( )
void setAlignment(int align)
Button class
Button( )
Button(String caption)
String getLabel( )
void setLabel(String caption)
Checkbox class
Checkbox(String label)
Checkbox(String label, boolean checked)
Checkbox(String label, boolean checked, CheckboxGroup cbg)
Checkbox(String label, CheckboxGroup cbg, boolean checked)
boolean getState( )
void setState(boolean checked)
String getLabel( )
void setLabel(String label)
Choice class
List class
The List component presents the user with a scrolling list of text items.
The list can be set up so that the user can choose either one item or
multiple items.
List( )
List(int numRows) no. of rows visible at any time.
List(int numRows, boolean multiselect)
e.g.
List lst = new List(2, false);
lst.add("Mercury");
lst.add("Venus");
lst.add("Earth");
lst.add("JavaSoft");
List class
TextArea( )
TextArea(String text)
TextArea(int numlines, int numChars)
TextArea(String text, int numlines, int numChars, int sbars)
sbars = TextArea.SCROLLBARS_BOTH
= TextArea.SCROLLBARS_NONE(default)
= TextArea.SCROLLBARS_HORIZONTAL_ONLY
= TextArea.SCROLLBARS_VERTICAL_ONLY
TextArea class
A code example:
Window class
Window(Frame owner)
A code example:
Panel class
An object of this class is a surface without border and without title bar.
Panel( )
Panel(LayoutManager lm)
creates a panel with the specified layout manager.
Layout Managers
There are different types of layout namely, flow layout, border layout,
grid layout, card layout and these are implemented in
FlowLayout, BorderLayout, GridLayout, CardLayout classes
respectively.
The flow layout manager lays out components from left to right and top
to bottom.
The default spacing between components is 5 pixels (both horizontal
and vertical direction).
FlowLayout( )
FlowLayout(int how)
how = FlowLayout.CENTER, FlowLayout.LEFT, FlowLayout.RIGHT
BorderLayout( )
BorderLayout(int hgap, int vgap)
GridLayout class
This layout manager lays out components in an invisible grid inside the
container.
GridLayout( )
GridLayout(int numRows, int numCols)
GridLayout(int numRows, int numCols, int hgap int vgap)
Changing layout of a container
If a text field has input focus and if you press the enter key then
ActionEvent is fired.
Event handling
When you edit a text field or a text area then TextEvent is fired.
For each key there is defined a public static final identifier in the
KeyEvent class and name of these identifiers starts with VK (virtual
key) e.g. VK_A, VK_B, VK_SHIFT
Adapter class
If you are implementing the KeyListener interface then you need to give
the definition of all the methods (even an empty definition is
mandatory).
If you use adapter class you don`t have to define all the methods of the
interface.
Adapter class
Code example:
//listener registration
addKeyListener(new KeyAdapter( ) {
public void keyTyped(KeyEvent ke) {
//code
}
}
);
Mouse event
@MouseListener interface
Mouse event
@MouseMotionListener interface
To find the order in which the event handling methods are called
include an output message in each of the event handling methods.
//registration
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose( );
}
}
);
Menu bar, menus, menu items & check box menu items
MenuCompnent
MenuBar MenuItem
Menu CheckboxMenuItem
MenuBar( )
e.g.MenuBar mbar = new MenuBar( );
Menu( )
Menu(String label)
Menu(String label, boolean tearOff)
e.g. Menu menu = new Menu(“Draw’);
MenuItem( )
MenuItem(String label)
MenuItem(String label, MenuShortcut keyAccel)
Menu bar, menus, menu items & check box menu items
MenuShortCut(int key)
MenuShortCut(int key, boolean shiftRequired)
e.g. MenuItem item =
new MenuItem(“Line”, new MenuShortcut(KeyEvent.VK_L, true)
CheckboxMenuItem( )
CheckboxMenuItem(String label)
CheckboxMenuItem(String label, boolean checked)