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

Unit4-BCA IADC

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views32 pages

Unit4-BCA IADC

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Indian Academy Degree College

Faculty of BCA

1.Thread in java
● In operating system you can work and execute with more than one programs
simultaneously. This process is known as multi threading.
Process:
● A process is a self contained execution environment and it can be seen as a program or
application. However a program itself contains multiple processes inside it. Java runtime
environment runs as a single process which contains different classes and programs as
processes.
What is thread?
A thread is a:
● Facility to allow multiple activities within a single process
● Referred as lightweight process
● A thread is a series of executed statements
● Each thread has its own program counter, stack and local variables
● A thread is a nested sequence of method calls
● Its shares memory, files and per-process state
Whats the need of a thread or why we use Threads?
● To perform asynchronous or background processing
● Increases the responsiveness of GUI applications
● Take advantage of multiprocessor systems
● Simplify program logic when there are multiple independent entities
What happens when a thread is invoked?
● When a thread is invoked, there will be two paths of execution. One path will execute the
thread and the other path will follow the statement after the thread invocation. There will
be a separate stack and memory space for each thread.
Thread:
● A thread is actually a lightweight process. Unlike many other computer languages, Java
provides built-in support for multithreaded programming.
● A multithreaded 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 the
execution.
● A multi-threaded program contains two or more parts that can run concurrently and each
part can handle a different task at the same time making optimal use of the available
resources specially when your computer has multiple CPUs.
● Multitasking is when multiple processes share common processing resources such as a
CPU. Multi-threading extends the idea of multitasking into applications where you can
subdivide specific operations within a single application into individual threads. Each of
the threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.
● Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.

Prepared By:Prof.Shweta JoshiPage 1


Indian Academy Degree College
Faculty of BCA

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to


utilize the CPU. Multitasking can be achieved in two ways:
o Process-based Multitasking (Multiprocessing)

Prepared By:Prof.Shweta JoshiPage 2


Indian Academy Degree College
Faculty of BCA

o Thread-based Multitasking (Multithreading)


1) Process-based Multitasking (Multiprocessing)
o Each process has an address in memory. In other words, each process allocates a separate
memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and loading
registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.

Creation of threads:
● Java provides Thread class to achieve thread programming. Thread class provides
constructors and methods to create and perform operations on a thread. Thread class
extends Object class and implements Runnable interface.
● Threads are implemented in the form of objects that contain a method call run().
● It makes up the entire body of a thread and is the only method in which thread’s
behaviour can be implemented.
Syntax:
public void run()
{
………
}
run() should be invoked by an object of thread and it can be achieved by creating and initiating it
with the help of start().

1. Extending thread class:


• The first way to create a thread is to create a new class that extends Thread class using
the following two simple steps. This approach provides more flexibility in handling
multiple threads created using available methods in Thread class.

Prepared By:Prof.Shweta JoshiPage 3


Indian Academy Degree College
Faculty of BCA

Step 1: Override run() Method


• You will need to override run( ) method available in Thread class. This method provides
an entry point for the thread and you will put your complete business logic inside this
method. Following is a simple syntax of run() method −
public void run( )

Step 2: Call Thread using start() Method


• Once Thread object is created, you can start it by calling start() method, which executes
a call to run( ) method. Following is a simple syntax of start() method −
void start( );

Class threadname extends Thread


{
…….
}
Example:
public class ThreadExample1 extends Thread {
public void run()
{
for(int i=0;i<4;i++){
System.out.println(i);
}
public static void main( String args[] )
{
ThreadExample1 t1 = new ThreadExample1();
t1.start();
ThreadExample1 t2 = new ThreadExample1();
t2.start();
}
}

2. Implementing runnable Interface:


• In Java, we can also create a thread by implementing the runnable interface. The runnable
interface provides us both the run() method and the start() method.
• If your class is intended to be executed as a thread then you can achieve this by
implementing a Runnable interface. You will need to follow three basic steps −
Prepared By:Prof.Shweta JoshiPage 4
Indian Academy Degree College
Faculty of BCA

• Step 1: Implement run() Method


• As a first step, you need to implement a run() method provided by a Runnable interface.
This method provides an entry point for the thread and you will put your complete
business logic inside this method. Following is a simple syntax of the run() method −
public void run( )
• Step 2: Instantiate a Thread Object
• As a second step, you will instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String threadName);
• Where, threadObj is an instance of a class that implements the Runnable interface
and threadName is the name given to the new thread.

