SlideShare a Scribd company logo
1 of 180
More Programming Concepts
Forth Year
University of Salahaddin-Erbil
College of Engineering
Department of Software Engineering
Karim Zebari
2003-2004
About this course
Programming courses, such as this course, usually involve a considerable
amount of practical coursework or programming in the labs. You should
find as much time as possible in the labs for exercises, assignments and
testing in Java. The only way to really learn a new programming language
is to write many programs and read other people’s programs. You have
no scheduled hours in the lab for this course; you should work at least 2
hours per week in the open lab.
These notes are intended to cover the bulk of this course, but you should
never rely on notes ONLY. The following textbooks are recommended:
1) Java How to Program, 3rd
Edition, 1999, Deitel & Deitel
2) Java The Complete Reference,
3) http://java.sun.com Java Homepage
4) http://java.sun.com/docs/books/tutorial Java Online Tutorial,
also available locally
Several other books are available in the department’s library/intranet.
Object Oriented Programming in Java 2
About this course 2
This half-year course will build on your previous programming courses and
we will continue to use the Java programming language.
The course will introduce you to more advanced programming concepts
and as such will offer you a collection of topics on specialized
programming areas. There will also be other computing topics discussed
and practiced using Java, such as data/network security, multi-threading,
etc.
Some of the concepts introduced in this course may be useful for your
Final Year project and these will be covered earlier on the course.
You should work in the labs as much as possible. This course
and some other courses, as well as your Final Year project may involve a
lot of programming in a network environment. You cannot do this at home,
if you have only one computer. I advice you to work very hard in this final
year and develop your programming skills as much as you can.
Object Oriented Programming in Java 3
The Syllabus
The following topics will be covered in this course:
- Multithreading
- Security in Java
- Java Beans
- Internationalization
- Java Servlets
- Java Server Pages
- Database access in Java
- More GUI Components & Printing
- Remote Method Invocation (RMI)
- Java Collections Framework
Object Oriented Programming in Java 4
Network Programming
The Transmission Control Protocol or TCP provides a reliable point-to-
point communication channel that clients and servers can use to
communicate with one another.
To communicate over TCP, a client program and a server program
establish a connection to one another. Each program binds a socket to its
end of the connection. To communicate, the client and the server each
reads from and writes to the socket bound to the connection.
A socket is one end-point of a two-way communication link between two
programs running on the network. Socket classes are used to represent
the connection between a client program and a server program. The
java.net package provides two classes: Socket and ServerSocket-
that implement the client side of the connection and the server side of the
connection, respectively.
Object Oriented Programming in Java 5
(Mostofthematerialontheseslidesistakenfromthe“TheJava
Tutorial”fromSun,whichiselectronicallyavailableontheintranet)
Network Programming 2
Generally speaking, a computer has a single physical connection to the
network. All data destined for a particular computer arrives through that
connection. However, the data may be intended for different applications
running on the computer. So how does the computer know to which
application to forward the data? Through the use of ports.
Data transmitted over the Internet is accompanied by addressing
information that identifies the computer and the port for which it is destined.
The computer is identified by its 32-bit IP address, which IP uses to deliver
data to the right computer on the network. Ports are identified by a 16-bit
number, which TCP use to deliver the data to the right application.
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. A client
can then talk with the server at the server's port, as illustrated ere:
Object Oriented Programming in Java 6
Network Programming 3
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.
So in order to establish communication between a client and a server, we
need a socket for the client and socket for the server (ServerSocket).
Then we need to specify a port and bind the socket (client or server ) to
this port, depending on the application. Your applications can use any
ports not in the range of well-known ports.
Object Oriented Programming in Java 7
Network Programming 4
In the following example, we will write a client and a server program. The client will try to
establish a connection with the server. After the connection is made between the two,
the client can send strings to the server and the server will return or echo what the client
sent it.
We will make the server to listen on port 4444, so the client will use this port number to
connect to the server. Of course, the client will also need the host name of the server.
You can this this client/server application on a network or on the same computer.
First the code for the client machine:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
;
Object Oriented Programming in Java 8
Network Programming 5
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null
try {
echoSocket = new Socket("toshiba", 4444);
out = new PrintWriter(
echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know host: toshiba.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: toshiba.");
System.exit(1);
}
Object Oriented Programming in Java 9
Network Programming 6
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
System.out.println(in.readLine());
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
This client program works like this: it first creates a socket which will be
used to connect to a machine called “toshiba” on port 4444. The prgram
Object Oriented Programming in Java 10
Network Programming 7
Then gets the socket's output stream and input stream. Notice that the
same socket can be used for both input and output of data.
The last statement in the while loop reads a line of information from the
BufferedReader connected to the socket. The readLine method waits
until the server echoes the information back to EchoClient. When
readline returns, EchoClient prints the information to the standard
output.
The while loop continues until the user types an end-of-input character.
That is, EchoClient reads input from the user, sends it to the Echo server,
gets a response from the server, and displays it, until it reaches the end-of-
input. The while loop then terminates and the program continues,
executing the next four lines of code:
Object Oriented Programming in Java 11
Network Programming 8
out.close();
in.close();
stdIn.close();
echoSocket.close();
These lines of code fall into the category of housekeeping. A well-behaved
program always cleans up after itself, and this program is well-behaved.
These statements close the readers and writers connected to the socket
and to the standard input stream, and close the socket connection to the
server. The order here is important. You should close any streams
connected to a socket before you close the socket itself.
This client program is straightforward and simple because the Echo server
implements a simple protocol. The client sends text to the server, and the
Object Oriented Programming in Java 12
Network Programming 9
server echoes it back. When your client programs are talking to a more
complicated server such as an HTTP server, your client program will also
be more complicated. However, the basics are much the same as they are
in this program:
1- Open a socket.
2- Open an input stream and output stream to the socket.
3- Read from and write to the stream according to the server's protocol.
4- Close the streams.
5- Close the socket.
Only step 3 differs from client to client, depending on the server. The other
steps remain largely the same.
Now the server application:
Object Oriented Programming in Java 13
Network Programming 10
The server program begins by creating a new ServerSocket object to
listen on a specific port. When writing a server, choose a port that is not
already dedicated to some other service.
ServerSocket is a java.net class that provides a system-independent
implementation of the server side of a client/server socket connection. The
constructor for ServerSocket throws an exception if it can't listen on the
specified port (for example, the port is already being used).
If the server successfully connects to its port, then the ServerSocket object
is successfully created and the server continues to the next step--accepting
a connection from a client:
clientSocket = serverSocket.accept();
The accept method waits until a client starts up and requests a connection
on the host and port of this server (in this example, the server is running on
the hypothetical machine taranis on port 4444).
Object Oriented Programming in Java 14
Network Programming 11
When a connection is requested and successfully established, the accept
method returns a new Socket object which is bound to a new port. The
server can communicate with the client over this new Socket and continue
to listen for client connection requests on the ServerSocket bound to the
original, predetermined port. This particular version of the program doesn't
listen for more client connection requests:
import java.net.*;
import java.io.*;
public class EchoServer {
public static void main(String[] args) throws IOException{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port:
Object Oriented Programming in Java 15
Network Programming 12
4444."); System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new
PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader( new
InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
out.println("Welcome to Toshiba Echo Server, Please
type some string");
Object Oriented Programming in Java 16
Network Programming 13
while ((inputLine = in.readLine()) != null) {
outputLine = inputLine;
out.println(outputLine);
if (outputLine.equals("Bye"))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
Run this server and attempt to connect to it with multiple clients. Only the
first client will succeed. To serve multiple client connections, you must use
threads. See the next server version which uses threads to serve multiple
clients at the same time. Threads will be introduced in this example.
Object Oriented Programming in Java 17
Network Programming 14
In this version of the server, which is very similar to the last one, every time
we know the program has established a new socket connection, that is, when
the call to accept was successful, we will start a new thread to deal with the
connection between the server and that client. The main program will just go
back waiting for more connection requests from other clients.
Here is the threaded server:
import java.net.*;
import java.io.*;
public class MultiServer {
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
boolean listening = true;
Object Oriented Programming in Java 18
Network Programming 15
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(-1);
}
while (listening)
new MultiServerThread(serverSocket.accept()).start();
serverSocket.close();
}
}
class MultiServerThread extends Thread {
private Socket socket = null;
public MultiServerThread(Socket socket) {
this.socket = socket;
}
Object Oriented Programming in Java 19
Network Programming 16
public void run() {
try { PrintWriter out = new PrintWriter(
socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String inputLine, outputLine;
out.println("Welcome to Toshiba Echo Server");
while ((inputLine = in.readLine()) != null) {
outputLine = inputLine;
out.println(outputLine);
if (outputLine.equals("Bye")) break;
}
out.close(); in.close(); socket.close();
} catch (IOException e) { e.printStackTrace();}
}
}
Object Oriented Programming in Java 20
Network Programming 17
Every time a new socket connection is established (when method accept
succeeds) a new thread is created and started to take care of the new
connection. Here a new class is created which extends the Thread class.
Any class that subclasses the Thread class should provide override the
run() method. You should not call the run method. Instead call the
object’s start() method which will call the run method. You provide the
desired functionality of the thread in the run method.
You should realize the importance of protocols by now. Look at the last
two programs again and test them. If the client and the server do not
understand each other, the client/server application will not function. They
cannot communicate. For this simple client/server pair, it was not
necessary to specify and document a protocol but for more complicated
applications, you will need to specify and develop protocols before writing
you client and server programs. Who should talk first? Second? When
should they disconnect?...
Object Oriented Programming in Java 21
Network Programming 18
One more point about sockets is that in real-life applications, especially on
a large network like the Internet, your programs may hang for a long time.
For example a host is unreachable, your program will wait a long time and
be at the mercy of the underlying operating system to time out the
connection.
To avoid such a situation, you can set a time-out value for your
applications using the method setSoTimeout in milliseconds:
Socket s=new Socket(…….);
s.setSoTimeout(10000);
There is a problem with this though. What if the Socket constructor itself
can block indefinitely? The solution to this is to construct the socket in a
separate thread and wait for that thread to complete or timeout.
Object Oriented Programming in Java 22
Network Programming 19
Internet addresses or IP addresses consist of four byes such as
122.23.132.167. There is a unique IP address for each Internet host.
This gives about 4.2 billion hosts.
Host names domain names can be used instead of Internet addresses as
they are easier for humans to remember. For example, it is a lot easier to
remember java,sun.com than 192.18.97.71.
Java has a class called InetAddress which can be used to convert
between host names and Internet addresses.
The static method getByName returns an IntetAddress of a host:
InetAddress address=InetAddress.getByName(“java.sun.com”);
This will return an InetAddress object that contains the sequence of four
bytes: 192.18.97.71. To access the byes use the getBytes method:
byte[] addressBytes=address.getBytes();
Object Oriented Programming in Java 23
Network Programming 20
Lets see a program that will convert any host name into an Internet
address:
import java.net.*;
public class InetAddressTest
{ public static void main(String[] args)
{ try
{
String host = "java.sun.com";
InetAddress address = InetAddress.getByName(host);
System.out.println(address);
}
catch (Exception e)
{ System.out.println("Error: " + e);
}
}
}
Object Oriented Programming in Java 24
Network Programming 21
Now we will look at another example in which an applet is used to
communicate with a running server on another machine (could be the
same machine). First the client applet:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class NetApplet extends JApplet implements
ActionListener {
TextField numbField;
Label display;
Socket socket;
Object Oriented Programming in Java 25
Network Programming 22
public void init() {
try {
socket = new Socket("toshiba",8765);
} catch (UnknownHostException e) {
System.out.println("Unknown host");
} catch (IOException e) {
System.out.println("IO Exception");
}
getContentPane().setLayout(new FlowLayout());
numbField = new TextField(6);
getContentPane().add(numbField);
Button button = new Button("Send");
getContentPane().add(button);
button.addActionListener(this);
display = new Label("No number");
getContentPane().add(display); }
Object Oriented Programming in Java 26
Network Programming 23
public void actionPerformed(ActionEvent e){
int numb = 0;
String numbStr = null;
BufferedReader fromServer = null;
PrintWriter toServer = null;
if (e.getSource()==button){
try {
numb = Integer.parseInt(numbField.getText());
}
catch (NumberFormatException ex){
JOptionPane.showMessageDialog(this, " Number
Format Exception", "Results",
JOptionPane.PLAIN_MESSAGE);
}
Object Oriented Programming in Java 27
Network Programming 24
try{
fromServer = new BufferedReader(new InputStreamReader
(socket.getInputStream()));
toServer =new PrintWriter(socket.getOutputStream(), true);
}
catch (IOException ex){
System.out.println("IO Exception");
}
toServer.println(numb);
Try { numbStr = fromServer.readLine(); }
catch (IOException ex){
System.out.println("Applet receive failed:");
}
display.setText(numbStr);
}
}
Object Oriented Programming in Java 28
Network Programming 25
The applet would look like something like this:
After creating a socket, the applet parses
and sends the text field value to the
server through an output stream.
It then waits until it receives a result
from the server. The result is then
placed in the label next to the text field.
The server: The server is much simpler than the client. Usually servers do
not have any GUI components. They just listen for client requests in the
background. After receiving a connection request and accepting it, the
server identifies the requesting client and if it is a certain client, it is
disconnected. If not it increments the integer it received and sends it back.
Object Oriented Programming in Java 29
Network Programming 26
public class NetServer {
public static void main(String[] args) {
try{
ServerSocket serverSocket = new ServerSocket(8765);
Socket clientSocket = serverSocket.accept();
InetAddress remote=clientSocket.getInetAddress();
if(remote.getHostName().equals("toshiba"))
clientSocket.close();
BufferedReader fromClient = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter toClient = new
PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
int n=Integer.parseInt(fromClient.readLine());
System.out.println("received: " + n);
toClient.println(n+1); }
Object Oriented Programming in Java 30
Network Programming 27
}
catch(IOException ex)
{
System.err.println(ex);
}
}
}
This server will accept and serve all clients except “toshiba”. Some
networks use firewalls to block traffic from certain networks. They use
methods like this to block access from certain networks or addresses. They
may also be used to block internal network users from accessing certain
outside networks.
Network programming in Java is a lot more than what we have covered in
the last few slides. It is a subject of its own. This was just to give you a
flavor. For more information you should consult textbooks and other
material available on the net. The net is the best resource of information.
Object Oriented Programming in Java 31
Database Programming
It has been estimated that half of all software development involves
client/server operations and most client-server operations involve database
connectivity.
A database system is a repository or store of data. Database systems
organize data in an orderly way making the data easily accessible and
updatable. Instead of using a database, you could use an ordinary text file
to store your data. But we all know how a database system management
system make updating, organizing and accessing data more efficient and
user-friendly.
Being able to access a database through programming is also important
and allows the programmer to write custom applications. Software users
(companies, universities, governments, stores…) prefer customized
software. Software that is designed to need their requirements and that is
easy to use.
Object Oriented Programming in Java 32
Database Programming 2
Java supports database programming. Java Database Connectivity or
JDBC is designed to provide Java programmers with a uniform way of
accessing database systems. With JDBC you can access almost all
current database systems (MS SQL Server, MS Access, Oracle, DB2,
Informix…)
JDBC works like this: database vendors provide drivers for their particular
database system to work with JDBC driver manager. JDBC provides an
abstraction layer on top of these drivers. Programs written according to
JDBC API would talk to the JDBC driver manager, which in turn, would use
the drivers that it has to talk to the actual database.
Using JDBC, Java programmers can write applications to access any
database, using standard SQL statements.
You can use JDBC in both applications and applets but bear in mind that
Object Oriented Programming in Java 33
Database Programming 3
With applets, security restrictions would apply which mean that the applet
can only access a database from the server from which it was downloaded.
JDBC is an interface to SQL which is an interface to all modern relational
databases. So basically, JDBC let’s you pass and execute SQL
statements to databases.
You should now SQL from your previous courses but here a short
introduction will be presented. You can find more information on SQL on
the intranet.
You can think of a database as a group of named tables with rows and
columns. Each column has a column name. The rows contain the actual
data (records).
Object Oriented Programming in Java 34
Database Programming 4
We assume we have a small MS Access database with a single table. The
program example which follow will use this database for testing. The table
Students has the following design:
In SQL, to select all the records from the above table you would use:
SELECT * FROM Students
The FROM clause tells database which table to access. Or you can restrict
the columns:
SELECT Name, [Coursework Mark] FROM Students
Object Oriented Programming in Java 35
Database Programming 5
To restrict the rows or records, you use the WHERE clause:
SELECT * FROM Students
WHERE [Coursework Mark] >40
Be careful with the “equals” sign. SQL used = and <>, not == or !=, as in
Java for testing equality. You can access more than one table at the same
time:
SELECT * FROM Students, Departments
You can also use SQL to update the data in a table:
UPDATE Students
SET [Coursework Mark]=[Coursework Mark] + 2
To insert values into a table, use the INSERT statement:
INSERT INTO Students
Values(‘hamid’,‘Hamid Husain’,‘4’,’10-Oct-1980’,‘35.5’)
Note that strings are enclosed in single quotes in SQL.
Object Oriented Programming in Java 36
Database Programming 6
To create a new table:
CREATE TABLE Departments
( Dept_Name CHAR(20) , Head CHAR(20),
No_Of_Students INT)
For details of SQL types and other statements, consult a book or the
intranet page for this course.
You also need to create a Data Source Name (DSN) for your Access
database. You will use this DSN when you connect to the database. You
can do this in the Control Panel. This will be demonstrated in the lab.
We will now write a simple Java program that will access the above
database :
Object Oriented Programming in Java 37
Database Programming 7
import java.sql.*;
public class CreateMarks {
public static void main(String args[]) {
String url = "jdbc:odbc:StudentsDSN";
Connection con;
String createString;
createString = "select * from Students";
Statement stmt;
try { //load odbc-jdbc bridge driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
Object Oriented Programming in Java 38
Database Programming 8
try {
con = DriverManager.getConnection(url, "", "");
stmt = con.createStatement();
ResultSet rs=stmt.executeQuery(createString);
while(rs.next())
System.out.println(rs.getString(2) + " | " +
rs.getString(3) + " | " + rs.getString(4) + " | " +
rs.getString(5));
rs.close();
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLExc.:" + ex.getMessage());
}
}
}
Object Oriented Programming in Java 39
Database Programming 9
The string url is used to represent a protocol, here jdbc:odbc: means
that JDBC interfaces Microsoft's ODBC which then connects to the
database server - whose Internet address is denoted by the DSN Data
Source Name StudentsDSN. This could be on another computer, in which
case you would have to specify its location.
A driver is needed which bridges between the Java JDBC and Microsoft's
ODBC. This driver is loaded from Sun's site. Then the connection to the
database, specified by URL, user name and password, is established.
Finally, a statement object is created, which will allow us to pass SQL
statements to the database.
You create an SQL statement and pass this statement to the
executeQuery method of the statement object. The result of this method
is a Resultset object ( a set of tuples/records). Then we use a loop to
iterate through the elements of the resultset object.
Object Oriented Programming in Java 40
Database Programming 10
You create an SQL statement and pass this statement to the
executeQuery method of the statement object. The result of this method
is a Resultset object ( a set of tuples/records) and does not change the
state of the database. Then we use a loop to iterate through the elements
of the resultset object.
A resultset object is a table of data representing a database result set,
which is usually generated by executing a statement that queries the
database. A ResultSet object maintains a cursor pointing to its current row
of data.
Initially the cursor is positioned before the first row. The next method
moves the cursor to the next row, and because it returns false when there
are no more rows in the ResultSet object, it can be used in a while loop to
iterate through the result set.
Object Oriented Programming in Java 41
Database Programming 11
Note that the method getString is given a number; this number
represents the column number. They start with 1. You could use column
names (in single quotes) instead:
rs.getString(‘Name’)
Or
rs.getInteger(‘Year’);
This program will output the 2nd
, 3rd
, 4th
and 5th
columns of each row.
Earlier, we used the executeQuery method of the Statement object to
execute a query which just returns a resultset and leaves the database
intact. To make updates to a database you can use the executeUpdate
method of the Statement object. For example, to add a new record to the
Students table:
stmt.executeUpdate(“INSERT INTO Students “ +
“values(‘username’,‘User Name’,3,’2-Apr-03’,45)”
Object Oriented Programming in Java 42
Database Programming 12
This statement would add the record to the table. Note that it is customary
to use uppercase letters for SQL keywords words. SQL is case insensitive.
The executeUpdate method, unlike the executeQuery method of the
JDBC alters the state of the database.
We know that the executeQuery method returns a resultset. The
executeUpdate method returns the number of records affected by the
update operation, for example the following SQL statement would return 3:
int n=stmt2.executeUpdate(“UPDATE Students SET
[cousework mark]=40 where
[cousework mark]<40");
System.out.println(n);
Object Oriented Programming in Java 43
Database Programming 13
You can create a new table as follows:
String createTable = “CREATE TABLE Department"+
"(Dept_ID INTEGER, Dept_NAME VARCHAR(40))";
There is a lot more to JDBC than what we have looked at so far. You must
know SQL to write more advanced database applications, especially when
you need to access databases with many tables and when there are
relationships between those tables.
For more information on SQL data types and their equivalents, consult the
Java documentation or other reference material.
Most client/server applications involve accessing database systems over a
network. You can now write useful applications that utilize both network
programming and database access. Adding a GUI interface to your client-
side application will make it user-friendly and easier to use.
Object Oriented Programming in Java 44
Database Programming 14
There are times when you don’t want a statement to be executed unless
another statement/statements are also executed. For example, consider
the following two tables:
And
Object Oriented Programming in Java 45
Database Programming 15
Now suppose you would like to update the Students table by adding a new
record to it. If this update operation is successful, you would also like the
second table, Departments, to be updated too. Otherwise your database
would be in an inconsistent state. You would want to update the value of
the third column in the Departments table.
A transaction is a set of one or more statements that are executed
together as a unit, so either all of the statements are executed, or none of
the statements is executed.
When a connection is created, it is in auto-commit mode. This means that
each individual SQL statement is treated as a transaction and will be
automatically committed right after it is executed. This is the default
behavior. The way to allow two or more statements to be grouped into a
transaction is to disable auto-commit mode. This is demonstrated in the
following line of code, where con is an active connection:
con.setAutoCommit(false);
Object Oriented Programming in Java 46
Database Programming 16
Once auto-commit mode is disabled, no SQL statements will be committed
until you call the method commit explicitly. All statements executed after the
previous call to the method commit will be included in the current transaction
and will be committed together as a unit. The following code, in which con is
an active connection, illustrates a transaction:
try {
con = DriverManager.getConnection(url, "", "");
con.setAutoCommit(false);
stmt1 = con.createStatement();
stmt2 = con.createStatement();
stmt1.executeUpdate("INSERT INTO Students
values('username9','User Name 9',1, 4,'2-Apr-80',45)");
stmt2.executeUpdate("Update Department SET
No_of_Student=No_of_Student+1 where Dept_ID=1");
con.commit();
con.setAutoCommit(true);
Object Oriented Programming in Java 47
Database Programming 17
con.close();
}
catch(SQLException ex) {
System.err.println("SQLException: " + x.getMessage());
if (con != null) {
try {
System.err.print("Transaction is being rolled
back");
con.rollback();
} catch(SQLException excep) {
System.err.print("SQLException: ");
System.err.println(excep.getMessage());
}
}
}
The code in bold constitutes a transaction or unit of execution. Here we
Object Oriented Programming in Java 48
Database Programming 18
have specified that we want all the statements in this transaction be
executed as one single statement. If there is a problem and one statement
cannot succeed for some reason, they we rollback that transaction in the
catch statement.
In this example, auto-commit mode is disabled for the connection con ,
which means that the two statements stmt1 and stmt2 will be committed
together when the method commit is called. Whenever the commit method
is called (either automatically when auto-commit mode is enabled or
explicitly when it is disabled), all changes resulting from statements in the
transaction will be made permanent.
The first statement, stmt1, succeeds without any problems. The second
statement, stmt2, includes an error and an exception is thrown and caught
before the commit method is executed.
Object Oriented Programming in Java 49
Database Programming 19
As mentioned earlier, calling the method rollback aborts a transaction and
returns any values that were modified to their previous values. If you are
trying to execute one or more statements in a transaction and get an
SQLException , you should call the method rollback to abort the
transaction and start the transaction all over again.
That is the only way to be sure of what has been committed and what has
not been committed. Catching an SQLException tells you that something
is wrong, but it does not tell you what was or was not committed. Since you
cannot count on the fact that nothing was committed, calling the method
rollback is the only way to be sure.
In our simple example, when we add a new student’s record to the
database, we would like to also update the count of students for that
particular department. If for some reason, either statement couldn’t be
executed, we would like to abort the whole transaction or rollback.
Object Oriented Programming in Java 50
Trees
With the JTree class, you can display hierarchical data. A JTree object
doesn't actually contain your data; it simply provides a view of the data.
Here's a picture of a tree:
As the preceding figure shows, JTree displays
its data vertically. Each row displayed by the tree
contains exactly one item of data, which is called
a node. Every tree has a root node from which all
nodes descend. By default, the tree displays the
root node, but you can decree otherwise. A node can either have children or
not. We refer to nodes that can have children -- whether or not they
currently have children -- as branch nodes. Nodes that can't have children
are leaf nodes.
Branch nodes can have any number of children. Typically, the user can
expand and collapse branch nodes -- making their children visible or
invisible -- by clicking them.
Object Oriented Programming in Java 51
Trees 2
By default, all branch nodes except the root node start out collapsed. A
program can detect changes in branch nodes' expansion state by listening
for tree expansion events. The following program will create a simple tree:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
public class SimpleTree
{ public static void main(String[] args)
{ JFrame frame = new SimpleTreeFrame();
frame.show();
}
}
Object Oriented Programming in Java 52
Trees 3
class SimpleTreeFrame extends JFrame
{ public SimpleTreeFrame()
{ setTitle("SimpleTree");
setSize(300, 200);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
} );
// set up tree nodes first
DefaultMutableTreeNode root
= new DefaultMutableTreeNode("Kurdistan Region");
DefaultMutableTreeNode governorate1 = new
DefaultMutableTreeNode("Erbil");
root.add(governorate1);
Object Oriented Programming in Java 53
Trees 4
DefaultMutableTreeNode town1 = new
DefaultMutableTreeNode("Shaqlawa");
governorate1.add(town1);
DefaultMutableTreeNode town2 = new
DefaultMutableTreeNode("Koye");
governorate1.add(town2);
DefaultMutableTreeNode town3 = new
DefaultMutableTreeNode("Soran");
governorate1.add(town3);
DefaultMutableTreeNode governorate2= new
DefaultMutableTreeNode("Sulaimaniyah");
root.add(governorate2);
DefaultMutableTreeNode town4= new
DefaultMutableTreeNode("Rania");
governorate2.add(town4);
Object Oriented Programming in Java 54
Trees 5
DefaultMutableTreeNode town5= new
DefaultMutableTreeNode("Dokan");
governorate2.add(town5);
DefaultMutableTreeNode governorate3= new
DefaultMutableTreeNode("Duhok");
root.add(governorate3);
DefaultMutableTreeNode town6= new
DefaultMutableTreeNode("Amedi");
governorate3.add(town6);
DefaultMutableTreeNode town7= new
DefaultMutableTreeNode("Zakho");
governorate3.add(town7);
DefaultMutableTreeNode governorate4= new
DefaultMutableTreeNode("Kirkuk");
root.add(governorate4);
Object Oriented Programming in Java 55
Trees 6
DefaultMutableTreeNode town8= new
DefaultMutableTreeNode("Tuz-Khurmatu");
governorate4.add(town8);
DefaultMutableTreeNode town9= new
DefaultMutableTreeNode("Kifry");
governorate4.add(town9);
// construct tree and put it in a scroll pane
JTree tree = new JTree(root);
Container contentPane = getContentPane();
contentPane.add(new JScrollPane(tree));
}
}
This is the output:
As you can see, the tree does not do
anything useful in response to user clicks
on its nodes.
Object Oriented Programming in Java 56
Trees 7
The code creates an instance of DefaultMutableTreeNode to serve as
the root node for the tree. It then creates the rest of the nodes in the tree.
After that, it creates the tree, specifying the root node as an argument to
the JTree constructor. Finally, it puts the tree in a scroll pane, a common
tactic because showing the full, expanded tree would otherwise require too
much space.
Responding to tree node selections is simple. You implement a tree
selection listener and register it on the tree. The following code shows the
selection-related code from the SimpleTree program above:
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node =
(DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();
if (node == null) return;
Object Oriented Programming in Java 57
Trees 8
if (node.isLeaf())
ta.append("Leaf node: " + node +"n");
else
ta.append("Non-leaf node: "+node + "n");
}
});
You can also use split pane to create two regions, one for the tree (on the
left) and one for a text area, for example: (this is a horizontal split; you can
make it vertical using VERTICAL_SPLIT). The following split pane object
constructor takes 3 parameters: orientation, left component, right
component.
JSplitPane outerPane
= new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
tree, ta);
getContentPane().add(outerPane, "Center");
private JTextArea ta=new JTextArea(10,15);
Object Oriented Programming in Java 58
Trees 9
The previous program’s output is a follows:
You can write complex
and Sophisticated
programs with Trees.
These notes are only
meant to give you a
Flavor of what you
can do with trees. If
You think you need
To use trees, you should look for more information on them from other
sources. One application of threes is when they are used to create links
On a webpage. (You would need to convert the program into an applet
first)
Object Oriented Programming in Java 59
Tables
Tables are very important in organizing data and in performing operations
on numerical data. You have seen their uses in spreadsheets and in
presenting data in web pages.
In Java, a table is a component that displays rows and columns of data.
Tables are implemented by the JTable class which has several
constructors among which the following is the main one:
JTable(Object[][] data, Object[] colHeadings);
data is a two-dimensional array of the information to be displayed, and
colHeading is a one-dimensioanl array of with the column headings.
Like many other Java components and objects, JTable cannot hold data of
the basic data types. To create tables with data of basic data types, you
need to convert your data to objects first.
Object Oriented Programming in Java 60
Tables 2
The following program creates a simple table:
import java.awt.*;import javax.swing.*;
public class JTableDemo extends JFrame{
public JTableDemo(){
setSize(300, 200);
final Object[] colHeading={"Name", "Email", "Year"};
final Object[][] data={
{"Pola", "pola@hotmail.com", "2"},
{"Bestoon","bestoon@soft-eng.net","3"},
{"Barzang", "barzang@yahoo.com", "4"},
{"Omed", "omed@yahoo.com", "4"}};
JTable classTable=new JTable(data, colHeading);
JScrollPane sp=new JScrollPane(classTable);
getContentPane().add(sp, BorderLayout.CENTER);
}
Object Oriented Programming in Java 61
Tables 3
public static void main(String[] a)
{
new JTableDemo().show();
}
}
And this is the output:
The columns of the table are resizable
but not the rows. You can also drag
The columns left or right. Column
Lengths are all equal.
This is the default behavior and is in some cases undesirable. To override
this default behavior and get around these restrictions, you need to extend
the abstract class AbstractTableModel class which implements the
TableModel interface. More information on tables can be found in “The
Java Tutorial”, The JDK documentation or your main textbook.
Object Oriented Programming in Java 62
Tabbed Panes
Another Java GUI component which is quite useful is the JTabbedPane
component which appears as a group of folders in a filing cabinet. Each
folder has a title and when clicked, its contents become visible. Tabbed
panes are commonly used to set configuration options in a program.
Here is a short example demonstrating tabbed panes:
import java.awt.*;import javax.swing.*;
public class JTabbedPaneDemo extends JFrame{
public JTabbedPaneDemo(){
setSize(400, 200);
JTabbedPane jtp=new JTabbedPane();
jtp.addTab("Universities", new
UniversitiesPanel());
jtp.addTab("Techicial Institutes", new
TechnicalInstitutesPanel());
Object Oriented Programming in Java 63
Tabbed Panes 2
jtp.addTab("Schools", new SchoolsPanel());
getContentPane().add(jtp);
}
public static void main(String[] a){
new JTabbedPaneDemo().show();
}
}
class UniversitiesPanel extends JPanel{
public UniversitiesPanel(){
JButton b1=new JButton("Salahaddin");
add(b1);
JButton b2=new JButton("Sulaimaniyah");
add(b2);
JButton b3=new JButton("Duhok"); add(b3);
}
}
Object Oriented Programming in Java 64
Tabbed Panes 3
class TechnicalInstitutesPanel extends JPanel{
public TechnicalInstitutesPanel(){
JButton b1=new JButton("Shaqlawa"); add(b1);
JButton b2=new JButton("Zakho"); add(b2);
JButton b3=new JButton("Erbil"); add(b3);
}
}
class SchoolsPanel extends JPanel{
public SchoolsPanel(){
JButton b1=new JButton("School1"); add(b1);
JButton b2=new JButton("School2");
add(b2);
JButton b3=new JButton("School3");
add(b3);
}
}
Object Oriented Programming in Java 65
Tabbed Panes 4
The second parameter of the JTabbedPane constructor can be any
component; here we have chosen it to be a panel.
Here is the output from this program:
More information on tabbed panes can be found in “The Java Tutorial”,
The JDK documentation or your main textbook.
Object Oriented Programming in Java 66
International Programs
Today, most major software development companies develop international
software rather than software specific to a single language/country. This
obviously has a lot of advantages for them, not least because they will
have a much bigger market out there to sell their software. You too, can
use Java to write multi-lingual programs, including Kurdish programs.
Java includes support for writing internationalized software. Instead of
duplicating the same code for different languages, Java allows you to write
the main code only once.
“Internationalization is the process of designing an application so that it can
be adapted to various languages and regions without engineering changes.
Sometimes the term internationalization is abbreviated as i18n, because
there are 18 letters between the first "i" and the last "n."
Object Oriented Programming in Java 67
(Mostofthematerialontheseslidesistakenfromthe“TheJava
Tutorial”fromSun,whichiselectronicallyavailableontheintranet)
International Programs 2
An internationalized program has the following characteristics:
- With the addition of localized data, the same executable can run worldwide.
-Textual elements, such as status messages and the GUI component labels, are
not hard-coded in the program. Instead they are stored outside the source code
and retrieved dynamically.
- Support for new languages does not require recompilation.
- Culturally-dependent data, such as dates and currencies, appear in formats that
conform to the end user's region and language.
- It can be localized quickly.
Localization is the process of adapting software for a specific region or
language by adding locale-specific components and translating text. The
term localization is often abbreviated as l10n, because there are 10 letters
between the "l" and the "n." Usually, the most time-consuming portion of the
localization phase is the translation of text. Other types of data, such as
sounds and images, may require localization if they are culturally sensitive.
Object Oriented Programming in Java 68
International Programs 3
We will now write a program which will demonstrate a simple multi-lingual
Java program:
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MultiLingualFrame extends JFrame
{
public MultiLingualFrame(){
currentLocale = new Locale("ar", "IQ");
messages = ResourceBundle.getBundle
("MessagesBundle",currentLocale);
Font f=new Font("Arial", Font.PLAIN, 18);
setTitle("Multi Lingual Program");
setSize(300, 250);
Container contentPane = getContentPane();
Object Oriented Programming in Java 69
International Programs 4
JPanel panel = new JPanel();
JButton aButton = new
JButton(messages.getString("text"));
panel.add(aButton);
aButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
textArea.append
(messages.getString("some_message"));
}
});
JButton quitButton=new JButton
(messages.getString("quit"));
quitButton.setFont(f);
panel.add(quitButton);
quitButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
Object Oriented Programming in Java 70
International Programs 5
System.exit(0);
}
});
textArea = new JTextArea(8, 20); textArea.setFont(f);
textArea.setComponentOrientation
(ComponentOrientation.RIGHT_TO_LEFT);
scrollPane = new JScrollPane(textArea);
contentPane.add(panel, "South");
contentPane.add(scrollPane, "Center");
}
private JTextArea textArea;
private JTextField from, to;
Locale currentLocale;
ResourceBundle messages;
}
Object Oriented Programming in Java 71
International Programs 6
public class MultiLingualTest {
public static void main(String[] args)
{ JFrame f = new MultiLingualFrame();
f.show();
}
}
Run this program and provide different locale information each time you run it.
If you look at the above internationalized source code, you'll notice that the
hard-coded English messages have been removed. Because the messages
are no longer hard-coded and because the language code is specified at run
time, the same executable can be distributed worldwide. No recompilation is
required for localization. The program has been internationalized.
As this program demonstrates, to internationalize a program, follow the
following steps:
Object Oriented Programming in Java 72
International Programs 7
1- Create the Properties Files
A properties file stores information about the characteristics of a program
or environment. A properties file is in plain-text format. You can create the
file with just about any text editor. The default properties file, which is
called MessagesBundle.properties, contains the following lines:
greetings = Hello
farewell = Goodbye
inquiry = How are you?
Notice that the values to the right side of the equal sign have been
translated but that the keys on the left side have not been changed. These
keys must not change, because they will be referenced when your
program fetches the translated text.
Object Oriented Programming in Java 73
International Programs 8
The name of the properties file is important. For example, the name of the
MessagesBundle_ar_IQ.properties file contains the ar language
code and the IQ country code. These codes are also used when creating a
Locale object.
Lines beginning with # denote comments and are ignored in a properties
file.
2. Define the Locale
The Locale object identifies a particular language and country. The
following statement defines a Locale for which the language is Arabic and
the country is the Iraq:
Locale aLocale = new Locale(“ar",“IQ");
3. Create a ResourceBundle
ResourceBundle objects contain locale-specific objects. You use
ResourceBundle objects to isolate locale-sensitive data, such as
Object Oriented Programming in Java 74
International Programs 9
translatable text. In the sample program the ResourceBundle is backed
by the properties files that contain the message text we want to display.
The ResourceBundle is created as follows:
message = ResourceBundle.getBundle(
"MessagesBundle", currentLocale);
The arguments passed to the getBundle method identify which
properties file will be accessed. The first argument, MessagesBundle,
refers to this family of properties files:
MessagesBundle_en_US.properties
MessagesBundle_fr_FR.properties
MessagesBundle_de_DE.properties
MessagesBundle_ar_IQ.properties
Object Oriented Programming in Java 75
International Programs 10
4. Fetch the Text from the ResourceBundle
The properties files contain key-value pairs. The values consist of the
translated text that the program will display. You specify the keys when
fetching the translated messages from the ResourceBundle with the
getString method. For example, to retrieve the message identified by
the greetings key, you invoke getString as follows:
String msg1 = messages.getString("greetings");
The sample program uses the key greetings because it reflects the content
of the message, but it could have used another String, such as s1 or
msg1. Just remember that the key is hard-coded in the program and it
must be present in the properties files. If your translators accidentally
modify the keys in the properties files, getString won't be able to find the
messages in that particular locale and the equivalent key in the default
properties file would be selected.
Object Oriented Programming in Java 76
International Programs 11
The MessageBundle_ar_IQ.properties file looks like this:
text=u0628u0646u0648u0633u0640u06d5
some_message=u062cu0640u06d5 u0646u062f
u0631u064Au0640u0632u06d5 u06a9 n
quit=u0628u06afu0631u06d5
These are escape characters. These are the values of the keys in
Unicode. Some platforms/programs do not support direct Unicode
characters and you have to write their equivalents with ASCII escape
sequences. If you are working on an Arabic/enabled platform, you will not
need to worry about these escape characters.
Text messages are the most obvious form of data that varies with culture.
However, other types of data may vary with region or language, including:
Sounds, Colors, Graphics, Dates, Times, Numbers, Currencies,
Measurements, etc. For more details on this, consult your textbooks.
Object Oriented Programming in Java 77
Multi-threading
Unlike most programming languages, Java has built-in support for multi-
threaded programming. A multi-threaded program has two or more parts
which run concurrently. Each part is called a thread or thread of execution.
A computer’s CPU is sometimes idle, for example waiting for some input from
the user, printing something, waiting for data over a network connection.
Using multi-threaded programs, you can minimize a CPU’s idle time by
making your program efficiently perform other tasks.
While a thread waits for data from a network connection, another thread can
be processing some data. The Java garbage collection mechanism is another
example, which runs as a low priority thread in the background.
The Thread Class
A thread can be created several ways; one way is using by sub-classing the
Thread class. The most common constructor for this class is :
Object Oriented Programming in Java 78
Mostofthematerialontheseslidesistakenfromthetextbook.
Multi-threading 2
public Thread(String threadName);
Which constructs a thread object whose name is threadName. The real
work of a thread is done in a method called run, which should be
overridden in subclasses of Thread. You saw an example of this when you
wrote a client-server network program.
Another way of creating a thread object is to make it a runnable object by
making it implement the Runnable interface. An example of this will be
studied later.
A program makes a thread start execution by calling the thread’s start
method, which in turn, calls the run method. After start launches the
thread, start returns to its called immediately. The called then executes
concurrently with the launched thread. In case the thread has already
been started and your program attempts to start it again by mistake, an
IllegalThreadStateException will be thrown.
Object Oriented Programming in Java 79
Multi-threading 3
The static method sleep is called with an argument specifying how long
the currently running thread should sleep. It causes the currently executing
thread to sleep (temporarily cease execution) for the specified number of
milliseconds. While a thread sleeps, it does not contend for CPU time and
so other threads can execute. This gives threads with lower priority a
chance to run.
Other thread methods such as interrupt, isAlive, setName,
getName, and join will be described when we come across them.
Life Cycle of a Thread
A thread can have any one of several thread states. A thread that has
been just created is in the born state. The thread remains in the born
state until its start method has been invoked; this causes the thread to
enter the ready state (or the runnable state). The highest-priority ready
thread enters the running state. It begins execution.
Object Oriented Programming in Java 80
Multi-threading 4
A thread enters the dead state when its run method completes or
terminates for any reason. A dead thread will eventually be disposed of by
the system.
A running thread can enter the blocked state when the thread issues an
input/output request. The blocked thread can be ready again when the I/O
operation it is waiting for completes. A blocked thread cannot use a
processor even if one is available.
When the sleep method of a running thread is called, that thread enters the
sleeping state. It becomes ready again after the designated sleep time
expires. A sleeping thread cannot use a processor even if one is available.
A thread can also be in the waiting state; this will be discussed later when
we look at monitors.
Object Oriented Programming in Java 81
Multi-threading 5
Object Oriented Programming in Java 82
Thisfigureistakenfromthetextbook,page738
Multi-threading 6
Thread Priorities and Thread Scheduling
Every Java program is multi-threaded (applets and applications). Every
Java program has at least one thread -- the main thread. When a Java
program starts, the JVM creates the main thread and calls the program's
main() method within that thread.
The JVM also creates other threads that are mostly invisible to you -- for
example, threads associated with garbage collection, object finalization,
and other JVM housekeeping tasks. Other facilities create threads too,
such as the AWT (Abstract Windowing Toolkit) or Swing UI toolkits, servlet
containers, application servers, and RMI (Remote Method Invocation).
Every Java thread has a priority in the range Thread.MIN_PRIORITY and
Thread.MAX_PRIORITY, or between 1 and 10. By default, each thread
has normal priority: Thread.NORM_PRIORITY which is a constant of 5.
Object Oriented Programming in Java 83
Multi-threading 7
Java assigns a priority to each thread; this determines how that thread
should be treated with respect to other threads. A thread’s priority is used
to decide when to switch from one running thread to the next. This is
called a context switch and the rules that determine a context switch are
simple:
-A thread can voluntarily relinquish control. This is done by explicitly
yielding, or blocking on pending input/output. In this situation, all other
threads are examined and the one with the highest priority that is ready to
run is given the CPU.
- a thread can be preempted by a higher priority thread. In this case, as
soon as a higher priority thread wants to run, it does. This is called
preemptive multitasking.
If two threads have equal priority, context switching depends on the
underlying operating system. On Windows systems, threads of equal
Object Oriented Programming in Java 84
Multi-threading 8
priority are time-sliced in round-robin fashion. In this case, each thread
receives a brief burst of CPU time called a quantum during which that
thread can execute. When the thread’s quantum completes, even if the
thread has not finished, the CPU is taken away from that thread an given to
the next thread of equal priority.
On Solaris, threads yield control voluntarily and if they don’t, the other
threads cannot run. In this situation, each thread in a set of equal-priority
threads runs to completion (unless the thread enters the waiting, sleeping
or blocked state) before other, equal priority, threads can get a chance to
run.
Other platforms may have different scheduling rules. A multi-thread
program may thus behave differently when run on different platforms or
operating systems.
Object Oriented Programming in Java 85
Multi-threading 9
You can change a thread’s priority using the method setPriority which
takes one argument of type integer. If the argument is not in the range 1 to
10, an IllegalArgumentException will be thrown. Use the
getPriority to obtain thread’s priority.
A thread can call the yield method to give other methods a chance to
execute, but using this method in time-slicing systems is unnecessary.
A thread executes unless
- It dies,
- it becomes blocked
- it calls sleep
- it calls wait
- it calls yield
- it is preempted by a higher priority threat
- its quantum expires
Object Oriented Programming in Java 86
Multi-threading 10
The following example from the text book demonstrates some of the above
thread features:
public class ThreadTester {
public static void main( String args[] ){
PrintThread thread1, thread2, thread3, thread4;
thread1 = new PrintThread( "thread1" );
thread2 = new PrintThread( "thread2" );
thread3 = new PrintThread( "thread3" );
thread4 = new PrintThread( "thread4" );
System.err.println( "nStarting threads" );
thread1.start(); thread2.start();
thread3.start(); thread4.start();
}
}
Object Oriented Programming in Java 87
Multi-threading 11
class PrintThread extends Thread {
private int sleepTime;
public PrintThread( String name ) {
super( name );
//random integer between 0 and 10,000 milliseconds
sleepTime = (int) ( Math.random() * 10000 );
System.out.println( "Name: " + getName() + "; sleep: "
+ sleepTime );
}
public void run() {
// put thread to sleep for a random interval
try {
System.out.println( getName() + " going to sleep " +
getPriority());
Thread.sleep( sleepTime );
}
Object Oriented Programming in Java 88
Multi-threading 12
catch ( InterruptedException exception ) {
System.out.println( exception.toString() );
}
System.out.println( getName() + " done sleeping" );
}
}
The program creates and
then starts four threads of
equal priority. Each thread,
after it runs, goes to sleep
for a random Interval
between 0 and 10 seconds.
After each thread awakens,
it prints its name.
Object Oriented Programming in Java 89
Multi-threading 13
When multiple threads try to access shared data (variables, objects, …), the
threads may see inconsistent data. To avoid inconsistent results, you must
control the way concurrent threads access shared data.
The following example will create two threads, one to update a shared
object and one to read the shared object. The shared object has a single
integer value. This program has four classes, each on a separate slide.
public class SharedCell {
public static void main( String args[] ){
HoldIntegerUnsynchronized h =
new HoldIntegerUnsynchronized();
ProduceInteger p = new ProduceInteger( h );
ConsumeInteger c = new ConsumeInteger( h );
p.start();
c.start();
}
}
Object Oriented Programming in Java 90
Multi-threading 14
class HoldIntegerUnsynchronized {
private int sharedInt = -1;
public void setSharedInt( int val ){
System.out.println( Thread.currentThread().getName() +
" setting sharedInt to " + val );
sharedInt = val;
}
public int getSharedInt()
{
System.out.println( Thread.currentThread().getName() +
" retrieving sharedInt value " + sharedInt );
return sharedInt;
}
}
Object Oriented Programming in Java 91
Multi-threading 15
class ProduceInteger extends Thread {
private HoldIntegerUnsynchronized pHold;
public ProduceInteger( HoldIntegerUnsynchronized h ){
super( "ProduceInteger" ); pHold = h;
}
public void run(){
for ( int count = 1; count <= 10; count++ ) {
try {
Thread.sleep( (int) ( Math.random() * 3000 ) );
}
catch( InterruptedException e ) {
System.err.println( e.toString() ); }
pHold.setSharedInt( count );
}
System.err.println( getName()+" finished producing
values" +"nTerminating " + getName() ); } }
Object Oriented Programming in Java 92
Multi-threading 16
class ConsumeInteger extends Thread {
private HoldIntegerUnsynchronized cHold;
public ConsumeInteger( HoldIntegerUnsynchronized h ){
super( "ConsumeInteger" ); cHold = h;
}
public void run() {
int val, sum = 0;
do {
try {
Thread.sleep( (int) ( Math.random() * 3000 ) ); }
catch( InterruptedException e ) {
System.err.println( e.toString() ); }
val = cHold.getSharedInt(); sum += val;
} while ( val != 10 );
System.err.println(getName() + " retrieved values
totaling: " + sum + "nTerminating " + getName() );} }
Object Oriented Programming in Java 93
Multi-threading 17
A run of this program looked like this:
The total of 1 to 5 is 15, not 22 as this program thinks. The Consumer
thread even reads -1, which it shouldn’t. Can you see what is happening
Object Oriented Programming in Java 94
Multi-threading 18
in this program? No synchronization! The two threads should be
synchronized so they access the shared data in a controlled way.
To solve this problem, you must declare each method used by the
Producer or Consumer (in this example, setSharedInt and
getSharedInt) objects which access the shared data, with the
synchronized keyword.
When a synchronized method is running on an object, that object is locked
so that no other synchronized method can run in that object at the same
time.
The next modified program is similar to the previous program; only the the
HoldIntegerUnsynchronized class is replaced with
HoldIntegerSynchronized class:
Object Oriented Programming in Java 95
Multi-threading 19
class HoldIntegerSynchronized {
private int sharedInt = -1;
private boolean writeable = true; // condition variable
public synchronized void setSharedInt( int val ) {
while ( !writeable ) { // not the producer's turn
try {
wait();
}
catch ( InterruptedException e ) {
e.printStackTrace();
}
}
System.err.println( Thread.currentThread().getName() +
" setting sharedInt to " + val );
sharedInt = val;
writeable = false;
Object Oriented Programming in Java 96
Multi-threading 20
notify(); // tell a waiting thread to become ready
}
public synchronized int getSharedInt(){
while ( writeable ) { // not the consumer's turn
try {
wait();
}
catch ( InterruptedException e ) {
e.printStackTrace(); }
}
writeable = true;
notify(); // tell a waiting thread to become ready
System.err.println( Thread.currentThread().getName() +
" retrieving sharedInt value " + sharedInt );
return sharedInt; }
}
Object Oriented Programming in Java 97
Multi-threading 21
This time, the program would produce correct results:
Think about a bank which lets its customers deposit, withdraw and transfer
money. If the bank’s system does not synchronize access to the bank
accounts, no one would want to save their money in this bank.
Object Oriented Programming in Java 98
Multi-threading 22
Thread Synchronization
Java uses monitors to facilitate synchronization. Every Java object with
synchronized methods is a monitor. A monitor’s job is to ensure that only
one thread at a time can execute a synchronized method on the object.
When a synchronized method is called on an object, that object is locked,
also called obtaining the lock. All other threads attempting to call
synchronized methods must wait. When a synchronized method finishes
executing, the lock on the object is released and the monitor lets the
highest-priority ready thread attempting to call a synchronized method on
the object to proceed.
A thread which, for some reason, cannot continue executing, can call the
wit method which will make the thread to go into the waiting state. This will
provide an opportunity for other threads to work on the monitor object.
Object Oriented Programming in Java 99
Multi-threading 23
When a thread executing a synchronized method finishes, it can call the
notify method to tell a waiting thread to become ready. The method
notifyAll is used when there are more than two waiting threads in
contention.
Methods wait, notify and notifyAll are all inherited from the class Object;
this implies that every type of object can be a monitor.
Threads in the waiting state for a monitor object must explicitly be
awakened with a notify/notifyAll ( or interrupt ) method, or the thread will
wait forever. This may result in deadlock. In your multi-threaded
programs, you need to make sure that every wait call has a corresponding
notify or notifyAll call.
It is an error to call the wait, notify and notifyAll methods on a monitor
object with having obtained a lock on the object. Otherwise, an
IllegalMonitorStateException will be thrown.
Object Oriented Programming in Java 100
Multi-threading 24
Some reasons for using threads are:
- Make the UI of your programs more responsive
Event-driven UI toolkits, such as AWT and Swing, have an event thread
that processes UI events such as keystrokes and mouse clicks.
AWT and Swing programs attach event listeners to UI objects. These
listeners are notified when a specific event occurs, such as a button being
clicked. Event listeners are called from within the AWT event thread.
If an event listener were to perform a lengthy task, such as checking
spelling in a large document, the event thread would be busy running the
spelling checker, and thus would not be able to process additional UI
events until the event listener completed. This would make the program
appear to freeze, which is disconcerting to the user.
Object Oriented Programming in Java 101
Multi-threading 25
To avoid stalling the UI, the event listener should hand off long tasks to
another thread so that the AWT thread can continue processing UI events
(including requests to cancel the long-running task being performed) while
the task is in progress.
- take advantage of multi-processor systems
Multiprocessor (MP) systems are much more common than they used to
be. Once they were found only in large data centers and scientific
computing facilities. Now many low-end server systems -- and even some
desktop systems -- have multiple processors.
Modern operating systems, including Linux, Solaris, and Windows
NT/2000, can take advantage of multiple processors and schedule threads
to execute on any available processor.
The basic unit of scheduling is generally the thread; if a program has only
Object Oriented Programming in Java 102
Multi-threading 26
one active thread, it can only run on one processor at a time. If a program
has multiple active threads, then multiple threads may be scheduled at
once. In a well-designed program, using multiple threads can improve
program throughput and performance.
-simplifying modeling problems (servers, games,…)
In some cases, using threads can make your programs simpler to write and
maintain. Consider a simulation application, where you simulate the
interaction between multiple entities. Giving each entity its own thread can
greatly simplify many simulation and modeling applications. Or consider a
server program which has to respond to multiple simultaneous connections
from clients.
- background processing
Server applications get their input from remote sources, such as sockets.
When you read from a socket, if there is no data currently available, the
Object Oriented Programming in Java 103
Multi-threading 27
call to read input from the socket will block until data is available.
If a single-threaded program were to read from the socket, and the entity
on the other end of the socket were never to send any data, the program
would simply wait forever, and no other processing would get done. On the
other hand, the program could poll the socket to see if data was available,
but this is often undesirable for performance reasons.
If, instead, you created a thread to read from the socket, the main thread
could perform other tasks while the other thread waited for input from the
socket. You can even create multiple threads so you can read from
multiple sockets at once. In this way, you are notified quickly when data is
available (because the waiting thread is awakened) without having to poll
frequently to check if data is available. The code to wait on a socket using
threads is also much simpler and less error-prone than polling would be.
Object Oriented Programming in Java 104
Multi-threading 28
While threads can greatly simplify many types of applications, overuse of
threads can be hazardous to your program's performance and its
maintainability. Threads consume resources. Therefore, there is a limit on
how many threads you can create without degrading performance.
In particular, using multiple threads will not make a CPU-bound program
run any faster on a single-processor system.
A deadlock is a situation where two or more threads cannot proceed with
execution, for example when all are in the waiting state. Deadlock are
quite common in large multi-threaded programs and there is no easy
solution to avoid them. They usually occur as a result of careless
programming.
Thread synchronization and deadlocks are important subjects in many
fields of computer science (operating systems, programming, parallel and
distributed systems) and have been well researched.
Object Oriented Programming in Java 105
Wrapper Classes
They say that Java is a pure object-oriented programming language.
Everything is an object. Not quite so, you may say?? Because of the
primitive data types. Many algorithms, data structures and methods in the
Java API libraries only operate on objects. They cannot operate on
primitive data.
Wrapper classes are designed to wrap around the primitive data and
produce object versions of those primitive types. These classes also have
static methods for working with primitive types. You have already used the
Integer wrapper class when converting/parsing strings to integers.
The Character class, for example, provides the following methods:
static boolean isDigit(char ch);
static boolean isLetter(char ch)
static boolean isLetterOrDigit(char ch)
static boolean isLowerCase(char ch)
static boolean isWhitespace(char ch)
Wrapper classes will be extensively used in the next section. (Collections)
Object Oriented Programming in Java 106
Collections
You can create complex data structures (linked lists, queues, stack,
trees…) in Java using objects and object references and by using heap
memory with the new operator.
But like C++, Java supports something called the Java Collections
Framework, which provides the programmer with pre-packaged data
structures as well as algorithms to work on those data structures.
Java collections are similar to C++ STL. Here, we will look at interfaces,
implementation classes, algorithms, and iterators.
The Java Collections Framework provides you with ready components to
use. You don’t have to reinvent the wheel. The collections are
standardized so they can easily be shared; they also encourage reusability.
The collections can hold any type of data; what’s more, a collection can
hold objects/elements of different types.
Object Oriented Programming in Java 107
Collections 2
A collection is a data structure (an object) that can hold other objects.
The collection interfaces define the operations that can be performed on
each type of collection . The collections implementations implement these
operations in particular ways to provide customized solutions.
The most common interfaces in the framework are: Set, List. They both
extend the root Collection interface. The Collection interface provides
basic methods to manipulate collection objects. The framework also
includes the Map interface for data structures containing both value and
keys. Programmers can implement these interfaces specific to their
application needs.
As well as the above interfaces, the framework also contains other
interfaces useful when working with collection objects. The classes and
interfaces of the collections framework are all members of the java.util
package.
Object Oriented Programming in Java 108
Collections 3
One of the classes in the framework is the class Arrays which provides
static methods to manipulate arrays. You have seen this class before.
The methods of this class are overloaded to work on both arrays of
primitive types and objects. Here is a program which demonstrates some
the more common methods of this class: (Only the main method is shown)
public static void main(String[] arg){
int[] a={3,1,2}; int[] b={1,2,3};
if(Arrays.equals(a,b))
System.out.println("Equal");
Arrays.fill(a, 5);
Arrays.sort(a);
//return index of 4 in array
System.out.println(Arrays.binarySearch(a,4));
for(int i=0; i<3; i++)
System.out.println(a[i]);
}
Object Oriented Programming in Java 109
Collections 4
The Collection interface provides methods (operations) common to all
collection objects such as: adding, clearing, comparing, determining a
collection’s size… There is also a class called Collections which contains
static methods to manipulate collections polymorphically.
A List is an ordered collection that may contain duplicate values. Like
arrays, Lists are zero based. Interface List is implemented by three classes
in the framework: ArrayList, LinkedList and Vector.
The following program demonstrates the ArrayList class:
import java.util.*;
public class myArrayList{
public static void main(String[] arg){
ArrayList aList=new ArrayList();
aList.add("Xyz");
Object Oriented Programming in Java 110
Collections 5
aList.add(new Integer(1));
aList.add(new Double(2.5));
aList.add(new Integer(3));
aList.add(2,new Integer(6));
System.out.println(aList.get(1));
System.out.println(aList.size());
System.out.println(aList.indexOf("Xyz"));
Iterator j=aList.iterator();
while(j.hasNext())
if(j.next() instanceof String)
j.remove();
System.out.println(aList.size());
for(int i=0; i<aList.size(); i++)
System.out.println(aList.get(i));
}
}
Object Oriented Programming in Java 111
Collections 6
The programs: first creates an ArrayList object and then using the
method add, appends or adds some elements to the list. More specifically,
it adds a string, an integer, a double, another double, and one last integer.
The last method takes two parameters, the first one specifies the position in
the list where the element will be stored. The previous element at the
position and all subsequent elements will be shifted to the right.
The get method takes the index of an element as a parameter and returns
that element. An IndexOutOfBoundsException exception will be
thrown if you provide an out of range index. The size method returns the
size of the ArrayList object.
The method indexOf the index of the first occurrence of the argument in
this list; returns -1 if the object is not found.
The next line, creates an iterator object which can be used to iterate through
collection objects. The iterator object has only three methods:
Object Oriented Programming in Java 112
Collections 7
hasNext checks to see if there are more elements in the list. Next returns
the next element in the list and remove removes the current element
reference by the iterator object.
Each ArrayList instance has a capacity. The capacity is the size of the
array used to store the elements in the list. It is always at least as large as
the list size. As elements are added to an ArrayList, its capacity grows
automatically. The ArrayList class has another constructor which takes a
parameter to specify the initial capacity of the list:
ArrayList(int initialCapacity)
This constructs an empty list with the specified initial capacity.
Notice that the ArrayList can hold objects of any type, as you saw in this
example. You cannot, however, directly store primitive type data like
integers and doubles in the list.
Object Oriented Programming in Java 113
Collections 8
Some useful ArralyList methods are:
- boolean addAll(Collection c) //group operation
Appends all of the elements in the specified Collection to the end of this
list, in the order that they are returned by the specified Collection's Iterator.
-boolean contains(Object elem)
Returns true if this list contains the specified element.
- boolean isEmpty()
Tests if this list has no elements.
-Object remove(int index)
Removes the element at the specified position in this list.
-Object set(int index, Object element)
Replaces the element at the specified position in this list with the specified
element.
Object Oriented Programming in Java 114
Collections 9
-Object[] toArray()
Returns an array containing all of the elements in this list in the correct
order.
-void trimToSize()
Trims the capacity of this ArrayList instance to be the list's current size.
For a complete coverage of the methods of this class, consult the JDK
documentation or a textbook.
The next collection implementation we are going to look at is the LinkedList
class.
A LinkedList, like an ArrayList also implements the List interface
but is more efficient for situations where you would insert/remove elements
in the middle of a sequence. Removing and inserting elements in the
Object Oriented Programming in Java 115
Collections 10
middle of an array, Vector or ArrayList are very expensive operations. The
LinkedList implementation does not suffer form this drawback. Because its
elements/object references are not stored sequentially. This class can also
be used to represent different types of queues and stacks.
LinkedList staff=new LinkedList();
staff.add(“ Xyz ”);
staff.add(“ Wyz ”);
staff.add(“ Zyz ”);
Staff.add(2,” Third ”);
Staff.remove(“ Wyz ”);
iterator it=staff.iterator();
for(int i=0; i<3; i++)
System.out.println(it.next());
This would output: Xyz Third Zyz
Object Oriented Programming in Java 116
Collections 11
But a linked list object in Java has references to both the next element and
the previous element. The Iterator interface we saw earlier only has a
forward reference to the next element. To facilitate bi-directional traversing
of linked list, Java provides the ListIterator interface.
LinkedList staff=new LinkedList();
staff.add(“ Xyz ");
staff.add(“ Wyz "); staff.add(“ Zyz ");
staff.add(2,“ Third ");
staff.remove(“ Wyz ");
ListIterator lt=staff.listIterator();
for(int i=0; i<staff.size(); i++)
System.out.println(lt.next());
for(int i=0; i<staff.size(); i++)
System.out.println(lt.previous());
The output: Xyz Third Zyz Zyz Third Xyz
Object Oriented Programming in Java 117
Collections 12
You can use the set method to change the value of an element of a list:
staff.set(0,"One");
Or you can use the listIterator:
Object oldValue=it.next();
it.set(newvalue);
The following program creates two linked lists, merges them and then removes
every second element from the second list. Finally the program removes all
methods that exist in the second list from the first list:
public class LinkedListTest
{ public static void main(String[] args)
{
List a = new LinkedList();
a.add("ABC"); a.add("DEF"); a.add("GHI");
List b = new LinkedList();
b.add("JKL"); b.add("MNO"); b.add("PQR"); b.add("STU");
Object Oriented Programming in Java 118
Collections 13
// merge the words from b into a
ListIterator aIter = a.listIterator();
Iterator bIter = b.iterator();
while (bIter.hasNext())
{ if (aIter.hasNext()) aIter.next();
aIter.add(bIter.next());
}
System.out.println(a);
// remove every second word from b
bIter = b.iterator();
while (bIter.hasNext())
{ bIter.next(); // skip one element
if (bIter.hasNext())
{ bIter.next(); // skip next element
bIter.remove(); // remove that element
}
}
Object Oriented Programming in Java 119
Collections 14
System.out.println(b);
// bulk operation: remove all words in b from a
a.removeAll(b);
System.out.println(a);
}
}
The program outputs:
You should use a linked list only when you have to perform many
insertions/deletions of elements in the middle of a list. In other cases, you
should use an ArrayList, as it is more efficient.
Object Oriented Programming in Java 120
Collections 15
The Java Collections Framework does not have any classes/interfaces for
queues and stacks. But it has several methods which cab used to view a
LinkedList as a queue or stack:
void addFirst(Object ob);
void addLast(Object ob);
Object getFirst();
Object getLast();
Object removeFirst();
Object removeLast();
LinkedList queue = ...; //First-In-First-Out
queue.addFirst(element);
Object object = queue.removeLast();
LinkedList stack = ...; //First-In-Last-Out
stack.addFirst(element);
Object object = stack.removeFirst();
Object Oriented Programming in Java 121
Collections 16
The root interface of the collections hierarchy is the Collection interface;
this interface contains methods common to all collection implementations as
we saw. This interface also includes methods for performing mathematical
operations on collections (when viewed as sets):
addAll(Collection c); //True if the collection changed
Adds all of the elements in the specified collection to this collection.
containsAll(Collection c); //subset operation
Returns true if this collection contains all of the elements in the specified
collection.
removeAll(Collection c); //True if the collection changed
Removes all this collection's elements that are also contained in the
specified collection.
retirnAll(Collection c);
Retains only the elements that are contained in the specified collection
Object Oriented Programming in Java 122
Collections 17
A set is a collection of objects in which duplicates are not allowed. “It
makes no guarantees as to the iteration order of the set; in particular, it
does not guarantee that the order will remain constant over time. “ (JDK)
In Java, the Set interface is implemented by two concrete classes:
HashSet and TreeSet. The following example demonstrates both classes:
Set set = new HashSet();
set.add("Elizabeth"); set.add("Bernadine");
set.add("Elizabeth"); //duplicate rejected
set.add("Gene"); System.out.println(set);
Set sortedSet = new TreeSet(set);
sortedSet.add("Romeo"); //automatically sorted
sortedSet.add("Alice"); sortedSet.add("Juliet");
System.out.println(sortedSet);
The output:
Object Oriented Programming in Java 123
Collections 18
You can make a collection un-modifiable or read-only. The Collection class
provides the following methods to create such collections:
Collection unmodifiableCollection(Collection c);
List unmodifiableList(List list) ;
Set unmodifiableSet(Set set) ;
The following code illustrates the use of third method:
Set set = new HashSet();
set.add("Bernadine");
set.add("Elizabeth");
set.add("Gene");
set.add("Elizabeth");
set=Collections.unmodifiableSet(set);
set.add("test");
The last statement will throw an UnsupportedOperationException
exception. The collection is read-only.
Object Oriented Programming in Java 124
Collections 19
Collection objects are not thread-safe. That is, if multiple threads attempt
to access a collection object simultaneously, the object must be
synchronized externally. Or, you could use the following methods to create
synchronized collection objects:
Collection synchronizedCollection(Collection c);
List synchronizedList(List list) ;
Set synchronizedSet(Set set) ;
Unlike when making a collection read-only, you synchronize the collection
immediately after creating it. You also must make sure you do not retain a
reference to the original collection, or else you can access the collection
unsynchronized. The simplest way to make sure you don't retain a
reference is to never create one:
Set set = Collection.synchronizedSet(new HashSet());
Making a collection un-modifiable also makes a collection thread-safe, as
the collection can't be modified. This avoids the synchronization overhead.
Object Oriented Programming in Java 125
Collections 20
The Map interface describes a mapping from keys to values, without
duplicate keys, by definition. It is like a database table which has no two
tuples with the same primary key ( key). In a map, there cannot be
duplicate keys; each key can map to at most one value. But the mapped
values can have duplicates.
The Map interface methods can be broken down into three sets of
operations: altering, querying, and providing alternative views.
The alteration operations allow you to add and remove key-value pairs
from the map. Both the key and value can be null:
Object put(Object key, Object value);
Object remove(Object key) ;
void putAll(Map mapping) ; void clear() ;
The query operations allow you to check on the contents of the map:
Object get(Object key) ;
boolean containsKey(Object key) ;
Object Oriented Programming in Java 126
Collections 21
boolean containsValue(Object value) ;
int size() ; boolean isEmpty() ;
The last set of methods allow you to work with the group of keys or values
as a collection.
public Set keySet();
public Collection values();
Since the collection of keys in a map must be unique, you get a Set back.
Since the collection of values in a map may not be unique, you get a
Collection back.
The Collections Framework provides two general-purpose Map
implementations: HashMap and TreeMap . As with all the concrete
implementations, which implementation you use depends on your specific
needs. For inserting, deleting, and locating elements in a Map, the HashMap
offers the best alternative. If, however, you need to traverse the keys in a
sorted order, then TreeMap is your better alternative. Using a HashMap
requires that your own classes have a well-defined
Object Oriented Programming in Java 127
Collections 22
hashCode() implementation. With the TreeMap implementation, elements
added to the map must be sortable (implement the comparable interface).
Map map = new HashMap();
Integer ONE = new Integer(1);
for (int i=0, n=args.length; i<n; i++) {
String key = args[i];
Integer frequency = (Integer)map.get(key);
System.out.println(frequency);
if (frequency == null) { frequency = ONE;}
else { int value = frequency.intValue();
frequency = new Integer(value + 1); }
map.put(key, frequency);
}
System.out.println(map);
Map sortedMap = new TreeMap(map);
System.out.println(sortedMap);
Object Oriented Programming in Java 128
URL Class
Definition: URL is an acronym for Uniform Resource Locator and is a
reference (an address) to a resource on the Internet. An example of a
URL is the following:
http://soft-eng.net/default.asp
The first part of the URL specifies a protocol, in this case it is the WWW
HTTP protocol. The second part specifies the resource name. The
resource name itself consists of the following sub-parts:
host: soft-eng.net
file name: default.asp
port no.: The port number to connect to (typically optional)
reference: a reference to named anchor within a resource that
usually identifies a specific location within a file. (none here)
The next example will demonstrate how to create and read from a URL:
Object Oriented Programming in Java 129
URL Class 2
Import java.net.*;
Import java.io.*;
Public class URLReader {
public static void main(String[] args) throws
Exception {
URL home=new URL(http://toshiba2/index.htm);
BufferedReader in=new BufferedReader(new
InputStreamReader(home.openStream()));
String inputLine;
while((inputLine=in.readLine()) !=null)
System.out.println(inputLine);
in.close();
}
}
Object Oriented Programming in Java 130
URL Class 3
Another example involving URLs:
import java.net.*; import java.io.*;
public class ParseURL {
public static void main(String[] args) throws
Exception {
URL aURL=new URL(http://soft-eng.net:80/final
year/assign1.asp);
System.out.println(“protocol: “ +
aURL.getProtocol());
System.out.println(“host: “+ aURL.getHost());
System.out.println(“filename: “ + aURL.getFile());
System.out.println(“port: “ + aURL.getPort());
System.out.println(“ref: “ + aURL.getRef());
}
}
Object Oriented Programming in Java 131
URL Class 4
This is the output of the previous program:
Protocol = http
Host = soft-eng.net
Filename = /final year/assign1.asp
Port = 80
Ref = null
You will probably need this class for your assignment. As you can see, this
class provides very useful functionality to work with web pages and web
addresses or URLs!
You will probably also need to work with strings in your assignment. The
next three slides will provide a brief recap of different types of strings in
Java.
Object Oriented Programming in Java 132
More on Strings
A string variable/object is immutable which means that once a string is
created, it cannot be changed. Each time a string is modified, a new string
is created. The following example illustrates:
String str=“Yes”;
str
str=“No”; str
Object Oriented Programming in Java 133
Yes
Yes
No
More on Strings 2
Java also provides a StringBuffer class which is not immutable and can be
more efficient for code that does a lot of string manipulation. A string buffer
implements a mutable sequence of characters. A string buffer is like a String,
but can be modified.
StringBuffer sb=new StringBuffer(“LLM");
sb.setCharAt(0,‘K'); //”KLM”
You couldn’t do this with a string object. There is also another useful class
called StrignTokenizer which can be used to break strings into smaller
strings:
BufferedReader br=new BufferedReader (new
FileReader("test.txt"));
String line=br.readLine();
StringTokenizer st=new StringTokenizer(line);
Object Oriented Programming in Java 134
More on Strings 3
while(st.hasMoreTokens())
System.out.println(st.nextToken());
The previous code fragment would open a file (test.txt), read the first line
and using a StringTokenizer object, the line would be broken into
several smaller strings.
The default delimiter is a space but you can specify any other character as
a delimiter (or even specify multiple delimiter characters in a string):
StringTokenizer st=new StringTokenizer(line,“ ,.n”);
This class can be useful when retrieving data from delimited text files. It
relieves the programmer from having to do the extraction process
manually. For more information on
Strings: C:jdk1.4docsapijavalangString.html
StringBuffer: C:jdk1.4docsapijavalangStringBuffer.html
StringTokenizer: C:jdk1.4docsapijavautilStringTokenizer.html
Object Oriented Programming in Java 135
Java Native Interfaces
The Java Native Interfaces (JNI) allow Java code that runs within a Java
Virtual Machine (JVM) to operate with applications and libraries written in
other programming languages, such as C, C++ and assembly.
Programmers use the JNI to write native methods to handle those
situations where an application cannot be written entirely in the Java
language. For example, you may need to use native methods and JNI in
the following situations:
-The standard Java class library may not support the platform-dependent
features needed by your application.
- you may already have a library or application written in another
programming language and you wish to make it accessible to Java
applications.
- You may want to implement a small portion of time-critical code in a
lower-level language, such as assembly, and then have your Java
application call this code.
Object Oriented Programming in Java 136
Java Native Interfaces 2
Writing native methods for Java programs is a multi-step process:
1- begin by writing the Java program. Create a Java class that declares the
native method; this class contains the signature or the declaration for the
native method/s. It also contains the main method which calls the native
method.
2- Compile the Java class that contains the native method and the main
method.
3- Generate a header file for the native method suing javah with the native
interface flag –jni. This header file will contain the formal signature for your
native method.
4- write the implementation of the native method in the language of your
choice, such as C, C++
5- compile the header and implementation files into a shared library file.
6- Run the Java program.
We will start with an example that uses C++’s clear screen function.
Object Oriented Programming in Java 137
Java Native Interfaces 3
Here is the step-by-step process:
1- create a class (MyNative.java) that declares the native method:
Public class MyNative{
public static void main(String[] args) {
System.out.println(This line will soon disappear”);
clearScreen();
}
public native static void clearScreen();
static{
System.loadLibrary(“clearScreenLibrary”);
}
}
Object Oriented Programming in Java 138
Java Native Interfaces 4
2- Compile the class MyNative.java to produce MyNative.class
3- Use Javah –jni MyNative to create C/C++ header file (MyNative.h)
Containing the declaration for the native method.
4-write the C/C++ implementation of the native method and include the
function prototype produced in the header file:
#include “MyNative.h”
#include <stdlib.h>
extern “C”
JNIEXPORT void JNICALL Java_MyNative_clearScreen
(JNIEnv *, jclass)
{
system(“cls”);
}
5- Compile the C/C++ implementation into a native library, creating the
clearScreenLibrary.dll.
Object Oriented Programming in Java 139
Java Native Interfaces 5
In step 5, you create a dll library using the following C/C++ compiler
command:
cl –Ic:jdkinclude –Ic:jdkincludewin32 –LD
Filename.cpp –FeDLLFileName
This simple exmaple only had one C++ methdo but you could have a whole
library of native methods in a file and compile them all into a dll file to be
used by Java programs.
Since you will need to use the Windows command-interpreter a few times,
you should execute the following command before starting any other
commands:
vcvars32.bat
This command is located in the bin directory of VC98 directory of Visual
Studio.
Object Oriented Programming in Java 140
Object Serialization
Object serialization is about saving objects to streams for later use. You have
seen how to store textual data to a disk or to a network stream. But in object-
oriented programs, you would be mainly dealing with objects and it would be
very helpful if there was a way to write/read whole objects into streams. Object
serialization does just that.
Of course, you could achieve this by manually saving object information (object
type, object data…), but this very tedious, especially when dealing with objects
in an inheritance hierarchy. Object serialization allows the programmer to
effortlessly deal with the problems of writing/reading objects to streams. Most
tasks are automated.
Use object serialization to: for RMI communication and object persistence.*
A class must implement the Serializable interface for its objects to be
saved and restored by serialization. This interface has no methods.
Object Oriented Programming in Java 141
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics
Advanced Java Topics

More Related Content

What's hot

C++ OOP Implementation
C++ OOP ImplementationC++ OOP Implementation
C++ OOP ImplementationFridz Felisco
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp PresentationVishwa Mohan
 
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual Abdul Hannan
 
Overview of c++
Overview of c++Overview of c++
Overview of c++geeeeeet
 
Introduction to c_sharp
Introduction to c_sharpIntroduction to c_sharp
Introduction to c_sharpHEM Sothon
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Akhil Mittal
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#Hawkman Academy
 
Difference between Java and c#
Difference between Java and c#Difference between Java and c#
Difference between Java and c#Sagar Pednekar
 
C++ to java
C++ to javaC++ to java
C++ to javaAjmal Ak
 
First draft programming c++
First draft programming c++First draft programming c++
First draft programming c++藝輝 王
 

What's hot (20)

Basics1
Basics1Basics1
Basics1
 
1 puc programming using c++
1 puc programming using c++1 puc programming using c++
1 puc programming using c++
 
C++ OOP Implementation
C++ OOP ImplementationC++ OOP Implementation
C++ OOP Implementation
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
 
Overview of c++
Overview of c++Overview of c++
Overview of c++
 
Introduction to c_sharp
Introduction to c_sharpIntroduction to c_sharp
Introduction to c_sharp
 
Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
 
Deep C
Deep CDeep C
Deep C
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Java chapter 3
Java   chapter 3Java   chapter 3
Java chapter 3
 
C# in depth
C# in depthC# in depth
C# in depth
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Difference between Java and c#
Difference between Java and c#Difference between Java and c#
Difference between Java and c#
 
Introduction to programing languages part 1
Introduction to programing languages   part 1Introduction to programing languages   part 1
Introduction to programing languages part 1
 
C++ to java
C++ to javaC++ to java
C++ to java
 
C sharp
C sharpC sharp
C sharp
 
First draft programming c++
First draft programming c++First draft programming c++
First draft programming c++
 

Viewers also liked

java training in chennai
java training in chennaijava training in chennai
java training in chennaisanjai rsamy
 
Unas Almas-Mila
Unas Almas-MilaUnas Almas-Mila
Unas Almas-Milanomadan
 
16coolnightshotjazzposterletterAI9
16coolnightshotjazzposterletterAI916coolnightshotjazzposterletterAI9
16coolnightshotjazzposterletterAI9Tracy Drissell
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentationVeeru Reddy
 
Childhood psychiatry
Childhood psychiatryChildhood psychiatry
Childhood psychiatryAbdo_452
 
MS-11 JAN JUNE 2016 SOLVED ASSIGNMENT
MS-11 JAN JUNE 2016 SOLVED ASSIGNMENTMS-11 JAN JUNE 2016 SOLVED ASSIGNMENT
MS-11 JAN JUNE 2016 SOLVED ASSIGNMENTDharmendra Sikarwar
 
MS-52 JAN JUNE 2016 SOLVED ASSIGNMENT
MS-52 JAN JUNE 2016 SOLVED ASSIGNMENTMS-52 JAN JUNE 2016 SOLVED ASSIGNMENT
MS-52 JAN JUNE 2016 SOLVED ASSIGNMENTDharmendra Sikarwar
 

Viewers also liked (12)

java training in chennai
java training in chennaijava training in chennai
java training in chennai
 
Ets 161102005340
Ets 161102005340Ets 161102005340
Ets 161102005340
 
Daniel tovar 10
Daniel tovar 10Daniel tovar 10
Daniel tovar 10
 
Unas Almas-Mila
Unas Almas-MilaUnas Almas-Mila
Unas Almas-Mila
 
16coolnightshotjazzposterletterAI9
16coolnightshotjazzposterletterAI916coolnightshotjazzposterletterAI9
16coolnightshotjazzposterletterAI9
 
Sevillana
SevillanaSevillana
Sevillana
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentation
 
Childhood psychiatry
Childhood psychiatryChildhood psychiatry
Childhood psychiatry
 
MS-11 JAN JUNE 2016 SOLVED ASSIGNMENT
MS-11 JAN JUNE 2016 SOLVED ASSIGNMENTMS-11 JAN JUNE 2016 SOLVED ASSIGNMENT
MS-11 JAN JUNE 2016 SOLVED ASSIGNMENT
 
MS-52 JAN JUNE 2016 SOLVED ASSIGNMENT
MS-52 JAN JUNE 2016 SOLVED ASSIGNMENTMS-52 JAN JUNE 2016 SOLVED ASSIGNMENT
MS-52 JAN JUNE 2016 SOLVED ASSIGNMENT
 
Calculus
CalculusCalculus
Calculus
 
LedZep
LedZepLedZep
LedZep
 

Similar to Advanced Java Topics

Socket Programming by Rajkumar Buyya
Socket Programming by Rajkumar BuyyaSocket Programming by Rajkumar Buyya
Socket Programming by Rajkumar BuyyaiDhawalVaja
 
How a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdfHow a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdfarccreation001
 
Networking in java, Advanced programming
Networking in java, Advanced programmingNetworking in java, Advanced programming
Networking in java, Advanced programmingGera Paulos
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket ProgrammingMousmi Pawar
 
socket-programming.pptx
socket-programming.pptxsocket-programming.pptx
socket-programming.pptxRubenAssandja
 
Chat server nitish nagar
Chat server nitish nagarChat server nitish nagar
Chat server nitish nagarNitish Nagar
 
maXbox Arduino Tutorial
maXbox Arduino TutorialmaXbox Arduino Tutorial
maXbox Arduino TutorialMax Kleiner
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docxhanneloremccaffery
 
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxkacie8xcheco
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenVannaSchrader3
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxalfredacavx97
 
Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project ReportKavita Sharma
 
692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded wsmile790243
 
Java Networking
Java NetworkingJava Networking
Java NetworkingSunil OS
 
Arduino LED maXbox starter18_3
Arduino LED maXbox starter18_3Arduino LED maXbox starter18_3
Arduino LED maXbox starter18_3Max Kleiner
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Javasuraj pandey
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat applicationSamsil Arefin
 

Similar to Advanced Java Topics (20)

Socket programming
Socket programmingSocket programming
Socket programming
 
Socket Programming by Rajkumar Buyya
Socket Programming by Rajkumar BuyyaSocket Programming by Rajkumar Buyya
Socket Programming by Rajkumar Buyya
 
How a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdfHow a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdf
 
Socket
SocketSocket
Socket
 
Networking in java, Advanced programming
Networking in java, Advanced programmingNetworking in java, Advanced programming
Networking in java, Advanced programming
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
socket-programming.pptx
socket-programming.pptxsocket-programming.pptx
socket-programming.pptx
 
Chat server nitish nagar
Chat server nitish nagarChat server nitish nagar
Chat server nitish nagar
 
maXbox Arduino Tutorial
maXbox Arduino TutorialmaXbox Arduino Tutorial
maXbox Arduino Tutorial
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
 
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
 
Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project Report
 
692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Arduino LED maXbox starter18_3
Arduino LED maXbox starter18_3Arduino LED maXbox starter18_3
Arduino LED maXbox starter18_3
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Java
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
 

More from Salahaddin University-Erbil (6)

C++ for beginners
C++ for beginnersC++ for beginners
C++ for beginners
 
HTML for beginners
HTML for beginnersHTML for beginners
HTML for beginners
 
Reporter 6 web
Reporter  6 webReporter  6 web
Reporter 6 web
 
Object-Oriented Programming Using C++
Object-Oriented Programming Using C++Object-Oriented Programming Using C++
Object-Oriented Programming Using C++
 
40 Nawawi
40 Nawawi40 Nawawi
40 Nawawi
 
Olap
OlapOlap
Olap
 

Recently uploaded

Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 

Recently uploaded (20)

Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 

Advanced Java Topics

  • 1. More Programming Concepts Forth Year University of Salahaddin-Erbil College of Engineering Department of Software Engineering Karim Zebari 2003-2004
  • 2. About this course Programming courses, such as this course, usually involve a considerable amount of practical coursework or programming in the labs. You should find as much time as possible in the labs for exercises, assignments and testing in Java. The only way to really learn a new programming language is to write many programs and read other people’s programs. You have no scheduled hours in the lab for this course; you should work at least 2 hours per week in the open lab. These notes are intended to cover the bulk of this course, but you should never rely on notes ONLY. The following textbooks are recommended: 1) Java How to Program, 3rd Edition, 1999, Deitel & Deitel 2) Java The Complete Reference, 3) http://java.sun.com Java Homepage 4) http://java.sun.com/docs/books/tutorial Java Online Tutorial, also available locally Several other books are available in the department’s library/intranet. Object Oriented Programming in Java 2
  • 3. About this course 2 This half-year course will build on your previous programming courses and we will continue to use the Java programming language. The course will introduce you to more advanced programming concepts and as such will offer you a collection of topics on specialized programming areas. There will also be other computing topics discussed and practiced using Java, such as data/network security, multi-threading, etc. Some of the concepts introduced in this course may be useful for your Final Year project and these will be covered earlier on the course. You should work in the labs as much as possible. This course and some other courses, as well as your Final Year project may involve a lot of programming in a network environment. You cannot do this at home, if you have only one computer. I advice you to work very hard in this final year and develop your programming skills as much as you can. Object Oriented Programming in Java 3
  • 4. The Syllabus The following topics will be covered in this course: - Multithreading - Security in Java - Java Beans - Internationalization - Java Servlets - Java Server Pages - Database access in Java - More GUI Components & Printing - Remote Method Invocation (RMI) - Java Collections Framework Object Oriented Programming in Java 4
  • 5. Network Programming The Transmission Control Protocol or TCP provides a reliable point-to- point communication channel that clients and servers can use to communicate with one another. To communicate over TCP, a client program and a server program establish a connection to one another. Each program binds a socket to its end of the connection. To communicate, the client and the server each reads from and writes to the socket bound to the connection. A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes: Socket and ServerSocket- that implement the client side of the connection and the server side of the connection, respectively. Object Oriented Programming in Java 5 (Mostofthematerialontheseslidesistakenfromthe“TheJava Tutorial”fromSun,whichiselectronicallyavailableontheintranet)
  • 6. Network Programming 2 Generally speaking, a computer has a single physical connection to the network. All data destined for a particular computer arrives through that connection. However, the data may be intended for different applications running on the computer. So how does the computer know to which application to forward the data? Through the use of ports. Data transmitted over the Internet is accompanied by addressing information that identifies the computer and the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver data to the right computer on the network. Ports are identified by a 16-bit number, which TCP use to deliver the data to the right application. 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. A client can then talk with the server at the server's port, as illustrated ere: Object Oriented Programming in Java 6
  • 7. Network Programming 3 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. So in order to establish communication between a client and a server, we need a socket for the client and socket for the server (ServerSocket). Then we need to specify a port and bind the socket (client or server ) to this port, depending on the application. Your applications can use any ports not in the range of well-known ports. Object Oriented Programming in Java 7
  • 8. Network Programming 4 In the following example, we will write a client and a server program. The client will try to establish a connection with the server. After the connection is made between the two, the client can send strings to the server and the server will return or echo what the client sent it. We will make the server to listen on port 4444, so the client will use this port number to connect to the server. Of course, the client will also need the host name of the server. You can this this client/server application on a network or on the same computer. First the code for the client machine: import java.io.*; import java.net.*; public class EchoClient { public static void main(String[] args) throws IOException { ; Object Oriented Programming in Java 8
  • 9. Network Programming 5 Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null try { echoSocket = new Socket("toshiba", 4444); out = new PrintWriter( echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know host: toshiba."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: toshiba."); System.exit(1); } Object Oriented Programming in Java 9
  • 10. Network Programming 6 BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; System.out.println(in.readLine()); while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } out.close(); in.close(); stdIn.close(); echoSocket.close(); } } This client program works like this: it first creates a socket which will be used to connect to a machine called “toshiba” on port 4444. The prgram Object Oriented Programming in Java 10
  • 11. Network Programming 7 Then gets the socket's output stream and input stream. Notice that the same socket can be used for both input and output of data. The last statement in the while loop reads a line of information from the BufferedReader connected to the socket. The readLine method waits until the server echoes the information back to EchoClient. When readline returns, EchoClient prints the information to the standard output. The while loop continues until the user types an end-of-input character. That is, EchoClient reads input from the user, sends it to the Echo server, gets a response from the server, and displays it, until it reaches the end-of- input. The while loop then terminates and the program continues, executing the next four lines of code: Object Oriented Programming in Java 11
  • 12. Network Programming 8 out.close(); in.close(); stdIn.close(); echoSocket.close(); These lines of code fall into the category of housekeeping. A well-behaved program always cleans up after itself, and this program is well-behaved. These statements close the readers and writers connected to the socket and to the standard input stream, and close the socket connection to the server. The order here is important. You should close any streams connected to a socket before you close the socket itself. This client program is straightforward and simple because the Echo server implements a simple protocol. The client sends text to the server, and the Object Oriented Programming in Java 12
  • 13. Network Programming 9 server echoes it back. When your client programs are talking to a more complicated server such as an HTTP server, your client program will also be more complicated. However, the basics are much the same as they are in this program: 1- Open a socket. 2- Open an input stream and output stream to the socket. 3- Read from and write to the stream according to the server's protocol. 4- Close the streams. 5- Close the socket. Only step 3 differs from client to client, depending on the server. The other steps remain largely the same. Now the server application: Object Oriented Programming in Java 13
  • 14. Network Programming 10 The server program begins by creating a new ServerSocket object to listen on a specific port. When writing a server, choose a port that is not already dedicated to some other service. ServerSocket is a java.net class that provides a system-independent implementation of the server side of a client/server socket connection. The constructor for ServerSocket throws an exception if it can't listen on the specified port (for example, the port is already being used). If the server successfully connects to its port, then the ServerSocket object is successfully created and the server continues to the next step--accepting a connection from a client: clientSocket = serverSocket.accept(); The accept method waits until a client starts up and requests a connection on the host and port of this server (in this example, the server is running on the hypothetical machine taranis on port 4444). Object Oriented Programming in Java 14
  • 15. Network Programming 11 When a connection is requested and successfully established, the accept method returns a new Socket object which is bound to a new port. The server can communicate with the client over this new Socket and continue to listen for client connection requests on the ServerSocket bound to the original, predetermined port. This particular version of the program doesn't listen for more client connection requests: import java.net.*; import java.io.*; public class EchoServer { public static void main(String[] args) throws IOException{ ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: Object Oriented Programming in Java 15
  • 16. Network Programming 12 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream())); String inputLine, outputLine; out.println("Welcome to Toshiba Echo Server, Please type some string"); Object Oriented Programming in Java 16
  • 17. Network Programming 13 while ((inputLine = in.readLine()) != null) { outputLine = inputLine; out.println(outputLine); if (outputLine.equals("Bye")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); } } Run this server and attempt to connect to it with multiple clients. Only the first client will succeed. To serve multiple client connections, you must use threads. See the next server version which uses threads to serve multiple clients at the same time. Threads will be introduced in this example. Object Oriented Programming in Java 17
  • 18. Network Programming 14 In this version of the server, which is very similar to the last one, every time we know the program has established a new socket connection, that is, when the call to accept was successful, we will start a new thread to deal with the connection between the server and that client. The main program will just go back waiting for more connection requests from other clients. Here is the threaded server: import java.net.*; import java.io.*; public class MultiServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; boolean listening = true; Object Oriented Programming in Java 18
  • 19. Network Programming 15 try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(-1); } while (listening) new MultiServerThread(serverSocket.accept()).start(); serverSocket.close(); } } class MultiServerThread extends Thread { private Socket socket = null; public MultiServerThread(Socket socket) { this.socket = socket; } Object Oriented Programming in Java 19
  • 20. Network Programming 16 public void run() { try { PrintWriter out = new PrintWriter( socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String inputLine, outputLine; out.println("Welcome to Toshiba Echo Server"); while ((inputLine = in.readLine()) != null) { outputLine = inputLine; out.println(outputLine); if (outputLine.equals("Bye")) break; } out.close(); in.close(); socket.close(); } catch (IOException e) { e.printStackTrace();} } } Object Oriented Programming in Java 20
  • 21. Network Programming 17 Every time a new socket connection is established (when method accept succeeds) a new thread is created and started to take care of the new connection. Here a new class is created which extends the Thread class. Any class that subclasses the Thread class should provide override the run() method. You should not call the run method. Instead call the object’s start() method which will call the run method. You provide the desired functionality of the thread in the run method. You should realize the importance of protocols by now. Look at the last two programs again and test them. If the client and the server do not understand each other, the client/server application will not function. They cannot communicate. For this simple client/server pair, it was not necessary to specify and document a protocol but for more complicated applications, you will need to specify and develop protocols before writing you client and server programs. Who should talk first? Second? When should they disconnect?... Object Oriented Programming in Java 21
  • 22. Network Programming 18 One more point about sockets is that in real-life applications, especially on a large network like the Internet, your programs may hang for a long time. For example a host is unreachable, your program will wait a long time and be at the mercy of the underlying operating system to time out the connection. To avoid such a situation, you can set a time-out value for your applications using the method setSoTimeout in milliseconds: Socket s=new Socket(…….); s.setSoTimeout(10000); There is a problem with this though. What if the Socket constructor itself can block indefinitely? The solution to this is to construct the socket in a separate thread and wait for that thread to complete or timeout. Object Oriented Programming in Java 22
  • 23. Network Programming 19 Internet addresses or IP addresses consist of four byes such as 122.23.132.167. There is a unique IP address for each Internet host. This gives about 4.2 billion hosts. Host names domain names can be used instead of Internet addresses as they are easier for humans to remember. For example, it is a lot easier to remember java,sun.com than 192.18.97.71. Java has a class called InetAddress which can be used to convert between host names and Internet addresses. The static method getByName returns an IntetAddress of a host: InetAddress address=InetAddress.getByName(“java.sun.com”); This will return an InetAddress object that contains the sequence of four bytes: 192.18.97.71. To access the byes use the getBytes method: byte[] addressBytes=address.getBytes(); Object Oriented Programming in Java 23
  • 24. Network Programming 20 Lets see a program that will convert any host name into an Internet address: import java.net.*; public class InetAddressTest { public static void main(String[] args) { try { String host = "java.sun.com"; InetAddress address = InetAddress.getByName(host); System.out.println(address); } catch (Exception e) { System.out.println("Error: " + e); } } } Object Oriented Programming in Java 24
  • 25. Network Programming 21 Now we will look at another example in which an applet is used to communicate with a running server on another machine (could be the same machine). First the client applet: import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; public class NetApplet extends JApplet implements ActionListener { TextField numbField; Label display; Socket socket; Object Oriented Programming in Java 25
  • 26. Network Programming 22 public void init() { try { socket = new Socket("toshiba",8765); } catch (UnknownHostException e) { System.out.println("Unknown host"); } catch (IOException e) { System.out.println("IO Exception"); } getContentPane().setLayout(new FlowLayout()); numbField = new TextField(6); getContentPane().add(numbField); Button button = new Button("Send"); getContentPane().add(button); button.addActionListener(this); display = new Label("No number"); getContentPane().add(display); } Object Oriented Programming in Java 26
  • 27. Network Programming 23 public void actionPerformed(ActionEvent e){ int numb = 0; String numbStr = null; BufferedReader fromServer = null; PrintWriter toServer = null; if (e.getSource()==button){ try { numb = Integer.parseInt(numbField.getText()); } catch (NumberFormatException ex){ JOptionPane.showMessageDialog(this, " Number Format Exception", "Results", JOptionPane.PLAIN_MESSAGE); } Object Oriented Programming in Java 27
  • 28. Network Programming 24 try{ fromServer = new BufferedReader(new InputStreamReader (socket.getInputStream())); toServer =new PrintWriter(socket.getOutputStream(), true); } catch (IOException ex){ System.out.println("IO Exception"); } toServer.println(numb); Try { numbStr = fromServer.readLine(); } catch (IOException ex){ System.out.println("Applet receive failed:"); } display.setText(numbStr); } } Object Oriented Programming in Java 28
  • 29. Network Programming 25 The applet would look like something like this: After creating a socket, the applet parses and sends the text field value to the server through an output stream. It then waits until it receives a result from the server. The result is then placed in the label next to the text field. The server: The server is much simpler than the client. Usually servers do not have any GUI components. They just listen for client requests in the background. After receiving a connection request and accepting it, the server identifies the requesting client and if it is a certain client, it is disconnected. If not it increments the integer it received and sends it back. Object Oriented Programming in Java 29
  • 30. Network Programming 26 public class NetServer { public static void main(String[] args) { try{ ServerSocket serverSocket = new ServerSocket(8765); Socket clientSocket = serverSocket.accept(); InetAddress remote=clientSocket.getInetAddress(); if(remote.getHostName().equals("toshiba")) clientSocket.close(); BufferedReader fromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter toClient = new PrintWriter(clientSocket.getOutputStream(), true); while (true) { int n=Integer.parseInt(fromClient.readLine()); System.out.println("received: " + n); toClient.println(n+1); } Object Oriented Programming in Java 30
  • 31. Network Programming 27 } catch(IOException ex) { System.err.println(ex); } } } This server will accept and serve all clients except “toshiba”. Some networks use firewalls to block traffic from certain networks. They use methods like this to block access from certain networks or addresses. They may also be used to block internal network users from accessing certain outside networks. Network programming in Java is a lot more than what we have covered in the last few slides. It is a subject of its own. This was just to give you a flavor. For more information you should consult textbooks and other material available on the net. The net is the best resource of information. Object Oriented Programming in Java 31
  • 32. Database Programming It has been estimated that half of all software development involves client/server operations and most client-server operations involve database connectivity. A database system is a repository or store of data. Database systems organize data in an orderly way making the data easily accessible and updatable. Instead of using a database, you could use an ordinary text file to store your data. But we all know how a database system management system make updating, organizing and accessing data more efficient and user-friendly. Being able to access a database through programming is also important and allows the programmer to write custom applications. Software users (companies, universities, governments, stores…) prefer customized software. Software that is designed to need their requirements and that is easy to use. Object Oriented Programming in Java 32
  • 33. Database Programming 2 Java supports database programming. Java Database Connectivity or JDBC is designed to provide Java programmers with a uniform way of accessing database systems. With JDBC you can access almost all current database systems (MS SQL Server, MS Access, Oracle, DB2, Informix…) JDBC works like this: database vendors provide drivers for their particular database system to work with JDBC driver manager. JDBC provides an abstraction layer on top of these drivers. Programs written according to JDBC API would talk to the JDBC driver manager, which in turn, would use the drivers that it has to talk to the actual database. Using JDBC, Java programmers can write applications to access any database, using standard SQL statements. You can use JDBC in both applications and applets but bear in mind that Object Oriented Programming in Java 33
  • 34. Database Programming 3 With applets, security restrictions would apply which mean that the applet can only access a database from the server from which it was downloaded. JDBC is an interface to SQL which is an interface to all modern relational databases. So basically, JDBC let’s you pass and execute SQL statements to databases. You should now SQL from your previous courses but here a short introduction will be presented. You can find more information on SQL on the intranet. You can think of a database as a group of named tables with rows and columns. Each column has a column name. The rows contain the actual data (records). Object Oriented Programming in Java 34
  • 35. Database Programming 4 We assume we have a small MS Access database with a single table. The program example which follow will use this database for testing. The table Students has the following design: In SQL, to select all the records from the above table you would use: SELECT * FROM Students The FROM clause tells database which table to access. Or you can restrict the columns: SELECT Name, [Coursework Mark] FROM Students Object Oriented Programming in Java 35
  • 36. Database Programming 5 To restrict the rows or records, you use the WHERE clause: SELECT * FROM Students WHERE [Coursework Mark] >40 Be careful with the “equals” sign. SQL used = and <>, not == or !=, as in Java for testing equality. You can access more than one table at the same time: SELECT * FROM Students, Departments You can also use SQL to update the data in a table: UPDATE Students SET [Coursework Mark]=[Coursework Mark] + 2 To insert values into a table, use the INSERT statement: INSERT INTO Students Values(‘hamid’,‘Hamid Husain’,‘4’,’10-Oct-1980’,‘35.5’) Note that strings are enclosed in single quotes in SQL. Object Oriented Programming in Java 36
  • 37. Database Programming 6 To create a new table: CREATE TABLE Departments ( Dept_Name CHAR(20) , Head CHAR(20), No_Of_Students INT) For details of SQL types and other statements, consult a book or the intranet page for this course. You also need to create a Data Source Name (DSN) for your Access database. You will use this DSN when you connect to the database. You can do this in the Control Panel. This will be demonstrated in the lab. We will now write a simple Java program that will access the above database : Object Oriented Programming in Java 37
  • 38. Database Programming 7 import java.sql.*; public class CreateMarks { public static void main(String args[]) { String url = "jdbc:odbc:StudentsDSN"; Connection con; String createString; createString = "select * from Students"; Statement stmt; try { //load odbc-jdbc bridge driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } Object Oriented Programming in Java 38
  • 39. Database Programming 8 try { con = DriverManager.getConnection(url, "", ""); stmt = con.createStatement(); ResultSet rs=stmt.executeQuery(createString); while(rs.next()) System.out.println(rs.getString(2) + " | " + rs.getString(3) + " | " + rs.getString(4) + " | " + rs.getString(5)); rs.close(); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println("SQLExc.:" + ex.getMessage()); } } } Object Oriented Programming in Java 39
  • 40. Database Programming 9 The string url is used to represent a protocol, here jdbc:odbc: means that JDBC interfaces Microsoft's ODBC which then connects to the database server - whose Internet address is denoted by the DSN Data Source Name StudentsDSN. This could be on another computer, in which case you would have to specify its location. A driver is needed which bridges between the Java JDBC and Microsoft's ODBC. This driver is loaded from Sun's site. Then the connection to the database, specified by URL, user name and password, is established. Finally, a statement object is created, which will allow us to pass SQL statements to the database. You create an SQL statement and pass this statement to the executeQuery method of the statement object. The result of this method is a Resultset object ( a set of tuples/records). Then we use a loop to iterate through the elements of the resultset object. Object Oriented Programming in Java 40
  • 41. Database Programming 10 You create an SQL statement and pass this statement to the executeQuery method of the statement object. The result of this method is a Resultset object ( a set of tuples/records) and does not change the state of the database. Then we use a loop to iterate through the elements of the resultset object. A resultset object is a table of data representing a database result set, which is usually generated by executing a statement that queries the database. A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set. Object Oriented Programming in Java 41
  • 42. Database Programming 11 Note that the method getString is given a number; this number represents the column number. They start with 1. You could use column names (in single quotes) instead: rs.getString(‘Name’) Or rs.getInteger(‘Year’); This program will output the 2nd , 3rd , 4th and 5th columns of each row. Earlier, we used the executeQuery method of the Statement object to execute a query which just returns a resultset and leaves the database intact. To make updates to a database you can use the executeUpdate method of the Statement object. For example, to add a new record to the Students table: stmt.executeUpdate(“INSERT INTO Students “ + “values(‘username’,‘User Name’,3,’2-Apr-03’,45)” Object Oriented Programming in Java 42
  • 43. Database Programming 12 This statement would add the record to the table. Note that it is customary to use uppercase letters for SQL keywords words. SQL is case insensitive. The executeUpdate method, unlike the executeQuery method of the JDBC alters the state of the database. We know that the executeQuery method returns a resultset. The executeUpdate method returns the number of records affected by the update operation, for example the following SQL statement would return 3: int n=stmt2.executeUpdate(“UPDATE Students SET [cousework mark]=40 where [cousework mark]<40"); System.out.println(n); Object Oriented Programming in Java 43
  • 44. Database Programming 13 You can create a new table as follows: String createTable = “CREATE TABLE Department"+ "(Dept_ID INTEGER, Dept_NAME VARCHAR(40))"; There is a lot more to JDBC than what we have looked at so far. You must know SQL to write more advanced database applications, especially when you need to access databases with many tables and when there are relationships between those tables. For more information on SQL data types and their equivalents, consult the Java documentation or other reference material. Most client/server applications involve accessing database systems over a network. You can now write useful applications that utilize both network programming and database access. Adding a GUI interface to your client- side application will make it user-friendly and easier to use. Object Oriented Programming in Java 44
  • 45. Database Programming 14 There are times when you don’t want a statement to be executed unless another statement/statements are also executed. For example, consider the following two tables: And Object Oriented Programming in Java 45
  • 46. Database Programming 15 Now suppose you would like to update the Students table by adding a new record to it. If this update operation is successful, you would also like the second table, Departments, to be updated too. Otherwise your database would be in an inconsistent state. You would want to update the value of the third column in the Departments table. A transaction is a set of one or more statements that are executed together as a unit, so either all of the statements are executed, or none of the statements is executed. When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. This is the default behavior. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode. This is demonstrated in the following line of code, where con is an active connection: con.setAutoCommit(false); Object Oriented Programming in Java 46
  • 47. Database Programming 16 Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly. All statements executed after the previous call to the method commit will be included in the current transaction and will be committed together as a unit. The following code, in which con is an active connection, illustrates a transaction: try { con = DriverManager.getConnection(url, "", ""); con.setAutoCommit(false); stmt1 = con.createStatement(); stmt2 = con.createStatement(); stmt1.executeUpdate("INSERT INTO Students values('username9','User Name 9',1, 4,'2-Apr-80',45)"); stmt2.executeUpdate("Update Department SET No_of_Student=No_of_Student+1 where Dept_ID=1"); con.commit(); con.setAutoCommit(true); Object Oriented Programming in Java 47
  • 48. Database Programming 17 con.close(); } catch(SQLException ex) { System.err.println("SQLException: " + x.getMessage()); if (con != null) { try { System.err.print("Transaction is being rolled back"); con.rollback(); } catch(SQLException excep) { System.err.print("SQLException: "); System.err.println(excep.getMessage()); } } } The code in bold constitutes a transaction or unit of execution. Here we Object Oriented Programming in Java 48
  • 49. Database Programming 18 have specified that we want all the statements in this transaction be executed as one single statement. If there is a problem and one statement cannot succeed for some reason, they we rollback that transaction in the catch statement. In this example, auto-commit mode is disabled for the connection con , which means that the two statements stmt1 and stmt2 will be committed together when the method commit is called. Whenever the commit method is called (either automatically when auto-commit mode is enabled or explicitly when it is disabled), all changes resulting from statements in the transaction will be made permanent. The first statement, stmt1, succeeds without any problems. The second statement, stmt2, includes an error and an exception is thrown and caught before the commit method is executed. Object Oriented Programming in Java 49
  • 50. Database Programming 19 As mentioned earlier, calling the method rollback aborts a transaction and returns any values that were modified to their previous values. If you are trying to execute one or more statements in a transaction and get an SQLException , you should call the method rollback to abort the transaction and start the transaction all over again. That is the only way to be sure of what has been committed and what has not been committed. Catching an SQLException tells you that something is wrong, but it does not tell you what was or was not committed. Since you cannot count on the fact that nothing was committed, calling the method rollback is the only way to be sure. In our simple example, when we add a new student’s record to the database, we would like to also update the count of students for that particular department. If for some reason, either statement couldn’t be executed, we would like to abort the whole transaction or rollback. Object Oriented Programming in Java 50
  • 51. Trees With the JTree class, you can display hierarchical data. A JTree object doesn't actually contain your data; it simply provides a view of the data. Here's a picture of a tree: As the preceding figure shows, JTree displays its data vertically. Each row displayed by the tree contains exactly one item of data, which is called a node. Every tree has a root node from which all nodes descend. By default, the tree displays the root node, but you can decree otherwise. A node can either have children or not. We refer to nodes that can have children -- whether or not they currently have children -- as branch nodes. Nodes that can't have children are leaf nodes. Branch nodes can have any number of children. Typically, the user can expand and collapse branch nodes -- making their children visible or invisible -- by clicking them. Object Oriented Programming in Java 51
  • 52. Trees 2 By default, all branch nodes except the root node start out collapsed. A program can detect changes in branch nodes' expansion state by listening for tree expansion events. The following program will create a simple tree: import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.tree.*; public class SimpleTree { public static void main(String[] args) { JFrame frame = new SimpleTreeFrame(); frame.show(); } } Object Oriented Programming in Java 52
  • 53. Trees 3 class SimpleTreeFrame extends JFrame { public SimpleTreeFrame() { setTitle("SimpleTree"); setSize(300, 200); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); // set up tree nodes first DefaultMutableTreeNode root = new DefaultMutableTreeNode("Kurdistan Region"); DefaultMutableTreeNode governorate1 = new DefaultMutableTreeNode("Erbil"); root.add(governorate1); Object Oriented Programming in Java 53
  • 54. Trees 4 DefaultMutableTreeNode town1 = new DefaultMutableTreeNode("Shaqlawa"); governorate1.add(town1); DefaultMutableTreeNode town2 = new DefaultMutableTreeNode("Koye"); governorate1.add(town2); DefaultMutableTreeNode town3 = new DefaultMutableTreeNode("Soran"); governorate1.add(town3); DefaultMutableTreeNode governorate2= new DefaultMutableTreeNode("Sulaimaniyah"); root.add(governorate2); DefaultMutableTreeNode town4= new DefaultMutableTreeNode("Rania"); governorate2.add(town4); Object Oriented Programming in Java 54
  • 55. Trees 5 DefaultMutableTreeNode town5= new DefaultMutableTreeNode("Dokan"); governorate2.add(town5); DefaultMutableTreeNode governorate3= new DefaultMutableTreeNode("Duhok"); root.add(governorate3); DefaultMutableTreeNode town6= new DefaultMutableTreeNode("Amedi"); governorate3.add(town6); DefaultMutableTreeNode town7= new DefaultMutableTreeNode("Zakho"); governorate3.add(town7); DefaultMutableTreeNode governorate4= new DefaultMutableTreeNode("Kirkuk"); root.add(governorate4); Object Oriented Programming in Java 55
  • 56. Trees 6 DefaultMutableTreeNode town8= new DefaultMutableTreeNode("Tuz-Khurmatu"); governorate4.add(town8); DefaultMutableTreeNode town9= new DefaultMutableTreeNode("Kifry"); governorate4.add(town9); // construct tree and put it in a scroll pane JTree tree = new JTree(root); Container contentPane = getContentPane(); contentPane.add(new JScrollPane(tree)); } } This is the output: As you can see, the tree does not do anything useful in response to user clicks on its nodes. Object Oriented Programming in Java 56
  • 57. Trees 7 The code creates an instance of DefaultMutableTreeNode to serve as the root node for the tree. It then creates the rest of the nodes in the tree. After that, it creates the tree, specifying the root node as an argument to the JTree constructor. Finally, it puts the tree in a scroll pane, a common tactic because showing the full, expanded tree would otherwise require too much space. Responding to tree node selections is simple. You implement a tree selection listener and register it on the tree. The following code shows the selection-related code from the SimpleTree program above: tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) return; Object Oriented Programming in Java 57
  • 58. Trees 8 if (node.isLeaf()) ta.append("Leaf node: " + node +"n"); else ta.append("Non-leaf node: "+node + "n"); } }); You can also use split pane to create two regions, one for the tree (on the left) and one for a text area, for example: (this is a horizontal split; you can make it vertical using VERTICAL_SPLIT). The following split pane object constructor takes 3 parameters: orientation, left component, right component. JSplitPane outerPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tree, ta); getContentPane().add(outerPane, "Center"); private JTextArea ta=new JTextArea(10,15); Object Oriented Programming in Java 58
  • 59. Trees 9 The previous program’s output is a follows: You can write complex and Sophisticated programs with Trees. These notes are only meant to give you a Flavor of what you can do with trees. If You think you need To use trees, you should look for more information on them from other sources. One application of threes is when they are used to create links On a webpage. (You would need to convert the program into an applet first) Object Oriented Programming in Java 59
  • 60. Tables Tables are very important in organizing data and in performing operations on numerical data. You have seen their uses in spreadsheets and in presenting data in web pages. In Java, a table is a component that displays rows and columns of data. Tables are implemented by the JTable class which has several constructors among which the following is the main one: JTable(Object[][] data, Object[] colHeadings); data is a two-dimensional array of the information to be displayed, and colHeading is a one-dimensioanl array of with the column headings. Like many other Java components and objects, JTable cannot hold data of the basic data types. To create tables with data of basic data types, you need to convert your data to objects first. Object Oriented Programming in Java 60
  • 61. Tables 2 The following program creates a simple table: import java.awt.*;import javax.swing.*; public class JTableDemo extends JFrame{ public JTableDemo(){ setSize(300, 200); final Object[] colHeading={"Name", "Email", "Year"}; final Object[][] data={ {"Pola", "pola@hotmail.com", "2"}, {"Bestoon","bestoon@soft-eng.net","3"}, {"Barzang", "barzang@yahoo.com", "4"}, {"Omed", "omed@yahoo.com", "4"}}; JTable classTable=new JTable(data, colHeading); JScrollPane sp=new JScrollPane(classTable); getContentPane().add(sp, BorderLayout.CENTER); } Object Oriented Programming in Java 61
  • 62. Tables 3 public static void main(String[] a) { new JTableDemo().show(); } } And this is the output: The columns of the table are resizable but not the rows. You can also drag The columns left or right. Column Lengths are all equal. This is the default behavior and is in some cases undesirable. To override this default behavior and get around these restrictions, you need to extend the abstract class AbstractTableModel class which implements the TableModel interface. More information on tables can be found in “The Java Tutorial”, The JDK documentation or your main textbook. Object Oriented Programming in Java 62
  • 63. Tabbed Panes Another Java GUI component which is quite useful is the JTabbedPane component which appears as a group of folders in a filing cabinet. Each folder has a title and when clicked, its contents become visible. Tabbed panes are commonly used to set configuration options in a program. Here is a short example demonstrating tabbed panes: import java.awt.*;import javax.swing.*; public class JTabbedPaneDemo extends JFrame{ public JTabbedPaneDemo(){ setSize(400, 200); JTabbedPane jtp=new JTabbedPane(); jtp.addTab("Universities", new UniversitiesPanel()); jtp.addTab("Techicial Institutes", new TechnicalInstitutesPanel()); Object Oriented Programming in Java 63
  • 64. Tabbed Panes 2 jtp.addTab("Schools", new SchoolsPanel()); getContentPane().add(jtp); } public static void main(String[] a){ new JTabbedPaneDemo().show(); } } class UniversitiesPanel extends JPanel{ public UniversitiesPanel(){ JButton b1=new JButton("Salahaddin"); add(b1); JButton b2=new JButton("Sulaimaniyah"); add(b2); JButton b3=new JButton("Duhok"); add(b3); } } Object Oriented Programming in Java 64
  • 65. Tabbed Panes 3 class TechnicalInstitutesPanel extends JPanel{ public TechnicalInstitutesPanel(){ JButton b1=new JButton("Shaqlawa"); add(b1); JButton b2=new JButton("Zakho"); add(b2); JButton b3=new JButton("Erbil"); add(b3); } } class SchoolsPanel extends JPanel{ public SchoolsPanel(){ JButton b1=new JButton("School1"); add(b1); JButton b2=new JButton("School2"); add(b2); JButton b3=new JButton("School3"); add(b3); } } Object Oriented Programming in Java 65
  • 66. Tabbed Panes 4 The second parameter of the JTabbedPane constructor can be any component; here we have chosen it to be a panel. Here is the output from this program: More information on tabbed panes can be found in “The Java Tutorial”, The JDK documentation or your main textbook. Object Oriented Programming in Java 66
  • 67. International Programs Today, most major software development companies develop international software rather than software specific to a single language/country. This obviously has a lot of advantages for them, not least because they will have a much bigger market out there to sell their software. You too, can use Java to write multi-lingual programs, including Kurdish programs. Java includes support for writing internationalized software. Instead of duplicating the same code for different languages, Java allows you to write the main code only once. “Internationalization is the process of designing an application so that it can be adapted to various languages and regions without engineering changes. Sometimes the term internationalization is abbreviated as i18n, because there are 18 letters between the first "i" and the last "n." Object Oriented Programming in Java 67 (Mostofthematerialontheseslidesistakenfromthe“TheJava Tutorial”fromSun,whichiselectronicallyavailableontheintranet)
  • 68. International Programs 2 An internationalized program has the following characteristics: - With the addition of localized data, the same executable can run worldwide. -Textual elements, such as status messages and the GUI component labels, are not hard-coded in the program. Instead they are stored outside the source code and retrieved dynamically. - Support for new languages does not require recompilation. - Culturally-dependent data, such as dates and currencies, appear in formats that conform to the end user's region and language. - It can be localized quickly. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text. The term localization is often abbreviated as l10n, because there are 10 letters between the "l" and the "n." Usually, the most time-consuming portion of the localization phase is the translation of text. Other types of data, such as sounds and images, may require localization if they are culturally sensitive. Object Oriented Programming in Java 68
  • 69. International Programs 3 We will now write a program which will demonstrate a simple multi-lingual Java program: import java.util.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; class MultiLingualFrame extends JFrame { public MultiLingualFrame(){ currentLocale = new Locale("ar", "IQ"); messages = ResourceBundle.getBundle ("MessagesBundle",currentLocale); Font f=new Font("Arial", Font.PLAIN, 18); setTitle("Multi Lingual Program"); setSize(300, 250); Container contentPane = getContentPane(); Object Oriented Programming in Java 69
  • 70. International Programs 4 JPanel panel = new JPanel(); JButton aButton = new JButton(messages.getString("text")); panel.add(aButton); aButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ textArea.append (messages.getString("some_message")); } }); JButton quitButton=new JButton (messages.getString("quit")); quitButton.setFont(f); panel.add(quitButton); quitButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ Object Oriented Programming in Java 70
  • 71. International Programs 5 System.exit(0); } }); textArea = new JTextArea(8, 20); textArea.setFont(f); textArea.setComponentOrientation (ComponentOrientation.RIGHT_TO_LEFT); scrollPane = new JScrollPane(textArea); contentPane.add(panel, "South"); contentPane.add(scrollPane, "Center"); } private JTextArea textArea; private JTextField from, to; Locale currentLocale; ResourceBundle messages; } Object Oriented Programming in Java 71
  • 72. International Programs 6 public class MultiLingualTest { public static void main(String[] args) { JFrame f = new MultiLingualFrame(); f.show(); } } Run this program and provide different locale information each time you run it. If you look at the above internationalized source code, you'll notice that the hard-coded English messages have been removed. Because the messages are no longer hard-coded and because the language code is specified at run time, the same executable can be distributed worldwide. No recompilation is required for localization. The program has been internationalized. As this program demonstrates, to internationalize a program, follow the following steps: Object Oriented Programming in Java 72
  • 73. International Programs 7 1- Create the Properties Files A properties file stores information about the characteristics of a program or environment. A properties file is in plain-text format. You can create the file with just about any text editor. The default properties file, which is called MessagesBundle.properties, contains the following lines: greetings = Hello farewell = Goodbye inquiry = How are you? Notice that the values to the right side of the equal sign have been translated but that the keys on the left side have not been changed. These keys must not change, because they will be referenced when your program fetches the translated text. Object Oriented Programming in Java 73
  • 74. International Programs 8 The name of the properties file is important. For example, the name of the MessagesBundle_ar_IQ.properties file contains the ar language code and the IQ country code. These codes are also used when creating a Locale object. Lines beginning with # denote comments and are ignored in a properties file. 2. Define the Locale The Locale object identifies a particular language and country. The following statement defines a Locale for which the language is Arabic and the country is the Iraq: Locale aLocale = new Locale(“ar",“IQ"); 3. Create a ResourceBundle ResourceBundle objects contain locale-specific objects. You use ResourceBundle objects to isolate locale-sensitive data, such as Object Oriented Programming in Java 74
  • 75. International Programs 9 translatable text. In the sample program the ResourceBundle is backed by the properties files that contain the message text we want to display. The ResourceBundle is created as follows: message = ResourceBundle.getBundle( "MessagesBundle", currentLocale); The arguments passed to the getBundle method identify which properties file will be accessed. The first argument, MessagesBundle, refers to this family of properties files: MessagesBundle_en_US.properties MessagesBundle_fr_FR.properties MessagesBundle_de_DE.properties MessagesBundle_ar_IQ.properties Object Oriented Programming in Java 75
  • 76. International Programs 10 4. Fetch the Text from the ResourceBundle The properties files contain key-value pairs. The values consist of the translated text that the program will display. You specify the keys when fetching the translated messages from the ResourceBundle with the getString method. For example, to retrieve the message identified by the greetings key, you invoke getString as follows: String msg1 = messages.getString("greetings"); The sample program uses the key greetings because it reflects the content of the message, but it could have used another String, such as s1 or msg1. Just remember that the key is hard-coded in the program and it must be present in the properties files. If your translators accidentally modify the keys in the properties files, getString won't be able to find the messages in that particular locale and the equivalent key in the default properties file would be selected. Object Oriented Programming in Java 76
  • 77. International Programs 11 The MessageBundle_ar_IQ.properties file looks like this: text=u0628u0646u0648u0633u0640u06d5 some_message=u062cu0640u06d5 u0646u062f u0631u064Au0640u0632u06d5 u06a9 n quit=u0628u06afu0631u06d5 These are escape characters. These are the values of the keys in Unicode. Some platforms/programs do not support direct Unicode characters and you have to write their equivalents with ASCII escape sequences. If you are working on an Arabic/enabled platform, you will not need to worry about these escape characters. Text messages are the most obvious form of data that varies with culture. However, other types of data may vary with region or language, including: Sounds, Colors, Graphics, Dates, Times, Numbers, Currencies, Measurements, etc. For more details on this, consult your textbooks. Object Oriented Programming in Java 77
  • 78. Multi-threading Unlike most programming languages, Java has built-in support for multi- threaded programming. A multi-threaded program has two or more parts which run concurrently. Each part is called a thread or thread of execution. A computer’s CPU is sometimes idle, for example waiting for some input from the user, printing something, waiting for data over a network connection. Using multi-threaded programs, you can minimize a CPU’s idle time by making your program efficiently perform other tasks. While a thread waits for data from a network connection, another thread can be processing some data. The Java garbage collection mechanism is another example, which runs as a low priority thread in the background. The Thread Class A thread can be created several ways; one way is using by sub-classing the Thread class. The most common constructor for this class is : Object Oriented Programming in Java 78 Mostofthematerialontheseslidesistakenfromthetextbook.
  • 79. Multi-threading 2 public Thread(String threadName); Which constructs a thread object whose name is threadName. The real work of a thread is done in a method called run, which should be overridden in subclasses of Thread. You saw an example of this when you wrote a client-server network program. Another way of creating a thread object is to make it a runnable object by making it implement the Runnable interface. An example of this will be studied later. A program makes a thread start execution by calling the thread’s start method, which in turn, calls the run method. After start launches the thread, start returns to its called immediately. The called then executes concurrently with the launched thread. In case the thread has already been started and your program attempts to start it again by mistake, an IllegalThreadStateException will be thrown. Object Oriented Programming in Java 79
  • 80. Multi-threading 3 The static method sleep is called with an argument specifying how long the currently running thread should sleep. It causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. While a thread sleeps, it does not contend for CPU time and so other threads can execute. This gives threads with lower priority a chance to run. Other thread methods such as interrupt, isAlive, setName, getName, and join will be described when we come across them. Life Cycle of a Thread A thread can have any one of several thread states. A thread that has been just created is in the born state. The thread remains in the born state until its start method has been invoked; this causes the thread to enter the ready state (or the runnable state). The highest-priority ready thread enters the running state. It begins execution. Object Oriented Programming in Java 80
  • 81. Multi-threading 4 A thread enters the dead state when its run method completes or terminates for any reason. A dead thread will eventually be disposed of by the system. A running thread can enter the blocked state when the thread issues an input/output request. The blocked thread can be ready again when the I/O operation it is waiting for completes. A blocked thread cannot use a processor even if one is available. When the sleep method of a running thread is called, that thread enters the sleeping state. It becomes ready again after the designated sleep time expires. A sleeping thread cannot use a processor even if one is available. A thread can also be in the waiting state; this will be discussed later when we look at monitors. Object Oriented Programming in Java 81
  • 82. Multi-threading 5 Object Oriented Programming in Java 82 Thisfigureistakenfromthetextbook,page738
  • 83. Multi-threading 6 Thread Priorities and Thread Scheduling Every Java program is multi-threaded (applets and applications). Every Java program has at least one thread -- the main thread. When a Java program starts, the JVM creates the main thread and calls the program's main() method within that thread. The JVM also creates other threads that are mostly invisible to you -- for example, threads associated with garbage collection, object finalization, and other JVM housekeeping tasks. Other facilities create threads too, such as the AWT (Abstract Windowing Toolkit) or Swing UI toolkits, servlet containers, application servers, and RMI (Remote Method Invocation). Every Java thread has a priority in the range Thread.MIN_PRIORITY and Thread.MAX_PRIORITY, or between 1 and 10. By default, each thread has normal priority: Thread.NORM_PRIORITY which is a constant of 5. Object Oriented Programming in Java 83
  • 84. Multi-threading 7 Java assigns a priority to each thread; this determines how that thread should be treated with respect to other threads. A thread’s priority is used to decide when to switch from one running thread to the next. This is called a context switch and the rules that determine a context switch are simple: -A thread can voluntarily relinquish control. This is done by explicitly yielding, or blocking on pending input/output. In this situation, all other threads are examined and the one with the highest priority that is ready to run is given the CPU. - a thread can be preempted by a higher priority thread. In this case, as soon as a higher priority thread wants to run, it does. This is called preemptive multitasking. If two threads have equal priority, context switching depends on the underlying operating system. On Windows systems, threads of equal Object Oriented Programming in Java 84
  • 85. Multi-threading 8 priority are time-sliced in round-robin fashion. In this case, each thread receives a brief burst of CPU time called a quantum during which that thread can execute. When the thread’s quantum completes, even if the thread has not finished, the CPU is taken away from that thread an given to the next thread of equal priority. On Solaris, threads yield control voluntarily and if they don’t, the other threads cannot run. In this situation, each thread in a set of equal-priority threads runs to completion (unless the thread enters the waiting, sleeping or blocked state) before other, equal priority, threads can get a chance to run. Other platforms may have different scheduling rules. A multi-thread program may thus behave differently when run on different platforms or operating systems. Object Oriented Programming in Java 85
  • 86. Multi-threading 9 You can change a thread’s priority using the method setPriority which takes one argument of type integer. If the argument is not in the range 1 to 10, an IllegalArgumentException will be thrown. Use the getPriority to obtain thread’s priority. A thread can call the yield method to give other methods a chance to execute, but using this method in time-slicing systems is unnecessary. A thread executes unless - It dies, - it becomes blocked - it calls sleep - it calls wait - it calls yield - it is preempted by a higher priority threat - its quantum expires Object Oriented Programming in Java 86
  • 87. Multi-threading 10 The following example from the text book demonstrates some of the above thread features: public class ThreadTester { public static void main( String args[] ){ PrintThread thread1, thread2, thread3, thread4; thread1 = new PrintThread( "thread1" ); thread2 = new PrintThread( "thread2" ); thread3 = new PrintThread( "thread3" ); thread4 = new PrintThread( "thread4" ); System.err.println( "nStarting threads" ); thread1.start(); thread2.start(); thread3.start(); thread4.start(); } } Object Oriented Programming in Java 87
  • 88. Multi-threading 11 class PrintThread extends Thread { private int sleepTime; public PrintThread( String name ) { super( name ); //random integer between 0 and 10,000 milliseconds sleepTime = (int) ( Math.random() * 10000 ); System.out.println( "Name: " + getName() + "; sleep: " + sleepTime ); } public void run() { // put thread to sleep for a random interval try { System.out.println( getName() + " going to sleep " + getPriority()); Thread.sleep( sleepTime ); } Object Oriented Programming in Java 88
  • 89. Multi-threading 12 catch ( InterruptedException exception ) { System.out.println( exception.toString() ); } System.out.println( getName() + " done sleeping" ); } } The program creates and then starts four threads of equal priority. Each thread, after it runs, goes to sleep for a random Interval between 0 and 10 seconds. After each thread awakens, it prints its name. Object Oriented Programming in Java 89
  • 90. Multi-threading 13 When multiple threads try to access shared data (variables, objects, …), the threads may see inconsistent data. To avoid inconsistent results, you must control the way concurrent threads access shared data. The following example will create two threads, one to update a shared object and one to read the shared object. The shared object has a single integer value. This program has four classes, each on a separate slide. public class SharedCell { public static void main( String args[] ){ HoldIntegerUnsynchronized h = new HoldIntegerUnsynchronized(); ProduceInteger p = new ProduceInteger( h ); ConsumeInteger c = new ConsumeInteger( h ); p.start(); c.start(); } } Object Oriented Programming in Java 90
  • 91. Multi-threading 14 class HoldIntegerUnsynchronized { private int sharedInt = -1; public void setSharedInt( int val ){ System.out.println( Thread.currentThread().getName() + " setting sharedInt to " + val ); sharedInt = val; } public int getSharedInt() { System.out.println( Thread.currentThread().getName() + " retrieving sharedInt value " + sharedInt ); return sharedInt; } } Object Oriented Programming in Java 91
  • 92. Multi-threading 15 class ProduceInteger extends Thread { private HoldIntegerUnsynchronized pHold; public ProduceInteger( HoldIntegerUnsynchronized h ){ super( "ProduceInteger" ); pHold = h; } public void run(){ for ( int count = 1; count <= 10; count++ ) { try { Thread.sleep( (int) ( Math.random() * 3000 ) ); } catch( InterruptedException e ) { System.err.println( e.toString() ); } pHold.setSharedInt( count ); } System.err.println( getName()+" finished producing values" +"nTerminating " + getName() ); } } Object Oriented Programming in Java 92
  • 93. Multi-threading 16 class ConsumeInteger extends Thread { private HoldIntegerUnsynchronized cHold; public ConsumeInteger( HoldIntegerUnsynchronized h ){ super( "ConsumeInteger" ); cHold = h; } public void run() { int val, sum = 0; do { try { Thread.sleep( (int) ( Math.random() * 3000 ) ); } catch( InterruptedException e ) { System.err.println( e.toString() ); } val = cHold.getSharedInt(); sum += val; } while ( val != 10 ); System.err.println(getName() + " retrieved values totaling: " + sum + "nTerminating " + getName() );} } Object Oriented Programming in Java 93
  • 94. Multi-threading 17 A run of this program looked like this: The total of 1 to 5 is 15, not 22 as this program thinks. The Consumer thread even reads -1, which it shouldn’t. Can you see what is happening Object Oriented Programming in Java 94
  • 95. Multi-threading 18 in this program? No synchronization! The two threads should be synchronized so they access the shared data in a controlled way. To solve this problem, you must declare each method used by the Producer or Consumer (in this example, setSharedInt and getSharedInt) objects which access the shared data, with the synchronized keyword. When a synchronized method is running on an object, that object is locked so that no other synchronized method can run in that object at the same time. The next modified program is similar to the previous program; only the the HoldIntegerUnsynchronized class is replaced with HoldIntegerSynchronized class: Object Oriented Programming in Java 95
  • 96. Multi-threading 19 class HoldIntegerSynchronized { private int sharedInt = -1; private boolean writeable = true; // condition variable public synchronized void setSharedInt( int val ) { while ( !writeable ) { // not the producer's turn try { wait(); } catch ( InterruptedException e ) { e.printStackTrace(); } } System.err.println( Thread.currentThread().getName() + " setting sharedInt to " + val ); sharedInt = val; writeable = false; Object Oriented Programming in Java 96
  • 97. Multi-threading 20 notify(); // tell a waiting thread to become ready } public synchronized int getSharedInt(){ while ( writeable ) { // not the consumer's turn try { wait(); } catch ( InterruptedException e ) { e.printStackTrace(); } } writeable = true; notify(); // tell a waiting thread to become ready System.err.println( Thread.currentThread().getName() + " retrieving sharedInt value " + sharedInt ); return sharedInt; } } Object Oriented Programming in Java 97
  • 98. Multi-threading 21 This time, the program would produce correct results: Think about a bank which lets its customers deposit, withdraw and transfer money. If the bank’s system does not synchronize access to the bank accounts, no one would want to save their money in this bank. Object Oriented Programming in Java 98
  • 99. Multi-threading 22 Thread Synchronization Java uses monitors to facilitate synchronization. Every Java object with synchronized methods is a monitor. A monitor’s job is to ensure that only one thread at a time can execute a synchronized method on the object. When a synchronized method is called on an object, that object is locked, also called obtaining the lock. All other threads attempting to call synchronized methods must wait. When a synchronized method finishes executing, the lock on the object is released and the monitor lets the highest-priority ready thread attempting to call a synchronized method on the object to proceed. A thread which, for some reason, cannot continue executing, can call the wit method which will make the thread to go into the waiting state. This will provide an opportunity for other threads to work on the monitor object. Object Oriented Programming in Java 99
  • 100. Multi-threading 23 When a thread executing a synchronized method finishes, it can call the notify method to tell a waiting thread to become ready. The method notifyAll is used when there are more than two waiting threads in contention. Methods wait, notify and notifyAll are all inherited from the class Object; this implies that every type of object can be a monitor. Threads in the waiting state for a monitor object must explicitly be awakened with a notify/notifyAll ( or interrupt ) method, or the thread will wait forever. This may result in deadlock. In your multi-threaded programs, you need to make sure that every wait call has a corresponding notify or notifyAll call. It is an error to call the wait, notify and notifyAll methods on a monitor object with having obtained a lock on the object. Otherwise, an IllegalMonitorStateException will be thrown. Object Oriented Programming in Java 100
  • 101. Multi-threading 24 Some reasons for using threads are: - Make the UI of your programs more responsive Event-driven UI toolkits, such as AWT and Swing, have an event thread that processes UI events such as keystrokes and mouse clicks. AWT and Swing programs attach event listeners to UI objects. These listeners are notified when a specific event occurs, such as a button being clicked. Event listeners are called from within the AWT event thread. If an event listener were to perform a lengthy task, such as checking spelling in a large document, the event thread would be busy running the spelling checker, and thus would not be able to process additional UI events until the event listener completed. This would make the program appear to freeze, which is disconcerting to the user. Object Oriented Programming in Java 101
  • 102. Multi-threading 25 To avoid stalling the UI, the event listener should hand off long tasks to another thread so that the AWT thread can continue processing UI events (including requests to cancel the long-running task being performed) while the task is in progress. - take advantage of multi-processor systems Multiprocessor (MP) systems are much more common than they used to be. Once they were found only in large data centers and scientific computing facilities. Now many low-end server systems -- and even some desktop systems -- have multiple processors. Modern operating systems, including Linux, Solaris, and Windows NT/2000, can take advantage of multiple processors and schedule threads to execute on any available processor. The basic unit of scheduling is generally the thread; if a program has only Object Oriented Programming in Java 102
  • 103. Multi-threading 26 one active thread, it can only run on one processor at a time. If a program has multiple active threads, then multiple threads may be scheduled at once. In a well-designed program, using multiple threads can improve program throughput and performance. -simplifying modeling problems (servers, games,…) In some cases, using threads can make your programs simpler to write and maintain. Consider a simulation application, where you simulate the interaction between multiple entities. Giving each entity its own thread can greatly simplify many simulation and modeling applications. Or consider a server program which has to respond to multiple simultaneous connections from clients. - background processing Server applications get their input from remote sources, such as sockets. When you read from a socket, if there is no data currently available, the Object Oriented Programming in Java 103
  • 104. Multi-threading 27 call to read input from the socket will block until data is available. If a single-threaded program were to read from the socket, and the entity on the other end of the socket were never to send any data, the program would simply wait forever, and no other processing would get done. On the other hand, the program could poll the socket to see if data was available, but this is often undesirable for performance reasons. If, instead, you created a thread to read from the socket, the main thread could perform other tasks while the other thread waited for input from the socket. You can even create multiple threads so you can read from multiple sockets at once. In this way, you are notified quickly when data is available (because the waiting thread is awakened) without having to poll frequently to check if data is available. The code to wait on a socket using threads is also much simpler and less error-prone than polling would be. Object Oriented Programming in Java 104
  • 105. Multi-threading 28 While threads can greatly simplify many types of applications, overuse of threads can be hazardous to your program's performance and its maintainability. Threads consume resources. Therefore, there is a limit on how many threads you can create without degrading performance. In particular, using multiple threads will not make a CPU-bound program run any faster on a single-processor system. A deadlock is a situation where two or more threads cannot proceed with execution, for example when all are in the waiting state. Deadlock are quite common in large multi-threaded programs and there is no easy solution to avoid them. They usually occur as a result of careless programming. Thread synchronization and deadlocks are important subjects in many fields of computer science (operating systems, programming, parallel and distributed systems) and have been well researched. Object Oriented Programming in Java 105
  • 106. Wrapper Classes They say that Java is a pure object-oriented programming language. Everything is an object. Not quite so, you may say?? Because of the primitive data types. Many algorithms, data structures and methods in the Java API libraries only operate on objects. They cannot operate on primitive data. Wrapper classes are designed to wrap around the primitive data and produce object versions of those primitive types. These classes also have static methods for working with primitive types. You have already used the Integer wrapper class when converting/parsing strings to integers. The Character class, for example, provides the following methods: static boolean isDigit(char ch); static boolean isLetter(char ch) static boolean isLetterOrDigit(char ch) static boolean isLowerCase(char ch) static boolean isWhitespace(char ch) Wrapper classes will be extensively used in the next section. (Collections) Object Oriented Programming in Java 106
  • 107. Collections You can create complex data structures (linked lists, queues, stack, trees…) in Java using objects and object references and by using heap memory with the new operator. But like C++, Java supports something called the Java Collections Framework, which provides the programmer with pre-packaged data structures as well as algorithms to work on those data structures. Java collections are similar to C++ STL. Here, we will look at interfaces, implementation classes, algorithms, and iterators. The Java Collections Framework provides you with ready components to use. You don’t have to reinvent the wheel. The collections are standardized so they can easily be shared; they also encourage reusability. The collections can hold any type of data; what’s more, a collection can hold objects/elements of different types. Object Oriented Programming in Java 107
  • 108. Collections 2 A collection is a data structure (an object) that can hold other objects. The collection interfaces define the operations that can be performed on each type of collection . The collections implementations implement these operations in particular ways to provide customized solutions. The most common interfaces in the framework are: Set, List. They both extend the root Collection interface. The Collection interface provides basic methods to manipulate collection objects. The framework also includes the Map interface for data structures containing both value and keys. Programmers can implement these interfaces specific to their application needs. As well as the above interfaces, the framework also contains other interfaces useful when working with collection objects. The classes and interfaces of the collections framework are all members of the java.util package. Object Oriented Programming in Java 108
  • 109. Collections 3 One of the classes in the framework is the class Arrays which provides static methods to manipulate arrays. You have seen this class before. The methods of this class are overloaded to work on both arrays of primitive types and objects. Here is a program which demonstrates some the more common methods of this class: (Only the main method is shown) public static void main(String[] arg){ int[] a={3,1,2}; int[] b={1,2,3}; if(Arrays.equals(a,b)) System.out.println("Equal"); Arrays.fill(a, 5); Arrays.sort(a); //return index of 4 in array System.out.println(Arrays.binarySearch(a,4)); for(int i=0; i<3; i++) System.out.println(a[i]); } Object Oriented Programming in Java 109
  • 110. Collections 4 The Collection interface provides methods (operations) common to all collection objects such as: adding, clearing, comparing, determining a collection’s size… There is also a class called Collections which contains static methods to manipulate collections polymorphically. A List is an ordered collection that may contain duplicate values. Like arrays, Lists are zero based. Interface List is implemented by three classes in the framework: ArrayList, LinkedList and Vector. The following program demonstrates the ArrayList class: import java.util.*; public class myArrayList{ public static void main(String[] arg){ ArrayList aList=new ArrayList(); aList.add("Xyz"); Object Oriented Programming in Java 110
  • 111. Collections 5 aList.add(new Integer(1)); aList.add(new Double(2.5)); aList.add(new Integer(3)); aList.add(2,new Integer(6)); System.out.println(aList.get(1)); System.out.println(aList.size()); System.out.println(aList.indexOf("Xyz")); Iterator j=aList.iterator(); while(j.hasNext()) if(j.next() instanceof String) j.remove(); System.out.println(aList.size()); for(int i=0; i<aList.size(); i++) System.out.println(aList.get(i)); } } Object Oriented Programming in Java 111
  • 112. Collections 6 The programs: first creates an ArrayList object and then using the method add, appends or adds some elements to the list. More specifically, it adds a string, an integer, a double, another double, and one last integer. The last method takes two parameters, the first one specifies the position in the list where the element will be stored. The previous element at the position and all subsequent elements will be shifted to the right. The get method takes the index of an element as a parameter and returns that element. An IndexOutOfBoundsException exception will be thrown if you provide an out of range index. The size method returns the size of the ArrayList object. The method indexOf the index of the first occurrence of the argument in this list; returns -1 if the object is not found. The next line, creates an iterator object which can be used to iterate through collection objects. The iterator object has only three methods: Object Oriented Programming in Java 112
  • 113. Collections 7 hasNext checks to see if there are more elements in the list. Next returns the next element in the list and remove removes the current element reference by the iterator object. Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The ArrayList class has another constructor which takes a parameter to specify the initial capacity of the list: ArrayList(int initialCapacity) This constructs an empty list with the specified initial capacity. Notice that the ArrayList can hold objects of any type, as you saw in this example. You cannot, however, directly store primitive type data like integers and doubles in the list. Object Oriented Programming in Java 113
  • 114. Collections 8 Some useful ArralyList methods are: - boolean addAll(Collection c) //group operation Appends all of the elements in the specified Collection to the end of this list, in the order that they are returned by the specified Collection's Iterator. -boolean contains(Object elem) Returns true if this list contains the specified element. - boolean isEmpty() Tests if this list has no elements. -Object remove(int index) Removes the element at the specified position in this list. -Object set(int index, Object element) Replaces the element at the specified position in this list with the specified element. Object Oriented Programming in Java 114
  • 115. Collections 9 -Object[] toArray() Returns an array containing all of the elements in this list in the correct order. -void trimToSize() Trims the capacity of this ArrayList instance to be the list's current size. For a complete coverage of the methods of this class, consult the JDK documentation or a textbook. The next collection implementation we are going to look at is the LinkedList class. A LinkedList, like an ArrayList also implements the List interface but is more efficient for situations where you would insert/remove elements in the middle of a sequence. Removing and inserting elements in the Object Oriented Programming in Java 115
  • 116. Collections 10 middle of an array, Vector or ArrayList are very expensive operations. The LinkedList implementation does not suffer form this drawback. Because its elements/object references are not stored sequentially. This class can also be used to represent different types of queues and stacks. LinkedList staff=new LinkedList(); staff.add(“ Xyz ”); staff.add(“ Wyz ”); staff.add(“ Zyz ”); Staff.add(2,” Third ”); Staff.remove(“ Wyz ”); iterator it=staff.iterator(); for(int i=0; i<3; i++) System.out.println(it.next()); This would output: Xyz Third Zyz Object Oriented Programming in Java 116
  • 117. Collections 11 But a linked list object in Java has references to both the next element and the previous element. The Iterator interface we saw earlier only has a forward reference to the next element. To facilitate bi-directional traversing of linked list, Java provides the ListIterator interface. LinkedList staff=new LinkedList(); staff.add(“ Xyz "); staff.add(“ Wyz "); staff.add(“ Zyz "); staff.add(2,“ Third "); staff.remove(“ Wyz "); ListIterator lt=staff.listIterator(); for(int i=0; i<staff.size(); i++) System.out.println(lt.next()); for(int i=0; i<staff.size(); i++) System.out.println(lt.previous()); The output: Xyz Third Zyz Zyz Third Xyz Object Oriented Programming in Java 117
  • 118. Collections 12 You can use the set method to change the value of an element of a list: staff.set(0,"One"); Or you can use the listIterator: Object oldValue=it.next(); it.set(newvalue); The following program creates two linked lists, merges them and then removes every second element from the second list. Finally the program removes all methods that exist in the second list from the first list: public class LinkedListTest { public static void main(String[] args) { List a = new LinkedList(); a.add("ABC"); a.add("DEF"); a.add("GHI"); List b = new LinkedList(); b.add("JKL"); b.add("MNO"); b.add("PQR"); b.add("STU"); Object Oriented Programming in Java 118
  • 119. Collections 13 // merge the words from b into a ListIterator aIter = a.listIterator(); Iterator bIter = b.iterator(); while (bIter.hasNext()) { if (aIter.hasNext()) aIter.next(); aIter.add(bIter.next()); } System.out.println(a); // remove every second word from b bIter = b.iterator(); while (bIter.hasNext()) { bIter.next(); // skip one element if (bIter.hasNext()) { bIter.next(); // skip next element bIter.remove(); // remove that element } } Object Oriented Programming in Java 119
  • 120. Collections 14 System.out.println(b); // bulk operation: remove all words in b from a a.removeAll(b); System.out.println(a); } } The program outputs: You should use a linked list only when you have to perform many insertions/deletions of elements in the middle of a list. In other cases, you should use an ArrayList, as it is more efficient. Object Oriented Programming in Java 120
  • 121. Collections 15 The Java Collections Framework does not have any classes/interfaces for queues and stacks. But it has several methods which cab used to view a LinkedList as a queue or stack: void addFirst(Object ob); void addLast(Object ob); Object getFirst(); Object getLast(); Object removeFirst(); Object removeLast(); LinkedList queue = ...; //First-In-First-Out queue.addFirst(element); Object object = queue.removeLast(); LinkedList stack = ...; //First-In-Last-Out stack.addFirst(element); Object object = stack.removeFirst(); Object Oriented Programming in Java 121
  • 122. Collections 16 The root interface of the collections hierarchy is the Collection interface; this interface contains methods common to all collection implementations as we saw. This interface also includes methods for performing mathematical operations on collections (when viewed as sets): addAll(Collection c); //True if the collection changed Adds all of the elements in the specified collection to this collection. containsAll(Collection c); //subset operation Returns true if this collection contains all of the elements in the specified collection. removeAll(Collection c); //True if the collection changed Removes all this collection's elements that are also contained in the specified collection. retirnAll(Collection c); Retains only the elements that are contained in the specified collection Object Oriented Programming in Java 122
  • 123. Collections 17 A set is a collection of objects in which duplicates are not allowed. “It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. “ (JDK) In Java, the Set interface is implemented by two concrete classes: HashSet and TreeSet. The following example demonstrates both classes: Set set = new HashSet(); set.add("Elizabeth"); set.add("Bernadine"); set.add("Elizabeth"); //duplicate rejected set.add("Gene"); System.out.println(set); Set sortedSet = new TreeSet(set); sortedSet.add("Romeo"); //automatically sorted sortedSet.add("Alice"); sortedSet.add("Juliet"); System.out.println(sortedSet); The output: Object Oriented Programming in Java 123
  • 124. Collections 18 You can make a collection un-modifiable or read-only. The Collection class provides the following methods to create such collections: Collection unmodifiableCollection(Collection c); List unmodifiableList(List list) ; Set unmodifiableSet(Set set) ; The following code illustrates the use of third method: Set set = new HashSet(); set.add("Bernadine"); set.add("Elizabeth"); set.add("Gene"); set.add("Elizabeth"); set=Collections.unmodifiableSet(set); set.add("test"); The last statement will throw an UnsupportedOperationException exception. The collection is read-only. Object Oriented Programming in Java 124
  • 125. Collections 19 Collection objects are not thread-safe. That is, if multiple threads attempt to access a collection object simultaneously, the object must be synchronized externally. Or, you could use the following methods to create synchronized collection objects: Collection synchronizedCollection(Collection c); List synchronizedList(List list) ; Set synchronizedSet(Set set) ; Unlike when making a collection read-only, you synchronize the collection immediately after creating it. You also must make sure you do not retain a reference to the original collection, or else you can access the collection unsynchronized. The simplest way to make sure you don't retain a reference is to never create one: Set set = Collection.synchronizedSet(new HashSet()); Making a collection un-modifiable also makes a collection thread-safe, as the collection can't be modified. This avoids the synchronization overhead. Object Oriented Programming in Java 125
  • 126. Collections 20 The Map interface describes a mapping from keys to values, without duplicate keys, by definition. It is like a database table which has no two tuples with the same primary key ( key). In a map, there cannot be duplicate keys; each key can map to at most one value. But the mapped values can have duplicates. The Map interface methods can be broken down into three sets of operations: altering, querying, and providing alternative views. The alteration operations allow you to add and remove key-value pairs from the map. Both the key and value can be null: Object put(Object key, Object value); Object remove(Object key) ; void putAll(Map mapping) ; void clear() ; The query operations allow you to check on the contents of the map: Object get(Object key) ; boolean containsKey(Object key) ; Object Oriented Programming in Java 126
  • 127. Collections 21 boolean containsValue(Object value) ; int size() ; boolean isEmpty() ; The last set of methods allow you to work with the group of keys or values as a collection. public Set keySet(); public Collection values(); Since the collection of keys in a map must be unique, you get a Set back. Since the collection of values in a map may not be unique, you get a Collection back. The Collections Framework provides two general-purpose Map implementations: HashMap and TreeMap . As with all the concrete implementations, which implementation you use depends on your specific needs. For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Using a HashMap requires that your own classes have a well-defined Object Oriented Programming in Java 127
  • 128. Collections 22 hashCode() implementation. With the TreeMap implementation, elements added to the map must be sortable (implement the comparable interface). Map map = new HashMap(); Integer ONE = new Integer(1); for (int i=0, n=args.length; i<n; i++) { String key = args[i]; Integer frequency = (Integer)map.get(key); System.out.println(frequency); if (frequency == null) { frequency = ONE;} else { int value = frequency.intValue(); frequency = new Integer(value + 1); } map.put(key, frequency); } System.out.println(map); Map sortedMap = new TreeMap(map); System.out.println(sortedMap); Object Oriented Programming in Java 128
  • 129. URL Class Definition: URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet. An example of a URL is the following: http://soft-eng.net/default.asp The first part of the URL specifies a protocol, in this case it is the WWW HTTP protocol. The second part specifies the resource name. The resource name itself consists of the following sub-parts: host: soft-eng.net file name: default.asp port no.: The port number to connect to (typically optional) reference: a reference to named anchor within a resource that usually identifies a specific location within a file. (none here) The next example will demonstrate how to create and read from a URL: Object Oriented Programming in Java 129
  • 130. URL Class 2 Import java.net.*; Import java.io.*; Public class URLReader { public static void main(String[] args) throws Exception { URL home=new URL(http://toshiba2/index.htm); BufferedReader in=new BufferedReader(new InputStreamReader(home.openStream())); String inputLine; while((inputLine=in.readLine()) !=null) System.out.println(inputLine); in.close(); } } Object Oriented Programming in Java 130
  • 131. URL Class 3 Another example involving URLs: import java.net.*; import java.io.*; public class ParseURL { public static void main(String[] args) throws Exception { URL aURL=new URL(http://soft-eng.net:80/final year/assign1.asp); System.out.println(“protocol: “ + aURL.getProtocol()); System.out.println(“host: “+ aURL.getHost()); System.out.println(“filename: “ + aURL.getFile()); System.out.println(“port: “ + aURL.getPort()); System.out.println(“ref: “ + aURL.getRef()); } } Object Oriented Programming in Java 131
  • 132. URL Class 4 This is the output of the previous program: Protocol = http Host = soft-eng.net Filename = /final year/assign1.asp Port = 80 Ref = null You will probably need this class for your assignment. As you can see, this class provides very useful functionality to work with web pages and web addresses or URLs! You will probably also need to work with strings in your assignment. The next three slides will provide a brief recap of different types of strings in Java. Object Oriented Programming in Java 132
  • 133. More on Strings A string variable/object is immutable which means that once a string is created, it cannot be changed. Each time a string is modified, a new string is created. The following example illustrates: String str=“Yes”; str str=“No”; str Object Oriented Programming in Java 133 Yes Yes No
  • 134. More on Strings 2 Java also provides a StringBuffer class which is not immutable and can be more efficient for code that does a lot of string manipulation. A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. StringBuffer sb=new StringBuffer(“LLM"); sb.setCharAt(0,‘K'); //”KLM” You couldn’t do this with a string object. There is also another useful class called StrignTokenizer which can be used to break strings into smaller strings: BufferedReader br=new BufferedReader (new FileReader("test.txt")); String line=br.readLine(); StringTokenizer st=new StringTokenizer(line); Object Oriented Programming in Java 134
  • 135. More on Strings 3 while(st.hasMoreTokens()) System.out.println(st.nextToken()); The previous code fragment would open a file (test.txt), read the first line and using a StringTokenizer object, the line would be broken into several smaller strings. The default delimiter is a space but you can specify any other character as a delimiter (or even specify multiple delimiter characters in a string): StringTokenizer st=new StringTokenizer(line,“ ,.n”); This class can be useful when retrieving data from delimited text files. It relieves the programmer from having to do the extraction process manually. For more information on Strings: C:jdk1.4docsapijavalangString.html StringBuffer: C:jdk1.4docsapijavalangStringBuffer.html StringTokenizer: C:jdk1.4docsapijavautilStringTokenizer.html Object Oriented Programming in Java 135
  • 136. Java Native Interfaces The Java Native Interfaces (JNI) allow Java code that runs within a Java Virtual Machine (JVM) to operate with applications and libraries written in other programming languages, such as C, C++ and assembly. Programmers use the JNI to write native methods to handle those situations where an application cannot be written entirely in the Java language. For example, you may need to use native methods and JNI in the following situations: -The standard Java class library may not support the platform-dependent features needed by your application. - you may already have a library or application written in another programming language and you wish to make it accessible to Java applications. - You may want to implement a small portion of time-critical code in a lower-level language, such as assembly, and then have your Java application call this code. Object Oriented Programming in Java 136
  • 137. Java Native Interfaces 2 Writing native methods for Java programs is a multi-step process: 1- begin by writing the Java program. Create a Java class that declares the native method; this class contains the signature or the declaration for the native method/s. It also contains the main method which calls the native method. 2- Compile the Java class that contains the native method and the main method. 3- Generate a header file for the native method suing javah with the native interface flag –jni. This header file will contain the formal signature for your native method. 4- write the implementation of the native method in the language of your choice, such as C, C++ 5- compile the header and implementation files into a shared library file. 6- Run the Java program. We will start with an example that uses C++’s clear screen function. Object Oriented Programming in Java 137
  • 138. Java Native Interfaces 3 Here is the step-by-step process: 1- create a class (MyNative.java) that declares the native method: Public class MyNative{ public static void main(String[] args) { System.out.println(This line will soon disappear”); clearScreen(); } public native static void clearScreen(); static{ System.loadLibrary(“clearScreenLibrary”); } } Object Oriented Programming in Java 138
  • 139. Java Native Interfaces 4 2- Compile the class MyNative.java to produce MyNative.class 3- Use Javah –jni MyNative to create C/C++ header file (MyNative.h) Containing the declaration for the native method. 4-write the C/C++ implementation of the native method and include the function prototype produced in the header file: #include “MyNative.h” #include <stdlib.h> extern “C” JNIEXPORT void JNICALL Java_MyNative_clearScreen (JNIEnv *, jclass) { system(“cls”); } 5- Compile the C/C++ implementation into a native library, creating the clearScreenLibrary.dll. Object Oriented Programming in Java 139
  • 140. Java Native Interfaces 5 In step 5, you create a dll library using the following C/C++ compiler command: cl –Ic:jdkinclude –Ic:jdkincludewin32 –LD Filename.cpp –FeDLLFileName This simple exmaple only had one C++ methdo but you could have a whole library of native methods in a file and compile them all into a dll file to be used by Java programs. Since you will need to use the Windows command-interpreter a few times, you should execute the following command before starting any other commands: vcvars32.bat This command is located in the bin directory of VC98 directory of Visual Studio. Object Oriented Programming in Java 140
  • 141. Object Serialization Object serialization is about saving objects to streams for later use. You have seen how to store textual data to a disk or to a network stream. But in object- oriented programs, you would be mainly dealing with objects and it would be very helpful if there was a way to write/read whole objects into streams. Object serialization does just that. Of course, you could achieve this by manually saving object information (object type, object data…), but this very tedious, especially when dealing with objects in an inheritance hierarchy. Object serialization allows the programmer to effortlessly deal with the problems of writing/reading objects to streams. Most tasks are automated. Use object serialization to: for RMI communication and object persistence.* A class must implement the Serializable interface for its objects to be saved and restored by serialization. This interface has no methods. Object Oriented Programming in Java 141