0% found this document useful (0 votes)
16 views32 pages

Advanced Programing 2

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 32

Chapter -2

Advanced Java Topics


Major Concepts

 Package and Interface.


 Object serialization
 Sockets
Package and Interface
 Package
Used group related pieces of a program together. A package
serves for two purposes. First, it provides a mechanism by
which related pieces of a program can be organized as a
unit. Classes defined within a package must be accessed
through their package name. Thus, a package provides a
way to name a collection of classes. Second, a package
participates in Java’s access control mechanism. Classes
defined within a package can be made private to that
package and not accessible by code outside the package.
Thus, the package provides a means by which classes can
be encapsulated.
cont..
 Defining a Package
All classes in Java belong to some package. When no package
statement is specified, the default (or global) package is used. To
create a package, put a package command at the top of a Java
source file. The classes declared within that file will then belong to the
specified package. Since a package defines a namespace, the
names of the classes that you put into the file become part of that
package’s namespace.
This is the general form of the package statement:
package packageName;
Package project1;
Java uses the file system to manage packages, with each package
stored in its own directory. For example, the .class files for any
classes you declare to be part of Project1 must be stored in a
directory called Project1.
Cont..
 Package and Member Access
If a member of a class has no explicit access specifier, then
it is visible within its package but not outside its package.
Therefore, you will use the default access specification for
elements that you want to keep private to a package but
public within that package. Members explicitly declared
public are visible everywhere, including different classes
and different packages. There is no restriction on their use
or access. A private member is accessible only to the
other members of its class. A private member is
unaffected by its membership in a package. A member
specified as protected is accessible within its package and
to all subclasses, including subclasses in other packages.
Continued..
Interface
Interfaces are syntactically similar to abstract classes.
However, in an interface, no method can include a body. That
is, an interface provides no implementation whatsoever. It
specifies what must be done, but not how. Once an interface
is defined, any number of classes can implement it. Also, one
class can implement any number of interfaces. To implement
an interface, a class must provide bodies (implementations)
for the methods described by the interface. Each class is free
to determine the details of its own implementation. Thus, two
classes might implement the same interface in different ways,
but each class still supports the same set of methods. Thus,
code that has knowledge of the interface can use objects of
either class since the interface to those objects is the same.
By providing the interface keyword, Java allows you to fully
utilize the “one interface, multiple methods” aspect of
polymorphism.
Here is the general form of an interface:
access interface name {
ret-type method-name1(param-list);
ret-type method-name2(param-list);
type var1 = value;
type var2 = value;
// ...
ret-type method-nameN(param-list);
type varN = value; }
Here, access is either public or not used. When no access specifier is
included, then default access results, and the interface is available only to
other members of its package. When it is declared as public, the interface
can be used by any other code.
Methods are declared using only their return type and signature. They are,
essentially, abstract methods. As explained, in an interface, no method can
have an implementation. Thus, each class that includes an interface must
implement all of the methods. In an interface, methods are implicitly public.
Variables declared in an interface are not instance variables. Instead, they
are implicitly public, final, and static and must be initialized. Thus, they are
essentially constants
public interface Series {
int getNext(); // return next number in series
void reset(); // restart
void setStart(int x); // set starting value }
Implement Series.
class ByTwos implements Series {
int start; int val;
ByTwos() { //constructor
start = 0; val = 0; }
public int getNext() { //defining getNext() method val += 2;
return val; }
public void reset() { //defining reset() method start = 0;
val = 0; }
public void setStart(int x) {
start = x; val = x; } }
main class
class SeriesDemo {
public static void main(String args[]) {
ByTwos ob = new ByTwos(); // Create ByTwo object
for(int i=0; i < 5; i++) {
System.out.println("Next value is " + ob.getNext()); }
System.out.println("\nResetting"); ob.reset();
for(int i=0; i < 5; i++) {
System.out.println("Next value is " + ob.getNext()); }
System.out.println("\nStarting at 100"); ob.setStart(100);
for(int i=0; i < 5; i++) {
System.out.println("Next value is " + ob.getNext()); }
} //ending main method
}//end of the class SeriesDemo
Interfaces Can Be Extended
One interface can inherit another by use of the keyword extends. The syntax is
the same as for inheriting classes. When a class implements an interface that
inherits another interface, it must provide implementations for all methods
defined within the interface inheritance chain.
Following is an example: // One interface can extend another. interface A {
void meth1(); void meth2(); }
// B now includes meth1() and meth2() – it adds meth3(). because B
inherits( extends) A.
interface B extends A {
void meth3(); } // This class must implement all of A and B
class MyClass implements B {
public void meth1() { System.out.println("Implement meth1()."); }
public void meth2() { System.out.println("Implement meth2()."); }
public void meth3() { System.out.println("Implement meth3().");} }
//main class class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1(); ob.meth2(); ob.meth3(); } }
Sockets
Client/Server Communication
At a basic level, network-based systems consist of a server,
client, and a media for communication. A computer running a
program that makes a request for services is called client
machine. A computer running a program that offers requested
services from one or more clients is called server machine. The
media for communication can be wired or wireless network.
Cont …
The transport layer comprises two types of protocols, TCP (Transport Control
Protocol) and UDP(User Datagram Protocol). The most widely used
programming interfaces for these protocols are sockets. TCP is a connection-
oriented protocol that provides a reliable flow of data between two computers.
Example applications that use such services are HTTP, FTP, and Telnet.
UDP is a protocol that sends independent packets of data, called datagrams,
from one computer to another with no guarantees about arrival and
sequencing. Example applications that use such services include Clock server
and Ping. The TCP and UDP protocols use ports to map incoming data to a
particular process running on a computer.
Hosts Identification and Service Ports
Every computer on the Internet is identified by a unique, 4-byte IP address.
This is typically written in dotted quad format like 128.250.25.158 where each
byte is an unsigned value between 0 and 255. This representation is clearly
not user-friendly because it does not tell us anything about the content and
then it is difficult to remember. Hence, IP addresses are mapped to names like
www.buyya.com or www.google.com, which are easier to remember.
Socket Programming and java.net class
A socket is an endpoint of a two-way communication link
between two programs running on the network. Socket is bound
to a port number so that the TCP layer can identify the
application that data is destined to be sent. Java provides a set
of classes, defined in a package called java.net, to enable the
rapid development of network applications.
TCP/IP Socket Programming
The two key classes from the java.net package used in creation
of server and client programs are:
 ServerSocket  Socket