• Step 3: Call Thread using start() Method


• Once a Thread object is created, you can start it by calling start() method, which
executes a call to run( ) method. Following is a simple syntax of start() method −
void start();
Example:
class RunnableDemo implements Runnable {
private Thread t;
String name;
RunnableDemo( String name) {
this.name = name;
System.out.println("Creating " + name );
}
public void run() {
try {
for(int i = 4; i > 0; i--) {
System.out.println( i);
}
} catch (Exception e) {
System.out.println(e);
}
}
public void start () {
t = new Thread (this, "one");
t.start ();
}

Prepared By:Prof.Shweta JoshiPage 5


Indian Academy Degree College
Faculty of BCA

}
public class ThreadEx {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo("one");
R1.start();
RunnableDemo R2 = new RunnableDemo( "two");
R2.start();
}
}
Lifecycle of thread:

Prepared By:Prof.Shweta JoshiPage 6


Indian Academy Degree College
Faculty of BCA

Prepared By:Prof.Shweta JoshiPage 7


Indian Academy Degree College
Faculty of BCA

Prepared By:Prof.Shweta JoshiPage 8


Indian Academy Degree College
Faculty of BCA

Example:
class A extends Thread
{
public void run()
{
try{
for(int i=0;i<4;i++)
{
if(i==1)
{
yield();
System.out.println("yield method is called");
System.out.println("From thread A:"+i);
}
}
}
catch(Exception e){
System.out.println(e);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
try{

Prepared By:Prof.Shweta JoshiPage 9


Indian Academy Degree College
Faculty of BCA

for(int i=1;i<4;i++)
{
System.out.println("From thread B:"+i);
if(i==2)
stop();
}
}
catch(Exception e){
System.out.println(e);
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run()
{

try{
for(int i=0;i<4;i++)
{
System.out.println("From thread c:"+i);
if(i==1)
{
try
{
sleep(7000);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
catch(Exception e){
System.out.println(e);
Prepared By:Prof.Shweta JoshiPage 10
Indian Academy Degree College
Faculty of BCA

}
System.out.println("Exit from thread c");
}
}
class ThreadLifecycle
{
public static void main(String args[])
{
A a=new A();
B b=new B();
C c=new C();
System.out.println("Start thread A:");
a.start();
Thread t=Thread.currentThread();
System.out.println("Current thread is:"+t);
System.out.println("Start thread B:");
b.start();
System.out.println("Start thread C:");
c.start();
}
}

Thread class and its methods:


Thread class provide constructors and methods to create and perform operations on a thread.Thread class
extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
4. (temporarily cease execution) for the specified number of milliseconds.
5. public void join(): waits for a thread to die.

Prepared By:Prof.Shweta JoshiPage 11


Indian Academy Degree College
Faculty of BCA

6. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
7. public int getPriority(): returns the priority of the thread.
8. public int setPriority(int priority): changes the priority of the thread.
9. public String getName(): returns the name of the thread.
10. public void setName(String name): changes the name of the thread.
11. public Thread currentThread(): returns the reference of currently executing thread.
12. public int getId(): returns the id of the thread.
13. public Thread.State getState(): returns the state of the thread.
14. public boolean isAlive(): tests if the thread is alive.
15. public void yield(): causes the currently executing thread object to temporarily pause and allow other
threads to execute.
16. public void suspend(): is used to suspend the thread(depricated).
17. public void resume(): is used to resume the suspended thread(depricated).
18. public void stop(): is used to stop the thread(depricated).
19. public boolean isDaemon(): tests if the thread is a daemon thread.
20. public void setDaemon(boolean b): marks the thread as daemon or user thread.
21. public void interrupt(): interrupts the thread.
22. public boolean isInterrupted(): tests if the thread has been interrupted.
23. public static boolean interrupted(): tests if the current thread has been interrupted.

2.Synchronization in multiple threads or Multithreading:


● For example suppose one thread may try to read a file while another thread is still writing
to a same file then depends on situation we get different results this differences generates
a problem to overcome this java gives a functionality called “Synchronization”.
● Synchronization in java is the capability to control the access of multiple threads to
any shared resource.
● Java Synchronization is better option where we want to allow only one thread to access
the shared resource.
● Generally synchronization is used
1. To prevent thread interference.
2. To prevent consistency problem.

Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization

Prepared By:Prof.Shweta JoshiPage 12


Indian Academy Degree College
Faculty of BCA

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. This can be done by three ways in java:
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)

For example:
Without synchronization
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}

}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
Prepared By:Prof.Shweta JoshiPage 13
Indian Academy Degree College
Faculty of BCA

}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
100
200
10
300
15
400
20
500
25
With synchronization
Using synchronized method
● If you declare any method as synchronized, it is known as synchronized method.
● Synchronized method is used to lock an object for any shared resource.
● When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the thread completes its task.
Example:
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
Prepared By:Prof.Shweta JoshiPage 14
Indian Academy Degree College
Faculty of BCA

}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
Prepared By:Prof.Shweta JoshiPage 15
Indian Academy Degree College
Faculty of BCA

100
200
300
400
500

Synchronized Block in Java


● Synchronized block can be used to perform synchronization on any specific resource of
the method.
● Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
● If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
● Synchronized block is used to lock an object for any shared resource.
● Scope of synchronized block is smaller than the method.

Syntax to use synchronized block


synchronized (object reference expression) {
//code block
}

Example:
class Table{
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){

Prepared By:Prof.Shweta JoshiPage 16


Indian Academy Degree College
Faculty of BCA

this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronizedBlock1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Output:
5
10
15
20
25
100
200
300
400
500

Prepared By:Prof.Shweta JoshiPage 17


Indian Academy Degree College
Faculty of BCA

Static Synchronization
If you make any static method as synchronized, the lock will be on the class not on object.

Here using synchronized method or block we can acquire lock between t1 and t2 or t3 and t4 but
there is no locking process between t1 and t3 or t2 and t4 so to apply lock static synchronization
is used.
Example:
class Table{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
}
}
class MyThread2 extends Thread{
public void run(){
Table.printTable(10);
}
}
class MyThread3 extends Thread{

Prepared By:Prof.Shweta JoshiPage 18


Indian Academy Degree College
Faculty of BCA

public void run(){


Table.printTable(100);
}
}
class MyThread4 extends Thread{
public void run(){
Table.printTable(1000);
}
}
public class TestSynchronization4{
public static void main(String t[]){
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}

Synchronized block on a class lock:


● The block synchronizes on the lock of the object denoted by the reference .class name
.class. A static synchronized method printTable(int n) in class Table is equivalent to the
following declaration:
static void printTable(int n) {
synchronized (Table.class) { // Synchronized block on class A
// ...
}
}

3.The collection Framework:


● A collection — sometimes called a container — is simply an object that groups multiple
elements like classes and interfaces into a single unit.A collections framework is a
unified architecture for representing and manipulating collections.
● It is used to Reduce programming effort

Prepared By:Prof.Shweta JoshiPage 19


Indian Academy Degree College
Faculty of BCA

● Increases program speed and quality


● Reduces effort to learn and to use new APIs
● Reduces effort to design new APIs
All collections frameworks contain the following:
● Interfaces: These are abstract data types that represent collections. Interfaces allow
collections to be manipulated independently of the details of their representation.
● Implementations: These are the concrete implementations of the collection interfaces.
● Algorithms: These are the methods that perform useful computations, such as searching
and sorting, on objects that implement collection interfaces. The algorithms are said to be
polymorphic: that is, the same method can be used on many different implementations of
the appropriate collection interface. In essence, algorithms are reusable functionality.
The Collection Interface
● It declares the core methods that all collections will have. The Collection interface is the
root interface of the Java collections framework.
● There is no direct implementation of this interface. However, it is implemented through
its subinterfaces like List, Set, and Queue.
● For example, the ArrayList class implements the List interface which is a subinterface of
the Collection Interface.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:
Method Description
add(Object) This method is used to add an object to the collection.
This method adds all the elements in the given collection to this
addAll(Collection c)
collection.
clear() This method removes all of the elements from this collection.
This method returns true if the collection contains the specified
contains(Object o)
element.
This method is used to return the hash code value for this
hashCode()
collection.
isEmpty() This method returns true if this collection contains no elements.
This method returns an iterator over the elements in this
iterator()
collection.
This method is used to remove the given object from the
remove(Object o) collection. If there are duplicate values, then this method removes
the first occurrence of the object.
This method is used to return the number of elements in the
size()
collection.

Prepared By:Prof.Shweta JoshiPage 20


Indian Academy Degree College
Faculty of BCA

The List Interface:


● The List interface provides a way to store the ordered collection. It is a child interface of
Collection.
● It is an ordered collection of objects in which duplicate values can be stored. Since List
preserves the insertion order, it allows positional access and insertion of elements.
● In order to use functionalities of the List interface, we can use these classes:

These classes are defined in the Collections framework and implement the List interface.

Example:
/ ArrayList implementation of List
List<String> list1 = new ArrayList<>();
// LinkedList implementation of List
List<String> list2 = new LinkedList<>();

Methods of List
Some of the commonly used methods of the Collection interface that's also available in the List
interface are:
● add() - adds an element to a list
● addAll() - adds all elements of one list to another
● get() - helps to randomly access elements from lists
● iterator() - returns iterator object that can be used to sequentially access elements of lists
● set() - changes elements of lists
● remove() - removes an element from the list
● removeAll() - removes all the elements from the list
● clear() - removes all the elements from the list (more efficient than removeAll())
● size() - returns the length of lists
● toArray() - converts a list into an array
● contains() - returns true if a list contains specified element

Example:
import java.util.List;
import java.util.ArrayList;
class ListDemo {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
Prepared By:Prof.Shweta JoshiPage 21
Indian Academy Degree College
Faculty of BCA

numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("List: " + numbers);
int number = numbers.get(2);
System.out.println("Accessed Element: " + number);
int removedNumber = numbers.remove(1);
System.out.println("Removed Element: " + removedNumber);
}
}
Output:
List: [1, 2, 3]
Accessed Element: 3
Removed Element: 2

Collection class:
● Java collection class is used exclusively with static methods that operate on or return
collections. It inherits Object class.

ArrayList class:
● The java.util.ArrayList class provides resizable-array and implements the List interface.
● It implements all optional list operations and it also permits all elements, includes null.
● It provides methods to manipulate the size of the array that is used internally to store the
list.
● The constant factor is low compared to that for the LinkedList implementation.

Constructor list:
Sr.No. Constructor & Description
ArrayList( )
1
This constructor builds an empty array list.
ArrayList(Collection c)
2 This constructor builds an array list that is initialized with the elements of the collection
c.
ArrayList(int capacity)
This constructor builds an array list that has the specified initial capacity. The capacity is
3
the size of the underlying array that is used to store the elements. The capacity grows
automatically as elements are added to an array list.

List of Methods:
Sr.No. Method & Description
1 void add(int index, Object element)

Prepared By:Prof.Shweta JoshiPage 22


Indian Academy Degree College
Faculty of BCA

Inserts the specified element at the specified position index in this list. Throws
IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >
size()).
boolean add(Object o)
2
Appends the specified element to the end of this list.
Object get(int index)
Returns the element at the specified position in this list. Throws
9
IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >=
size()).
int indexOf(Object o)
10 Returns the index in this list of the first occurrence of the specified element, or -1 if the
List does not contain this element.
Object remove(int index)
12 Removes the element at the specified position in this list. Throws
IndexOutOfBoundsException if the index out is of range (index < 0 || index >= size()).

