Chapter Two: Advanced Java Topics
Chapter Two: Advanced Java Topics
1
Contents
2
Introduction to Packages
• A package is a mechanism to group the
similar type of classes, interfaces and sub-
packages and provide access control.
• It organizes classes into single unit.
• In Java already many predefined packages are
available, used while programming.
For example: java.lang, java.io, java.util etc.
3
Advantages of Packages
• Packages provide code reusability, because a
package has group of classes.
• It helps in resolving naming collision when multiple
packages have classes with the same name.
• Package also provides the hiding of class facility.
Thus other programs cannot use the classes from
hidden package.
• Access limitation can be applied with the help of
packages.
• One package can be defined in another package.
4
Types of Packages
• Built-in packages
– Built-in packages are already defined in java API. For
example: java.util, java.io, java,lang, java.awt,
java.applet, java.net etc.
• User defined packages
– The package we create according to our need is called
user defined package.
5
Creating a Package
• We can create our own package by creating our
own classes and interfaces together.
• The package statement should be declared at
the beginning of the program.
Syntax:
• package <packagename>;
class ClassName
{
……..
……..
}
6
Cont…
7
The “import” keyword
• The import keyword provides the access to other
package classes and interfaces in current packages.
• “import” keyword is used to import built-in and user
defined packages in java program.
• There are different 3 ways to access a package from
other packages.
• Using full qualified name
class Demo extends java.util.Scanner
{
//statements
}
8
Cont…
14
Cont…
• Note: A class can implement more than one
interface. Java can achieve multiple inheritances
by using interface.
– A real world example:
import java.io.*;
interface Vehicle {
// all are the abstract methods.
void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}
15
class Bicycle implements Vehicle{
int speed;
int gear;
// to decrease speed
// to change gear
@Override
@Override
public void applyBrakes(int decrement){
public void changeGear(int newGear){
speed = speed - decrement;
gear = newGear; }
}
public void printStates() {
// to increase speed System.out.println("speed: " + speed
@Override + " gear: " + gear);
public void speedUp(int increment){ }
}
speed = speed + increment;
}
16
Employee Interface
public interface Employee {
double getSalary();
}
17
Student Class Revisted
public class Student {
private String name;
private String course;
Output:
Conor, intern majoring in Math
with an income of $200000.0
20
Variable Types
• A variable may have the type of an abstract class,
an interface, or a concrete class (a non-abstract
class).
24
Object serialization
• Serialization is a process of converting an object
into a sequence of bytes which can be persisted to
a disk or database or can be sent through streams.
• The reverse process of creating object from
sequence of bytes is called deserialization.
25
Cont…
• A class must implement Serializable interface
present in java.io package in order to serialize its
object successfully.
• Serializable is a marker interface that adds
serializable behaviour to the class implementing it.
• Marker Interface is a special interface in Java
without any field and method.
• Marker interface is used to inform compiler that
the class implementing it has some special
behaviour or meaning.
26
Cont…
• Java provides Serializable API encapsulated under java.io
package for serializing and deserializing objects which
include.
– java.io.serializable
– java.io.Externalizable
• Classes ObjectInputStream and ObjectOutputStream are
high-level streams that contain the methods for serializing
and deserializing an object.
• The ObjectOutputStream class contains many write
methods for writing various data types
– public final void writeObject(Object x) throws IOException
– writeObject() method of ObjectOutputStream class serializes an
object and send it to the output stream. 27
Cont…
• Similarly, the ObjectInputStream class contains the method for
deserializing an object
– public final Object readObject() throws IOException,
ClassNotFoundException
• readObject() method of ObjectInputStream class references
object out of stream and deserialize it.
• NOTE: Static members are never serialized because they are
connected to class not object of class.
• transient Keyword: While serializing an object, if we don't
want certain data member of the object to be serialized we
can mention it transient.
• transient keyword will prevent that data member from being
serialized. 28
Sample code for object serialization and de-serialization
} 29
cont…
import java.io.*;
public class deserialization {
public static void main(String[] args) {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("src/serialization/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
System.out.println("Deserialized Employee...“+ + e.name+ e.address + e.SSN + e.number);
}}
30
Socket Programming
31
Socket Programming
What is socket
• Socket represents a end point connection between two
processes that permits them to exchange data.
• Socket programming refers to programming at the
application level/layer!
• There are two types of socket:
– TCP Stream socket: reliable two-way connected communication
streams.
– UDP Datagram socket: unreliable connectionless communication
datagram.
• a door between application process and end-to-end
transport protocols (TCP or UDP) 32
Cont…
33
Development of client/application that
communicate using sockets
34
Cont…
37
Cont…
• A server is the process that is constantly running,
listening for socket connections.
• The client process, attempts to make contact with
the server, when needed.
38
General TCP client/server model description
39
Cont…
4. Three-way handshake
Client knocks server welcoming socket.
Server hears the knock and creates new socket to particular
client (connection socket).
TCP connection exist between client's socket and server's new
socket.
5. Client sends data via its client socket to server via connection
socket and TCP guarantees the delivery of data which means that
TCP provides reliable byte-stream service between client and
service processes.
40
41
Cont…
42
Client-Server Application
43
44
Cont…
45
46
Cont…
47
Important notes
• Client has Socket type for clientSocket, server has
ServerSocket type for welcomingSocket and
Socket type for connectionSocket.
• clientSocket needs hostname for server and port
number, serverSocket needs only port number.
• BufferedReader stream is used for reading data
at client or server sides,DataInput/OutputStream
is used for sending data between client and
server through network.
48
Socket -programming using UDP
• UDP:
– Connectionless and unreliable service.
– There isn’t an initial handshaking phase.
– Doesn’t have a pipe.
– Transmitted data may be received out of order, or lost.
• UDP Reliability
– there is no guarantee that the sent datagrams will be
received by the receiving socket
49
Cont…
• UDP Timing
– does not include a congestion-control mechanism, so
a sending process can pump data into network at any
rate it pleases (although not all the data may make it
to the receiving socket)
50
Socket Programming with UDP
• No need for a welcoming socket.
• No streams are attached to the sockets.
• The sending hosts creates “packets” by attaching
the IP destination address and port number to
each batch of bytes.
• The receiving process must discover received
packet to obtain the packet’s information bytes.
• Sockets type is DatagramSocket
51
52
Input/output representation…
53
Cont…
• Note: General mechanisms of TCP and UDP
models for socket programming are the same with
some differences that appears according to the
differences between TCP and UDP features.
54
55
56
Important notes
• Client code:
– DatagramSocket clientSocket = new DatagramSocket() line:
Does n't initiate TCP connection, client host doesn't contact
with the server host according to creating the socket.
– DatagramSocket() doesn't take the server hostname or the
port number as arguments.
– InetAddress IPAddress =
InetAddress.getByName("hostname")line: Get the IP address
of the destination host in order to attach it to every sent
packet.
– Sent packets has a type of DatagramPacket.
– Send/receive methods at UDP programming are instead of
Input/Output streams at TCP programming that attached to
sockets. 57
Server code
• There is no new socket is created for new
connection request from client.
• Unlike TCP, at UDP client code is executed before
server code because client doesn't initiate a
connection with server when client code
executed.
58
applets
• Applet is a Java program that can be embedded into a
web page.
• It runs inside the web browser and works at client side.
• Applet is embedded in a HTML page using the APPLET or
OBJECT tag and hosted on a web server.
• Applets are used to make the web site more dynamic
and entertaining.
• Some important points:
– All applets are sub-classes (either directly or
indirectly) of java.applet.Applet class.
59
Cont…
• Applets are not stand-alone programs. Instead, they run
within either a web browser or an applet viewer.
– JDK provides a standard applet viewer tool
called applet viewer.
• In general, execution of an applet does not begin at
main() method.
• Output of an applet window is not performed
by System.out.println(). Rather it is handled with various
AWT methods, such as drawString().
• The newer javax.swing.JApplet is such an extension, so
more functionality is inherited by extending the JApplet
class instead
60
Life cycle of an applet
• init( )
Initialization occurs when the applet is first loaded (or reloaded),
similarly to the main() method in applications.
This is the first of your methods to be executed
Typically this method is used to initialize instance fields, create GUI
components, load sound to play, load image to display.
Applet does not have constructor. Instead, we override the init()
method to initialize the GUI display when the applet is loaded into
the web browser.
It is only executed once 62
Cont …
• To provide behavior for the initialization of your applet, override
the init() method in your applet class.
String s= " ";
public void init()
{
s=s+ " int ";
}
start( ) :
The start( ) method is called after init( ).
it can happen many different times during an applet's lifetime
Note that init( ) is called once i.e. when the first time an applet is
loaded whereas start( ) is called each time an applet’s HTML
document is displayed onscreen.
Starting can also occur if the applet was previously stopped.
For example, an applet is stopped if the reader follows a link to a different
page, and it is started again when the reader returns to this page. 63
Cont…
• Paint():
– this method is called by applet container after init() and start() methods.
– Painting is how an applet actually draws something on the screen, be it
text, a line, a colored background, or an image.
– You override the paint() method if your applet needs to have an actual
appearance on the screen (that is, most of the time).
– The paint method is where the real work of this applet (what little work
goes on) really occurs.
– The paint( ) method has one parameter of type Graphics.
– This parameter will contain the graphics context, which describes the
graphics environment in which the applet is running.
– This context is used whenever output to the applet is required.
– called back when the applet drawing area must be refreshed, e.g.,
another window partially covers the applet
64
Example
65
Cont…
• stop( ) :
– The stop( ) method is called when a web browser
leaves the HTML document containing the applet
• when it goes to another page, for example.
• When stop( ) is called, the applet is probably running.
– You should use stop( ) to suspend threads that don’t
need to run when the applet is not visible.
• You can restart them when start( ) is called if the user
returns to the page.
66
Cont…
• destroy( ) :
– The destroy( ) method is called when the
environment determines that your applet needs to be
removed completely from memory.
• At this point, you should free up any resources the applet
may be using.
– The stop( ) method is always called before destroy( ).
67
Cont…
• init( ) and destroy() are only called
once are only called once each
• start( ) and stop() are called whenever
the browser enter and leaves the page
•
68
Cont…
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
69
Cont…
import java.awt.Color;
import java.awt.Graphics; // import Graphics class
public void paint(Graphics g) {
import javax.swing.*; // import swing package
import javax.swing.JApplet;
// draw the results with
import javax.swing.JOptionPane;
Color bgColor = Color.blue;
public class AdditionApplet extends JApplet {
// sum of the values entered by the user
setBackground(bgColor);
g.setColor(bgColor);
double sum;
g.drawRect(15, 10, 270,
public void init() {
20);
String firstNumber, secondNumber;
double number1, number2;
g.drawString("the sum of
// read in first number from user the two numbers are " +
firstNumber = JOptionPane.showInputDialog("Enter first
floating point value"); sum, 25, 25);
secondNumber = JOptionPane.showInputDialog("Enter second
floating point value"); } //end of paint } //end of
number1 = Double.parseDouble(firstNumber);
number2 = Double.parseDouble(secondNumber); AdditionApplet class
sum = number1 + number2;
}
} 70
Cont…
71
Using java enabled web browser
• To execute an applet in a web browser we have to write a
short HTML text file that contains a tag that loads the applet.
• We can use APPLET or OBJECT tag for this purpose. Using
APPLET, here is the HTML file that executes AdditionApplet :
<html>
<head>
<title>Digital Clock Applet</title>
</head>
<body bgcolor=white>
<h1>The Digital Clock Applet</h1>
<p> <applet code= AdditionApplet.class width=250 height=80> </applet>
</body>
</html>
72
Cont…
import java.awt.Color; public void stop() {
import java.awt.Font; clockThread = null;
import java.awt.Graphics; }
import java.util.Calendar; public void run() {
import javax.swing.JApplet; while (Thread.currentThread() == clockThread) {
repaint();
public class DigitalClock extends JApplet implements Runnable {
try {
protected Thread clockThread; Thread.currentThread().sleep(1000);
protected Font font; } catch (InterruptedException e) {
protected Color color; }
}
public void init() { }
// TODO start asynchronous download of heavy resources
public void paint(Graphics g) {
clockThread = null;
Calendar calendar = Calendar.getInstance();
font = new Font("Monospaced", Font.BOLD, 48);
color = Color.green; int hour = calendar.get(Calendar.HOUR_OF_DAY);
} int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
// TODO overwrite start(), stop() and destroy() methods g.setFont(font);
public void start() { g.setColor(color);
if (clockThread == null) {
g.drawString(hour + ":" + minute / 10 + minute % 10
clockThread = new Thread(this);
+ ":" + second / 10 + second % 10, 10, 60);
clockThread.start();
} //end of paint } //end of DigitalClock class
}
} }
73
Cont…
74
Cont….
75