A server program creates a specific type of socket that is used to
listen for client requests (server socket), In the case of a
connection request, the program creates a new socket through
which it will exchange data with the client using input and output
streams. The socket abstraction is very similar to the file concept:
developers have to open a socket, perform I/O, and close it.
Cont…
The steps for creating a simple server program are:
a. Open the Server Socket:
ServerSocket server = new ServerSocket( PORT );
b. Wait for the Client Request:
Socket client = server.accept();
c. Create I/O streams for communicating to the client
DataInputStream is = new
DataInputStream(client.getInputStream());
DataOutputStream os = new
DataOutputStream(client.getOutputStream());
d. Perform communication with client
Receive from client: String line = is.readLine();
Send to client: os.writeBytes(“Hello\n”);
e. Close socket: client.close();
Cont…
The steps for creating a simple client program are:
i. Create a Socket Object:
Socket client = new Socket(server, port_id);
ii. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream());
os = new DataOutputStream(client.getOutputStream());
iii. Perform I/O or communication with the server:
Receive data from the server: String line = is.readLine();
Send data to the server: os.writeBytes(“Hello\n”);
iv. Close the socket when done:
client.close();
Client
Server
Cont…
Running Socket Programs Compile both server and client
programs and then deploy server program code on a machine
which is going to act as a server and client program, which is
going to act as a client. The client program is just establishing a
connection with the server and then waits for a message. On
receiving a response message, it prints the same to the console.
It should be noted that once the server program execution is
started, it is not possible for any other server program to run on
the same port until the first program which is successful using it is
terminated. Port numbers are a mutually exclusive resource. They
cannot be shared among different processes at the same time.
Chapter 3
Threads
Introductions to threads

Thread Scheduling

Creating a Thread

Synchronization

The Object Monitor


Introduction to Thread
Although Java contains many innovative features, one
of its most exciting is its built-in support for multi-
threaded programming. A multi-threaded program
contains two or more parts that can run concurrently.
Each part of such a program is called a thread, and
each thread defines a separate path of execution.
Thus, multi-threading is a specialized form of
multitasking.
Creating a Thread
You create a thread by instantiating an object of type
Thread. The Thread class encapsulates an object that
is runnable.
Cont…
Java defines two ways in which you can create a runnable object:

● You can implement the Runnable interface.

● You can extend the Thread class.

Both approaches still use the Thread class to instantiate, access, and control the
thread. The only difference is how a thread-enabled class is created.

implement the Runnable interface

The Runnable interface abstracts a unit of executable code. You can construct a
thread on any object that implements the Runnable interface. Runnable defines only
one method called run( ), which is declared like this: public void run( ) Inside run( ),
you will define the code that constitutes the new thread.

The sleep( ) method causes the thread from which it is called to suspend execution
for the specified period of milliseconds. Its general form is shown here:

static void sleep(long milliseconds) throws InterruptedException


Cont…
Progress Check
1.How do you set a thread’s priority?
2. How do you restrict access to an object to one thread at a time?
3. The synchronized keyword can be used to modify a method or to create a
__________ block.
Ans
1. To set a thread’s priority, call setPriority( ).
2. To restrict access to an object to one thread at a time, use the synchronized
keyword.
3. synchronized
import java.io.*;
public classEmployee{
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class only.
private double salary;
// the name variable is assigned in the constructor.
public Employee(String empName){
name=empName;}
// the salary variable is assigned a value.
public void setSalary(doubleempSal){
salary=empSal;}
// this method prints the employee details.
public void printEmp(){
System.out.println("name : "+ name );
System.out.println("salary :"+ salary);}
public static void main(String args[]){
EmployeeempOne=newEmployee(“Boonna");
empOne.setSalary(1000);
empOne.printEmp(); }}
Constructor
Exception handling
public class Testtrycatch1{
public static void main(String args[]){
int data=50/0;//may throw exception
System.out.println("rest of the code..."); } }
Error handled
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){
System.out.println(e);}
System.out.println("rest of the code..."); } }

You might also like