Example:
import java.util.*;
public class ArrayListDemo {
public static void main(String args[]) {
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
System.out.println("Contents of al: " + al);
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
Output:
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Prepared By:Prof.Shweta JoshiPage 23
Indian Academy Degree College
Faculty of BCA

Contents of al: [C, A2, E, B, D]

Iterating elements of collection:


Java Iterators:
● Java provides an interface Iterator to iterate over the Collections, such as List, Map, etc.
It contains two key methods next() and hasNaxt() that allows us to perform an iteration
over the List.
● next(): The next() method perform the iteration in forward order. It returns the next
element in the List.
● hasNext(): The hasNext() method helps us to find the last element of the List. It checks if
the List has the next element or not.

Example:
import java.util.*;
public class IterateListExample3
{
public static void main(String args[])
{
List<String> city = Arrays.asList("Boston", "San Diego", "Las Vegas", "Houston", "Miami", "A
ustin");
Iterator<String> cityIterator = city.iterator();
while(cityIterator.hasNext())
{
System.out.println(cityIterator.next());
}
}
}
Output:
Boston
San Diego
Las Vegas
Houston
Miami
Austin

4.Java Bean:
● A java bean is a specially constructed java class written in java and coded
according to the JavaBeans API specifications.
● A java bean is a reusable software component that can be manipulated
visually in an application builder tool.
● Characteristics of JavaBean: Should be serializable and implement the serializable
interface. Provides default,no argument constructor. It may have a number of properties
Prepared By:Prof.Shweta JoshiPage 24
Indian Academy Degree College
Faculty of BCA

which can be read or written. It may have number of “getter” and “setter” method for
properties.
● A bean encapsulates many objects into one object so we can access this object from
multiple places. Java Beans are not actually required to inherit a particular base
class or implement a particular interface.
● Java Bean provides support for introspection (it is a process by which an application
builder discovers the properties, methods and events that are associated with
JavaBeans.), properties, customization, events, persistent storage.

Advantages of Java Bean:


● Provides property of “Write once and run anywhere”. Can work in different local
platforms.
● Beans have the capability of capturing the events sent by other objects and
vice versa enabling object communication.
● The properties,events and methods of the bean can be controlled by the
application developer. It can be configured with the help of auxiliary s/w during design
time so no bother at runtime.
● The configuration setting can be made persistent so it is reused. Configuration setting of
a bean can be saved in persistent storage and restored later.

Properties, Methods and Events in Java Beans:


1. Properties: Properties are basically are named attributes associated with a bean that can
be read or written by calling appropriate methods on the bean.
EX. a bean might have a “foreground” property that represents its foreground
color.This property might read by calling a “Color getForeground()” and
updated by calling a “void set Foreground(Color c)”

2. Methods: Methods a java bean exports are just normal java methods which can be
called from other components or from a scripting environment.By default all of
a bean’s public methods will be exported but a bean can choose to export
only a subset of its public methods.

3. Events: Events provide a way for one component to notify other components that
something interesting has happened. When the event source detects that
something interesting happens it will call an appropriate method on the event
listener object.

Java Bean Property and Methods:


● A java Bean property is a named attribute that can be accessed by the user of
the object.The attribute can be of any java data type. Java Bean properties are accessed
through two methods in the javaBean’s implementation class:

Prepared By:Prof.Shweta JoshiPage 25


Indian Academy Degree College
Faculty of BCA

1)getPropertyName()(Read only): This method is called accessor. Return type of this method
must be data type of attribute,because it will return
value of attribute. No parameterized method. Ex.property name is firstName so method would
be getFirstName().
2)setPropertyName()(Write only): This method is called mutator. Return type of this method
must be void because it is used to set value of the
property. Single parameterized method having type of attribute. Ex.property name is firstName
so method name would be setFirstName().

Example:
public class person {
private String firstName = null;
private String lastName = null;
private int age = 0;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

Introduction to Network Programming:


Java Networking is a concept of connecting two or more computing devices together so that we
can share resources.
Java socket programming provides facility to share data between different computing devices.
Advantage of Java Networking
1. Sharing resources

Prepared By:Prof.Shweta JoshiPage 26


Indian Academy Degree College
Faculty of BCA

2. Centralize software management


The java.net package supports two protocols,
1. TCP: Transmission Control Protocol provides reliable communication between the
sender and receiver. TCP is used along with the Internet Protocol referred as TCP/IP.

2. UDP: User Datagram Protocol provides a connection-less protocol service by allowing


packet of data to be transferred along two or more nodes.

Terminology:
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed
of octets that range from 0 to 255.
It is a logical address that can be changed.

2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
○ TCP

○ FTP

○ Telnet

○ SMTP

○ POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a communication
endpoint between applications.
The port number is associated with the IP address for communication between two applications.

4) MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC address.
or example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.

5) Connection-oriented and connection-less protocol

Prepared By:Prof.Shweta JoshiPage 27


Indian Academy Degree College
Faculty of BCA

In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but


slow. The example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not
reliable but fast. The example of connection-less protocol is UDP.

6) Socket
A socket is an endpoint between two way communications.

Java Socket Programming:

● Java Socket programming is used for communication between the applications running
on different JRE.
● Java Socket programming can be connection-oriented or connection-less.
● Socket and ServerSocket classes are used for connection-oriented socket programming
and DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.

The client in socket programming must know two information:

1. IP Address of Server, and


2. Port number.
● Here, we are going to make one-way client and server communication. In this
application, client sends a message to the server, server reads the message and prints it.
● Here, two classes are being used: Socket and ServerSocket. The Socket class is used to
communicate client and server. Through this class, we can read and write message.
● The ServerSocket class is used at server-side. The accept() method of ServerSocket class
blocks the console until the client is connected. After the successful connection of client,
it returns the instance of Socket at server-side.

Prepared By:Prof.Shweta JoshiPage 28


Indian Academy Degree College
Faculty of BCA

Socket class:

● A socket is simply an endpoint for communications between the machines. The Socket
class can be used to create a socket.

methods:

Method Description

1) public InputStream getInputStream() returns the InputStream attached with this socket.

2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.

3) public synchronized void close() closes this socket

Prepared By:Prof.Shweta JoshiPage 29


Indian Academy Degree College
Faculty of BCA

ServerSocket class:

● The ServerSocket class can be used to create a server socket. This object is used to
establish communication with the clients.

methods:

Method Description

1) public Socket accept() returns the socket and establish a connection between server
and client.

2) public synchronized void closes the server socket.


close()

Example of Java Socket Programming:

Creating Server:

● To create the server application, we need to create the instance of ServerSocket class.
● we are using 6666 port number for the communication between the client and server. You
may also choose any other port number.
● The accept() method waits for the client. If clients connects with the given port number, it
returns an instance of Socket.

ServerSocket ss=new ServerSocket(6666);

Socket s=ss.accept();//establishes connection and waits for the client

Creating Client:

Prepared By:Prof.Shweta JoshiPage 30


Indian Academy Degree College
Faculty of BCA

● To create the client application, we need to create the instance of Socket class. Here, we
need to pass the IP address or hostname of the Server and a port number. Here, we are
using "localhost" because our server is running on same system.

Socket s=new Socket("localhost",6666);

File: MyServer.java

import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
Output:

message= Hello Server

Prepared By:Prof.Shweta JoshiPage 31


Indian Academy Degree College
Faculty of BCA

Prepared By:Prof.Shweta JoshiPage 32

You might also like