You are on page 1of 79

1 |M.

sc sem I OOPs USING JAVA

UNIT III Network-socket Programming and JDBC


(1) lntroduction to Collectlons and "lntrbduction to Generics
Collections in Java
The Collection in Java is a framework that provides an architecture to store and manipulate the group of
objects.

Java Collections can achieve all the operations that you perform on a data such as searching, sorting,
insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set,
List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet,
TreeSet).

What is Collection in Java


A Collection represents a single unit of objects, i.e., a group.ides readymade architecture.

o It represents a set of classes and interfaces.


o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating a group of objects.
It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

Do You Know?

o What are the two ways to iterate the elements of a collection?


o What is the difference between ArrayList and LinkedList classes in collection framework?
o What is the difference between ArrayList and Vector classes in collection framework?
o What is the difference between HashSet and HashMap classes in collection framework?
o What is the difference between HashMap and Hashtable class?
o What is the difference between Iterator and Enumeration interface in collection framework?
o How can we sort the elements of an object? What is the difference between Comparable and Comparator
interfaces?
o What does the hashcode() method?
o What is the difference between Java collection and Java collections?
2 |M.sc sem I OOPs USING JAVA

Hierarchy of Collection Framework


Let us see the hierarchy of Collection framework. The java.util package contains all
the classes and interfaces for the Collection framework.

Methods of Collection interface


There are many methods declared in the Collection interface. They are as follows:

No. Method Description

1 public boolean add(E e) It is used to insert an element in this collection.

2 public boolean addAll(Collection<? It is used to insert the specified collection elements in the
extends E> c) invoking collection.

3 public boolean remove(Object element) It is used to delete an element from the collection.
3 |M.sc sem I OOPs USING JAVA

4 public boolean removeAll(Collection<?> It is used to delete all the elements of the specified collection
c) from the invoking collection.

5 default boolean removeIf(Predicate<? It is used to delete all the elements of the collection that satisfy
super E> filter) the specified predicate.

6 public boolean retainAll(Collection<?> It is used to delete all the elements of invoking collection
c) except the specified collection.

7 public int size() It returns the total number of elements in the collection.

8 public void clear() It removes the total number of elements from the collection.

9 public boolean contains(Object element) It is used to search an element.

10 public boolean It is used to search the specified collection in the collection.


containsAll(Collection<?> c)

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime type of the
returned array is that of the specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> parallelStream() It returns a possibly parallel Stream with the collection as its
source.

16 default Stream<E> stream() It returns a sequential Stream with the collection as its source.

17 default Spliterator<E> spliterator() It generates a Spliterator over the specified elements in the
collection.

18 public boolean equals(Object element) It matches two collections.

19 public int hashCode() It returns the hash code number of the collection.

Iterator interface
4 |M.sc sem I OOPs USING JAVA

Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

No. Method Description

1 public boolean hasNext() It returns true if the iterator has more elements otherwise it returns false.

2 public Object next() It returns the element and moves the cursor pointer to the next element.

3 public void remove() It removes the last elements returned by the iterator. It is less used.

Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection interface extends the
Iterable interface and therefore all the subclasses of Collection interface also implement the Iterable
interface.

It contains only one abstract method. i.e.,

1. Iterator<T> iterator()

It returns the iterator over the elements of type T.

Collection Interface
The Collection interface is the interface which is implemented by all the classes in the collection framework.
It declares the methods that every collection will have. In other words, we can say that the Collection
interface builds the foundation on which the collection framework depends.

Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll ( Collection c),
void clear(), etc. which are implemented by all the subclasses of Collection interface.

List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure in which we
can store the ordered collection of objects. It can have duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

To instantiate the List interface, we must use :


5 |M.sc sem I OOPs USING JAVA

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete, and access the elements from
the list.

The classes that implement the List interface are given below.

ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate element of
different data types. The ArrayList class maintains the insertion order and is non-synchronized. The
elements stored in the ArrayList class can be randomly accessed. Consider the following example.

1. import java.util.*;
2. class TestJavaCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }

Output:

LinkedList implements the Collection interface. It uses a doubly linked list internally to store the elements.
It can store the duplicate elements. It maintains the insertion order and is not synchronized. In LinkedList,
the manipulation is fast because no shifting is required.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection2{
3. public static void main(String args[]){
6 |M.sc sem I OOPs USING JAVA

4. LinkedList<String> al=new LinkedList<String>();


5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is synchronized
and contains many methods that are not the part of Collection framework.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection3{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();
5. v.add("Ayush");
6. v.add("Amit");
7. v.add("Ashish");
8. v.add("Garima");
9. Iterator<String> itr=v.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The stack
contains all of the methods of Vector class and also provides its methods like boolean push(), boolean
peek(), boolean push(object o), which defines its properties.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection4{
7 |M.sc sem I OOPs USING JAVA

3. public static void main(String args[]){


4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is used to
hold the elements which are about to be processed. There are various classes like PriorityQueue, Deque,
and ArrayDeque which implements the Queue interface.

Queue interface can be instantiated as:

1. Queue<String> q1 = new PriorityQueue();


2. Queue<String> q2 = new ArrayDeque();

There are various classes that implement the Queue interface, some of them are given below.

PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or objects which are to be
processed by their priorities. PriorityQueue doesn't allow null values to be stored in the queue.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection5{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. queue.add("Amit Sharma");
8 |M.sc sem I OOPs USING JAVA

6. queue.add("Vijay Raj");
7. queue.add("JaiShankar");
8. queue.add("Raj");
9. System.out.println("head:"+queue.element());
10. System.out.println("head:"+queue.peek());
11. System.out.println("iterating the queue elements:");
12. Iterator itr=queue.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. queue.remove();
17. queue.poll();
18. System.out.println("after removing two elements:");
19. Iterator<String> itr2=queue.iterator();
20. while(itr2.hasNext()){
21. System.out.println(itr2.next());
22. }
23. }
24. }

Output:

Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the elements from both
the side. Deque stands for a double-ended queue which enables us to perform the operations at both the
ends.

Deque can be instantiated as:

1. Deque d = new ArrayDeque();

ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we can
add or delete the elements from both the ends.

ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection6{
3. public static void main(String[] args) {
9 |M.sc sem I OOPs USING JAVA

4. //Creating Deque and adding elements


5. Deque<String> deque = new ArrayDeque<String>();
6. deque.add("Gautam");
7. deque.add("Karan");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }

Output:

Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It represents the
unordered set of elements which doesn't allow us to store the duplicate items. We can store at most one
null value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.

Set can be instantiated as:

1. Set<data-type> s1 = new HashSet<data-type>();


2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();

HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table for storage.
Hashing is used to store the elements in the HashSet. It contains unique items.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection7{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
10 |M.sc sem I OOPs USING JAVA

12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the HashSet class
and implements Set interface. Like HashSet, It also contains unique elements. It maintains the insertion
order and permits null elements.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection8{
3. public static void main(String args[]){
4. LinkedHashSet<String> set=new LinkedHashSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Ravi");
8. set.add("Ajay");
9. Iterator<String> itr=set.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

Output:

SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its elements. The elements of
the SortedSet are arranged in the increasing (ascending) order. The SortedSet provides the additional
methods that inhibit the natural ordering of the elements.

The SortedSet can be instantiated as:

1. SortedSet<data-type> set = new TreeSet();


11 |M.sc sem I OOPs USING JAVA

TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also
contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The elements in
TreeSet stored in ascending order.

Consider the following example:

1. import java.util.*;
2. public class TestJavaCollection9{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> set=new TreeSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

(2) Generics
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the code
stable by detecting the bugs at compile time.

Before generics, we can store any type of objects in the collection, i.e., non-generic. Now generics force the
java programmer to store a specific type of objects.

Advantage of Java Generics


There are mainly 3 advantages of generics. They are as follows:

1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store other
objects.

Without Generics, we can store any type of objects.


12 |M.sc sem I OOPs USING JAVA

1. List list = new ArrayList();


2. list.add(10);
3. list.add("10");
4. With Generics, it is required to specify the type of object we need to store.
5. List<Integer> list = new ArrayList<Integer>();
6. list.add(10);
7. list.add("10");// compile-time error

2) Type casting is not required: There is no need to typecast the object.

Before Generics, we need to type cast.

1. List list = new ArrayList();


2. list.add("hello");
3. String s = (String) list.get(0);//typecasting
4. After Generics, we don't need to typecast the object.
5. List<String> list = new ArrayList<String>();
6. list.add("hello");
7. String s = list.get(0);

3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good
programming strategy says it is far better to handle the problem at compile time than runtime.

1. List<String> list = new ArrayList<String>();


2. list.add("hello");
3. list.add(32);//Compile Time Error

Syntax to use generic collection

1. ClassOrInterface<Type>

Example to use Generics in java

1. ArrayList<String>

Full Example of Generics in Java


Here, we are using the ArrayList class, but you can use any collection class such as ArrayList, LinkedList,
HashSet, TreeSet, HashMap, Comparator etc.

1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
13 |M.sc sem I OOPs USING JAVA

6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }

1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
Test it Now

Output:Example of Java Generics using Map


Now we are going to use map elements using generics. Here, we need to pass key and value. Let us
understand it by a simple example:

1. import java.util.*;
2. class TestGenerics2{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
14 |M.sc sem I OOPs USING JAVA

5. map.put(1,"vijay");
6. map.put(4,"umesh");
7. map.put(2,"ankit");
8.
9. //Now use Map.Entry for Set and Iterator
10. Set<Map.Entry<Integer,String>> set=map.entrySet();
11.
12. Iterator<Map.Entry<Integer,String>> itr=set.iterator();
13. while(itr.hasNext()){
14. Map.Entry e=itr.next();//no need to typecast
15. System.out.println(e.getKey()+" "+e.getValue());
16. }
17.
18. }}
Test it Now

Output

Generic class
A class that can refer to any type is known as a generic class. Here, we are using the T type parameter to
create the generic class of specific type.

Let's see a simple example to create and use the generic class.

Creating a generic class:

1. class MyGen<T>{
2. T obj;
3. void add(T obj){this.obj=obj;}
4. T get(){return obj;}
5. }

The T type indicates that it can refer to any type (like String, Integer, and Employee). The type you specify
for the class will be used to store and retrieve the data.

Using generic class:

Let's see the code to use the generic class.

1. class TestGenerics3{
2. public static void main(String args[]){
3. MyGen<Integer> m=new MyGen<Integer>();
4. m.add(2);
15 |M.sc sem I OOPs USING JAVA

5. //m.add("vivek");//Compile time error


6. System.out.println(m.get());
7. }}
Test it Now

Output

Type Parameters
The type parameters naming conventions are important to learn generics thoroughly. The common type
parameters are as follows:

1. T - Type
2. E - Element
3. K - Key
4. N - Number
5. V - Value

Generic Method
Like the generic class, we can create a generic method that can accept any type of arguments. Here, the
scope of arguments is limited to the method where it is declared. It allows static as well as non-static
methods.

Let's see a simple example of java generic method to print array elements. We are using here E to denote
the element.

1. public class TestGenerics4{


2.
3. public static < E > void printArray(E[] elements) {
4. for ( E element : elements){
5. System.out.println(element );
6. }
7. System.out.println();
8. }
9. public static void main( String args[] ) {
10. Integer[] intArray = { 10, 20, 30, 40, 50 };
11. Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','T' };
12.
13. System.out.println( "Printing Integer Array" );
14. printArray( intArray );
15.
16. System.out.println( "Printing Character Array" );
16 |M.sc sem I OOPs USING JAVA

17. printArray( charArray );


18. }
19. }
Test it Now

Output

Wildcard in Java Generics


The ? (question mark) symbol represents the wildcard element. It means any type. If we write <? extends
Number>, it means any child class of Number, e.g., Integer, Float, and double. Now we can call the method
of Number class through any child class object.

We can use a wildcard as a type of a parameter, field, return type, or local variable. However, it is not
allowed to use a wildcard as a type argument for a generic method invocation, a generic class
instance creation, or a supertype.

Let's understand it by the example given below:

1. import java.util.*;
2. abstract class Shape{
3. abstract void draw();
4. }
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. class GenericTest{
12. //creating a method that accepts only child class of Shape
13. public static void drawShapes(List<? extends Shape> lists){
14. for(Shape s:lists){
15. s.draw();//calling method of Shape class by child class instance
16. }
17. }
18. public static void main(String args[]){
19. List<Rectangle> list1=new ArrayList<Rectangle>();
20. list1.add(new Rectangle());
21.
22. List<Circle> list2=new ArrayList<Circle>();
23. list2.add(new Circle());
24. list2.add(new Circle());
17 |M.sc sem I OOPs USING JAVA

25.
26. drawShapes(list1);
27. drawShapes(list2);
28. }}

Output

Upper Bounded Wildcards


The purpose of upper bounded wildcards is to decrease the restrictions on a variable. It restricts the
unknown type to be a specific type or a subtype of that type. It is used by declaring wildcard character
("?") followed by the extends (in case of, class) or implements (in case of, interface) keyword, followed by
its upper bound.

Syntax

1. List<? extends Number>

Here,

? is a wildcard character.

extends, is a keyword.

Number, is a class present in java.lang package

Suppose, we want to write the method for the list of Number and its subtypes (like Integer, Double).
Using List<? extends Number> is suitable for a list of type Number or any of its subclasses
whereas List<Number> works with the list of type Number only. So, List<? extends Number> is less
restrictive than List<Number>.

Example of Upper Bound Wildcard

In this example, we are using the upper bound wildcards to write the method for List<Integer> and
List<Double>.

1. import java.util.ArrayList;
2.
3. public class UpperBoundWildcard {
4.
5.
6. private static Double add(ArrayList<? extends Number> num) {
7.
8. double sum=0.0;
9.
10. for(Number n:num)
18 |M.sc sem I OOPs USING JAVA

11. {
12. sum = sum+n.doubleValue();
13. }
14.
15. return sum;
16. }
17.
18. public static void main(String[] args) {
19.
20. ArrayList<Integer> l1=new ArrayList<Integer>();
21. l1.add(10);
22. l1.add(20);
23. System.out.println("displaying the sum= "+add(l1));
24.
25. ArrayList<Double> l2=new ArrayList<Double>();
26. l2.add(30.0);
27. l2.add(40.0);
28. System.out.println("displaying the sum= "+add(l2));
29.
30.
31. }
32.
33. }
Test it Now

Output

Unbounded Wildcards
The unbounded wildcard type represents the list of an unknown type such as List<?>. This approach can
be useful in the following scenarios: -

o When the given method is implemented by using the functionality provided in the Object class.
o When the generic class contains the methods that don't depend on the type parameter.

Example of Unbounded Wildcards

1. import java.util.Arrays;
2. import java.util.List;
3.
4. public class UnboundedWildcard {
5.
19 |M.sc sem I OOPs USING JAVA

6. public static void display(List<?> list)


7. {
8.
9. for(Object o:list)
10. {
11. System.out.println(o);
12. }
13.
14. }
15.
16.
17. public static void main(String[] args) {
18.
19. List<Integer> l1=Arrays.asList(1,2,3);
20. System.out.println("displaying the Integer values");
21. display(l1);
22. List<String> l2=Arrays.asList("One","Two","Three");
23. System.out.println("displaying the String values");
24. display(l2);
25. }
26.
27. }
Test it Now

Output

Lower Bounded Wildcards


The purpose of lower bounded wildcards is to restrict the unknown type to be a specific type or a
supertype of that type. It is used by declaring wildcard character ("?") followed by the super keyword,
followed by its lower bound.

Syntax

1. List<? super Integer>

Here,

? is a wildcard character.

super, is a keyword.

Integer, is a wrapper class.


20 |M.sc sem I OOPs USING JAVA

Suppose, we want to write the method for the list of Integer and its supertype (like Number, Object).
Using List<? super Integer> is suitable for a list of type Integer or any of its superclasses
whereas List<Integer> works with the list of type Integer only. So, List<? super Integer> is less
restrictive than List<Integer>.

Example of Lower Bound Wildcard

In this example, we are using the lower bound wildcards to write the method for List<Integer> and
List<Number>.

1. import java.util.Arrays;
2. import java.util.List;
3.
4. public class LowerBoundWildcard {
5.
6. public static void addNumbers(List<? super Integer> list) {
7.
8. for(Object n:list)
9. {
10. System.out.println(n);
11. }
12.
13.
14.
15. }
16. public static void main(String[] args) {
17.
18. List<Integer> l1=Arrays.asList(1,2,3);
19. System.out.println("displaying the Integer values");
20. addNumbers(l1);
21.
22. List<Number> l2=Arrays.asList(1.0,2.0,3.0);
23. System.out.println("displaying the Number values");
24. addNumbers(l2);
25. }
26.
27. }
Test it Now

Output
21 |M.sc sem I OOPs USING JAVA

(3) Java Serialization


Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly
used in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization where byte-stream is converted into an object.
The serialization and deserialization process is platform-independent, it means you can serialize an object
on one platform and deserialize it on a different platform.

For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for
deserialization we call the readObject() method of ObjectInputStream class.

We must have to implement the Serializable interface for serializing the object.

Advantages of Java Serialization


It is mainly used to travel object's state on the network (that is known as marshalling).

java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes so
that the objects of these classes may get a certain capability. The Cloneable and Remote are also marker
interfaces.

The Serializable interface must be implemented by the class whose object needs to be persisted.

The String class and all the wrapper classes implement the java.io.Serializable interface by default.

Let's see the example given below:

Student.java
22 |M.sc sem I OOPs USING JAVA

1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }

In the above example, Student class implements Serializable interface. Now its objects can be converted
into stream. The main class implementation of is showed in the next code.

ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects to an OutputStream.
Only objects that support the java.io.Serializable interface can be written to streams.

Constructor

1) public ObjectOutputStream(OutputStream out) throws It creates an ObjectOutputStream that writes to the


IOException {} specified OutputStream.

Important Methods

Method Description

1) public final void writeObject(Object obj) throws It writes the specified object to the
IOException {} ObjectOutputStream.

2) public void flush() throws IOException {} It flushes the current output stream.

3) public void close() throws IOException {} It closes the current output stream.

ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.

Constructor
23 |M.sc sem I OOPs USING JAVA

1) public ObjectInputStream(InputStream in) throws It creates an ObjectInputStream that reads from the
IOException {} specified InputStream.

Important Methods

Method Description

1) public final Object readObject() throws IOException, It reads an object from the input
ClassNotFoundException{} stream.

2) public void close() throws IOException {} It closes ObjectInputStream.

Example of Java Serialization


In this example, we are going to serialize the object of Student class from above code. The writeObject()
method of ObjectOutputStream class provides the functionality to serialize the object. We are saving the
state of the object in the file named f.txt.

Persist.java

1. import java.io.*;
2. class Persist{
3. public static void main(String args[]){
4. try{
5. //Creating the object
6. Student s1 =new Student(211,"ravi");
7. //Creating stream and writing the object
8. FileOutputStream fout=new FileOutputStream("f.txt");
9. ObjectOutputStream out=new ObjectOutputStream(fout);
10. out.writeObject(s1);
11. out.flush();
12. //closing the stream
13. out.close();
14. System.out.println("success");
15. }catch(Exception e){System.out.println(e);}
16. }
17. }

Output:

success
download this example of serialization
24 |M.sc sem I OOPs USING JAVA

Example of Java Deserialization


Deserialization is the process of reconstructing the object from the serialized state. It is the reverse
operation of serialization. Let's see an example where we are reading the data from a deserialized object.

Deserialization is the process of reconstructing the object from the serialized state. It is the reverse
operation of serialization. Let's see an example where we are reading the data from a deserialized object.

Depersist.java

1. import java.io.*;
2. class Depersist{
3. public static void main(String args[]){
4. try{
5. //Creating stream to read the object
6. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
7. Student s=(Student)in.readObject();
8. //printing the data of the serialized object
9. System.out.println(s.id+" "+s.name);
10. //closing the stream
11. in.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }

Java Serialization with Inheritance (IS-A Relationship)


If a class implements Serializable interface then all its sub classes will also be serializable. Let's see the
example given below:

SerializeISA.java

1. import java.io.Serializable;
2. class Person implements Serializable{
3. int id;
4. String name;
5. Person(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
10. class Student extends Person{
11. String course;
25 |M.sc sem I OOPs USING JAVA

12. int fee;


13. public Student(int id, String name, String course, int fee) {
14. super(id,name);
15. this.course=course;
16. this.fee=fee;
17. }
18. }
19. public class SerializeISA
20. {
21. public static void main(String args[])
22. {
23. try{
24. //Creating the object
25. Student s1 =new Student(211,"ravi","Engineering",50000);
26. //Creating stream and writing the object
27. FileOutputStream fout=new FileOutputStream("f.txt");
28. ObjectOutputStream out=new ObjectOutputStream(fout);
29. out.writeObject(s1);
30. out.flush();
31. //closing the stream
32. out.close();
33. System.out.println("success");
34. }catch(Exception e){System.out.println(e);}
35. try{
36. //Creating stream to read the object
37. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
38. Student s=(Student)in.readObject();
39. //printing the data of the serialized object
40. System.out.println(s.id+" "+s.name+" "+s.course+" "+s.fee);
41. //closing the stream
42. in.close();
43. }catch(Exception e){System.out.println(e);}
44. }
45. }

Output:

The SerializeISA class has serialized the Student class object that extends the Person class which is
Serializable. Parent class properties are inherited to subclasses so if parent class is Serializable, subclass
would also be.
26 |M.sc sem I OOPs USING JAVA

Java Serialization with Aggregation (HAS-A Relationship)


If a class has a reference to another class, all the references must be Serializable otherwise serialization
process will not be performed. In such case, NotSerializableException is thrown at runtime.

Address.java

1. class Address{
2. String addressLine,city,state;
3. public Address(String addressLine, String city, String state) {
4. this.addressLine=addressLine;
5. this.city=city;
6. this.state=state;
7. }
8. }

Student.java

1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. Address address;//HAS-A
6. public Student(int id, String name) {
7. this.id = id;
8. this.name = name;
9. }
10. }

Since Address is not Serializable, you cannot serialize the instance of the Student class.

Note: All the objects within an object must be Serializable.

Java Serialization with the static data member


If there is any static data member in a class, it will not be serialized because static is the part of class not
object.

Employee.java

1. class Employee implements Serializable{


2. int id;
3. String name;
4. static String company="SSS IT Pvt Ltd";//it won't be serialized
5. public Student(int id, String name) {
27 |M.sc sem I OOPs USING JAVA

6. this.id = id;
7. this.name = name;
8. }
9. }

Java Serialization with array or collection


Rule: In case of array or collection, all the objects of array or collection must be serializable. If any object is
not serialiizable, serialization will be failed.

Externalizable in java
The Externalizable interface provides the facility of writing the state of an object into a byte stream in
compress format. It is not a marker interface.

The Externalizable interface provides two methods:

o public void writeExternal(ObjectOutput out) throws IOException


o public void readExternal(ObjectInput in) throws IOException

Java Transient Keyword


If you don't want to serialize any data member of a class, you can mark it as transient.

Employee.java

1. class Employee implements Serializable{


2. transient int id;
3. String name;
4. public Student(int id, String name) {
5. this.id = id;
6. this.name = name;
7. }
8. }

Now, id will not be serialized, so when you deserialize the object after serialization, you will not get the
value of id. It will return default value always. In such case, it will return 0 because the data type of id is an
integer.

Visit next page for more details.

SerialVersionUID
The serialization process at runtime associates an id with each Serializable class which is known as
SerialVersionUID. It is used to verify the sender and receiver of the serialized object. The sender and receiver
must be the same. To verify it, SerialVersionUID is used. The sender and receiver must have the same
28 |M.sc sem I OOPs USING JAVA

SerialVersionUID, otherwise, InvalidClassException will be thrown when you deserialize the object. We
can also declare our own SerialVersionUID in the Serializable class. To do so, you need to create a field
SerialVersionUID and assign a value to it. It must be of the long type with static and final. It is suggested
to explicitly declare the serialVersionUID field in the class and have it private also. For example:

1. private static final long serialVersionUID=1L;

Now, the Serializable class will look like this:

Employee.java

1. import java.io.Serializable;
2. class Employee implements Serializable{
3. private static final long serialVersionUID=1L;
4. int id;
5. String name;
6. public Student(int id, String name) {
7. this.id = id;
8. this.name = name;
9. }
10. }

(4) Network Programming


Networking
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
2. Centralize software management

Do You Know ?
o How to perform connection-oriented Socket Programming in networking ?
o How to display the data of any online web page ?
o How to get the IP address of any host name e.g. www.google.com ?
o How to perform connection-less socket programming in networking ?

The java.net package supports two protocols,


29 |M.sc sem I OOPs USING JAVA

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

Java Networking Terminology


The widely used Java networking terminologies are given below:rime Ministers of India | List of Prime Minister of India
(1947-2020)

1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

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:

o TCP
o FTP
o Telnet
o SMTP
o 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
30 |M.sc sem I OOPs USING JAVA

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.

For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.

5) Connection-oriented and connection-less protocol


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.

Visit next page for Java socket programming.

java.net package
The java.net package can be divided into two sections:

1. A Low-Level API: It deals with the abstractions of addresses i.e. networking identifiers, Sockets i.e.
bidirectional data communication mechanism and Interfaces i.e. network interfaces.
2. A High Level API: It deals with the abstraction of URIs i.e. Universal Resource Identifier, URLs i.e. Universal
Resource Locator, and Connections i.e. connections to the resource pointed by URLs.

The java.net package provides many classes to deal with networking applications in Java. A list of these
classes is given below:

o Authenticator
o CacheRequest
o CacheResponse
o ContentHandler
o CookieHandler
o CookieManager
o DatagramPacket
o DatagramSocket
o DatagramSocketImpl
o InterfaceAddress
o JarURLConnection
o MulticastSocket
31 |M.sc sem I OOPs USING JAVA

o InetSocketAddress
o InetAddress
o Inet4Address
o Inet6Address
o IDN
o HttpURLConnection
o HttpCookie
o NetPermission
o NetworkInterface
o PasswordAuthentication
o Proxy
o ProxySelector
o ResponseCache
o SecureCacheResponse
o ServerSocket
o Socket
o SocketAddress
o SocketImpl
o SocketPermission
o StandardSocketOptions
o URI
o URL
o URLClassLoader
o URLConnection
o URLDecoder
o URLEncoder
o URLStreamHandler

List of interfaces available in java.net package:

o ContentHandlerFactory
o CookiePolicy
o CookieStore
o DatagramSocketImplFactory
o FileNameMap
o SocketOption<T>
32 |M.sc sem I OOPs USING JAVA

o SocketOptions
o SocketImplFactory
o URLStreamHandlerFactory
o ProtocolFamily

What we will learn in Networking Tutorial


o Networking and Networking Terminology
o Socket Programming (Connection-oriented)
o URL class
o Displaying data of a webpage by URLConnection class
o InetAddress class
o DatagramSocket and DatagramPacket (Connection-less)

(5) socket Progrimming


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.
33 |M.sc sem I OOPs USING JAVA

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

Important 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

ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish communication
with the clients.
34 |M.sc sem I OOPs USING JAVA

Important methods

Method Description

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

2) public synchronized void close() closes the server socket.

Example of Java Socket Programming


Creating Server:

To create the server application, we need to create the instance of ServerSocket class. Here, 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.

1. ServerSocket ss=new ServerSocket(6666);


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

Creating Client:

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.

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

Let's see a simple of Java socket programming where client sends a text and server receives and prints it.

File: MyServer.java

1. import java.io.*;
2. import java.net.*;
3. public class MyServer {
4. public static void main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(6666);
7. Socket s=ss.accept();//establishes connection
8. DataInputStream dis=new DataInputStream(s.getInputStream());
9. String str=(String)dis.readUTF();
10. System.out.println("message= "+str);
11. ss.close();
12. }catch(Exception e){System.out.println(e);}
35 |M.sc sem I OOPs USING JAVA

13. }
14. }

File: MyClient.java

1. import java.io.*;
2. import java.net.*;
3. public class MyClient {
4. public static void main(String[] args) {
5. try{
6. Socket s=new Socket("localhost",6666);
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. dout.writeUTF("Hello Server");
9. dout.flush();
10. dout.close();
11. s.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }

To execute this program open two command prompts and execute each program at each command
prompt as displayed in the below figure.

After running the client application, a message will be displayed on the server console.

Example of Java Socket Programming (Read-Write both side)


In this example, client will write first to the server then server will receive and print the text. Then server will
write to the client and client will receive and print the text. The step goes on.

File: MyServer.java

1. import java.net.*;
2. import java.io.*;
3. class MyServer{
4. public static void main(String args[])throws Exception{
5. ServerSocket ss=new ServerSocket(3333);
6. Socket s=ss.accept();
7. DataInputStream din=new DataInputStream(s.getInputStream());
8. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
9. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
10.
11. String str="",str2="";
36 |M.sc sem I OOPs USING JAVA

12. while(!str.equals("stop")){
13. str=din.readUTF();
14. System.out.println("client says: "+str);
15. str2=br.readLine();
16. dout.writeUTF(str2);
17. dout.flush();
18. }
19. din.close();
20. s.close();
21. ss.close();
22. }}

File: MyClient.java

1. import java.net.*;
2. import java.io.*;
3. class MyClient{
4. public static void main(String args[])throws Exception{
5. Socket s=new Socket("localhost",3333);
6. DataInputStream din=new DataInputStream(s.getInputStream());
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
9.
10. String str="",str2="";
11. while(!str.equals("stop")){
12. str=br.readLine();
13. dout.writeUTF(str);
14. dout.flush();
15. str2=din.readUTF();
16. System.out.println("Server says: "+str2);
17. }
18.
19. dout.close();
20. s.close();
21. }}

(6) processing E-Mails with Java


37 |M.sc sem I OOPs USING JAVA

What is E-mail?
E-mail is defined as the transmission of messages on the Internet. It is one of the most commonly used
features over communications networks that may contain text, files, images, or other attachments.
Generally, it is information that is stored on a computer sent through a network to a specified individual or
group of individuals.

Email messages are conveyed through email servers; it uses multiple protocols within the TCP/IP suite. For
example, SMTP is a protocol, stands for simple mail transfer protocol and used to send messages whereas
other protocols IMAP or POP are used to retrieve messages from a mail server. If you want to login to your
mail account, you just need to enter a valid email address, password, and the mail servers used to send
and receive messages.

Although most of the webmail servers automatically configure your mail account, therefore, you only
required to enter your email address and password. However, you may need to manually configure each
account if you use an email client like Microsoft Outlook or Apple Mail. In addition, to enter the email
address and password, you may also need to enter incoming and outgoing mail servers and the correct
port numbers for each one.

Email messages include three components, which are as follows:

o Message envelope: It depicts the email's electronic format.


o Message header: It contains email subject line and sender/recipient information.
o Message body: It comprises images, text, and other file attachments.

The email was developed to support rich text with custom formatting, and the original email standard is
only capable of supporting plain text messages. In modern times, email supports HTML (Hypertext markup
language), which makes it capable of emails to support the same formatting as websites. The email that
supports HTML can contain links, images, CSS layouts, and also can send files or "email attachments" along
with messages. Most of the mail servers enable users to send several attachments with each message. The
attachments were typically limited to one megabyte in the early days of email. Still, nowadays, many mail
servers are able to support email attachments of 20 megabytes or more in size.

In 1971, as a test e-mail message, Ray Tomlinson sent the first e-mail to himself. This email was contained
the text "something like QWERTYUIOP." However, the e-mail message was still transmitted through
ARPANET, despite sending the e-mail to himself. Most of the electronic mail was being sent as compared
to postal mail till 1996.

Differences between email and webmail


The term email is commonly used to describe both browser-based electronic mail and non-browser-based
electronic mail today. The AOL and Gmail are browser-based electronic mails, whereas Outlook for Office
365 is non-browser-based electronic mail. However, to define email, a difference was earlier made as a
non-browser program that needed a dedicated client and email server. The non-browser emails offered
some advantages, which are enhanced security, integration with corporate software platforms, and lack of
advertisements.
38 |M.sc sem I OOPs USING JAVA

Uses of email
Email can be used in different ways: it can be used to communicate either within an organization or
personally, including between two people or a large group of people. Most people get benefit from
communicating by email with colleagues or friends or individuals or small groups. It allows you to
communicate with others around the world and send and receive images, documents, links, and other
attachments. Additionally, it offers benefit users to communicate with the flexibility on their own schedule.

There is another benefit of using email; if you use it to communicate between two people or small groups
that will beneficial to remind participants of approaching due dates and time-sensitive activities and send
professional follow-up emails after appointments. Users can also use the email to quickly remind all
upcoming events or inform the group of a time change. Furthermore, it can be used by companies or
organizations to convey information to large numbers of employees or customers. Mainly, email is used
for newsletters, where mailing list subscribers are sent email marketing campaigns directly and promoted
content from a company.

History of E-mail
As compared to ARPANet or the Internet, email is much older. The early email was just a small advance,
which is known as a file directory in nowadays. It was used to just put a message in other user's directory
in the place where they were able to see the message by logging in. For example, the same as leaving a
note on someone's desk. Possibly MAILBOX was used at Massachusetts Institute of Technology, which was
the first email system of this type from 1965. For sending messages on the same computer, another early
program was SNDMSG.

Later in 1972, Ray Tomlinson invented email to remove some difficulties. Tomlinson worked (Like many
of the Internet inventors) for Newman and Bolt Beranek as an ARPANET contractor. To denote sending
messages from one computer to another, he picked up the @ symbol from the keyboard. Then, it became
easy to send a message to another with the help of Internet standards; they were only required to
propose name-of-the-user@name-of-the-computer. One of the first users of the new system was Internet
pioneer Jon Postel. Also, describing as a "nice hack," credited goes to Jon Postel.

Although the World Wide Web offers many services, email is the most widely used facility and remains the
most important application of the Internet. On the international level, over 600 million people use email.
There were hundreds of email users by 1974, as ARPANET ultimately encouraged it. Furthermore, email
caused a radical shift in Arpa's purpose, as it became the savior of Arpanet.

When personal computers came on the scene, the offline reader was one of the first new developments.
Then, email users became able to store their email on their own personal computers with the help of offline
reader and read it. Also, without actually being connected to the network, they were able to prepare replies
like Microsoft Outlook can do today. In parts of the world, this was specifically useful for people where the
telephone was expensive as compared to the email system.

Without being connected to a telephone, it was able to prepare a reply with connection charges of many
dollars a minute and then get on the network to send it. Also, it was useful as the offline mode allowed for
more simple user interfaces. In this modern time of very few standards being connected directly to the host
email system often resulted in no capacity for text to wrap around on the screen of the user's computer,
39 |M.sc sem I OOPs USING JAVA

and backspace keys and delete keys may not work and other such annoyances. Offline readers helped out
more to overcome these kinds of difficulties.

The SMTP (simple mail transfer protocol) was the first important email standard. It was a fairly naïve
protocol that is still in use. And, it was made in terms of no attempt to find the person who sent a message
that was the right or not what they claimed to be. In the email addresses, fraudulent was very easy and is
still available. Later, these basic flaws were used in the protocol by security frauds, worms and viruses, and
spammers forging identities. From 2004, some of these problems are still being processed for a solution.

Individual dialup users were required to charges for an email per-minute in those days. Also, on the Internet,
email and email discussion groups were the main uses for most people. There were several issues on a
wide variety of subjects; they became USENET as a body of newsgroups.

With the World Wide Web (WWW), email became available with a simple user interface that was offered
by providers like Hotmail and Yahoo. And, users did not require to pay any charges on these platforms.
Now everyone wanted at least one email address as it is much simple and affordable, and the medium was
adopted by millions of people.

Internet Service Providers (ISPs) started to connect people with each other all over the world by the 1980s.
Also, by 1993 the use of the Internet was becoming widespread, and the word electronic mail was replaced
by email.

Today, email has become a primary platform to communicate with people all over the world. There are
continuing updates to the system with so many people using email for communication. Although email
has some security issues, there have been laws passed to prevent the spread of junk email over the years.

Advantages of Email
There are many advantages of email, which are as follows:

o Cost-effective: Email is a very cost-effective service to communicate with others as there are several email
services available to individuals and organizations for free of cost. Once a user is online, it does not include
any additional charge for the services.
o Email offers users the benefit of accessing email from anywhere at any time if they have an Internet
connection.
o Email offers you an incurable communication process, which enables you to send a response at a convenient
time. Also, it offers users a better option to communicate easily regardless of different schedules users.
o Speed and simplicity: Email can be composed very easily with the correct information and contacts. Also,
minimum lag time, it can be exchanged quickly.
o Mass sending: You can send a message easily to large numbers of people through email.
o Email exchanges can be saved for future retrieval, which allows users to keep important conversations or
confirmations in their records and can be searched and retrieved when they needed quickly.
40 |M.sc sem I OOPs USING JAVA

o Email provides a simple user interface and enables users to categorize and filter their messages. This can help
you recognize unwanted emails like junk and spam mail. Also, users can find specific messages easily when
they are needed.
o As compared to traditional posts, emails are delivered extremely fast.
o Email is beneficial for the planet, as it is paperless. It reduces the cost of paper and helps to save the
environment by reducing paper usage.

Disadvantages of Email
o Impersonal: As compared to other forms of communication, emails are less personal. For example, when
you talk to anyone over the phone or meeting face to face is more appropriate for communicating than email.
o Misunderstandings: As email includes only text, and there is no tone of voice or body language to provide
context. Therefore, misunderstandings can occur easily with email. If someone sends a joke on email, it can
be taken seriously. Also, well-meaning information can be quickly typed as rude or aggressive that can impact
wrong. Additionally, if someone types with short abbreviations and descriptions to send content on the email,
it can easily be misinterpreted.
o Malicious Use: As email can be sent by anyone if they have an only email address. Sometimes, an
unauthorized person can send you mail, which can be harmful in terms of stealing your personal information.
Thus, they can also use email to spread gossip or false information.
o Accidents Will Happen: With email, you can make fatal mistakes by clicking the wrong button in a hurry.
For instance, instead of sending it to a single person, you can accidentally send sensitive information to a
large group of people. Thus, the information can be disclosed, when you have clicked the wrong name in an
address list. Therefore, it can be harmful and generate big trouble in the workplace.
o Spam: Although in recent days, the features of email have been improved, there are still big issues with
unsolicited advertising arriving and spam through email. It can easily become overwhelming and takes time
and energy to control.
o Information Overload: As it is very easy to send email to many people at a time, which can create
information overload. In many modern workplaces, it is a major problem where it is required to move a lot
of information and impossible to tell if an email is important. And, email needs organization and upkeep. The
bad feeling is one of the other problems with email when you returned from vacation and found hundreds
of unopened emails in your inbox.
o Viruses: Although there are many ways to travel viruses in the devices, email is one of the common ways to
enter viruses and infect devices. Sometimes when you get a mail, it might be the virus come with an attached
document. And, the virus can infect the system when you click on the email and open the attached link.
Furthermore, an anonymous person or a trusted friend or contact can send infected emails.
o Pressure to Respond: If you get emails and you do not answer them, the sender can get annoyed and think
you are ignoring them. Thus, this can be a reason to make pressure on your put to keep opening emails and
then respond in some way.
41 |M.sc sem I OOPs USING JAVA

o Time Consuming: When you get an email and read, write, and respond to emails that can take up vast
amounts of time and energy. Many modern workers spend their most time with emails, which may be caused
to take more time to complete work.
o Overlong Messages: Generally, email is a source of communication with the intention of brief messages.
There are some people who write overlong messages that can take much time than required.
o Insecure: There are many hackers available that want to gain your important information, so email is a
common source to seek sensitive data, such as political, financial, documents, or personal messages. In recent
times, there have various high-profile cases occurred that shown how email is insecure about information
theft.

Different types of Email


There are many types of email; such are as follows:

Newsletters: It is studying by Clutch, the newsletter is the most common type of email that are routinely
sent to all mailing list subscribers, either daily, weekly, or monthly. These emails often contain from the
blog or website, links curated from other sources, and selected content that the company has recently
published. Typically, Newsletter emails are sent on a consistent schedule, and they offer businesses the
option to convey important information to their client through a single source. Newsletters might also
incorporate upcoming events or new, webinars from the company, or other updates.

Lead Nurturing: Lead-nurturing emails are a series of related emails that marketers use to take users on
a journey that may impact their buying behavior. These emails are typically sent over a period of several
days or weeks. Lead-nurturing emails are also known as trigger campaigns, which are used for solutions in
an attempt to move any prospective sale into a completed purchase and educate potential buyers on the
services. These emails are not only helpful for converting emails but also drive engagement. Furthermore,
lead-nurturing emails are initiated by a potential buyer taking initial action, such as clicking links on a
promotional email or downloading a free sample.

Promotional emails: It is the most common type of B2B (Business to Business) email, which is used to
inform the email list of your new or existing products or services. These types of emails contain creating
new or repeat customers, speeding up the buying process, or encouraging contacts to take some type of
action. It provides some critical benefits to buyers, such as a free month of service, reduced or omitted fees
for managed services, or percentage off the purchase price.

Standalone Emails: These emails are popular like newsletters emails, but they contain a limitation. If you
want to send an email with multiple links or blurbs, your main call-to-action can weaken. Your subscriber
may skip your email and move on, as they may click on the first link or two in your email but may not come
back to the others.

Onboarding emails: An onboarding email is a message that is used to strengthen customer loyalty, also
known as post-sale emails. These emails receive users right after subscription. The onboarding emails are
sent to buyers to familiarize and educate them about how to use a product effectively. Additionally, when
clients faced with large-scale service deployments, these emails help them facilitate user adoption.
42 |M.sc sem I OOPs USING JAVA

Transactional: These emails are related to account activity or a commercial transaction and sent from one
sender to one recipient. Some examples of transactional email are purchase confirmations, password
reminder emails, and personalized product notifications. These emails are used when you have any kind of
e-commerce component to your business. As compared to any other type of email, the transactional email
messages have 8x the opens and clicks.

Plain-Text Emails: It is a simple email that does not include images or graphics and no formatting; it only
contains the text. These types of emails may worth it if you try to only ever send fancy formatted emails,
text-only messages. According to HubSpot, although people prefer fully designed emails with various
images, plain text emails with less HTML won out in every A/B test. In fact, HTML emails contain lower open
and click-through rates, and plain text emails can be great for blog content, event invitations, and survey
or feedback requests. Even if you do not send plainer emails, but you can boost your open and click through
rates by simplifying your emails and including fewer images.

Welcome emails: It is a type of B2B email and common parts of onboarding emails that help users get
acquainted with the brand. These emails can improve subscriber constancy as they include additional
information, which helps to the new subscriber in terms of a business objective. Generally, welcome emails
are sent buyers who got a subscription to a business's opt-in activities, such as a blog, mailing list, or
webinar. Also, these emails can help businesses to build a better relationship between customers.

Examples of email attacks


Although there are many ways to travel viruses in the devices, email is one of the most common vectors
for cyberattacks. The methods include spoofing, spamming, spear-phishing, phishing, ransomware, and
business email compromise (BEC).

There are many organizations (around 7710) hit by a BEC attack every month, as one out of every 412
emails contains a malware attack. According to the Symantec Internet Threat Security Report, spear-
phishing is the most widely used infection vector. Below is given a complete description of these types of
attacks:

o Phishing: A form of fraud in which the attacks are the practice of sending fraudulent communications that
appear to come from a reputable entity or person in email or other communication channels. Usually, it is
done through the email; phishing emails are used by attackers to steal sensitive data like credit card and
login information or to install malware on the victim's machine. Additionally, everyone should learn about a
phishing attack in order to protect themselves, as it is a common type of cyberattack. The common features
of phishing emails are Sense of urgency, Hyperlinks, Too Good to Be True, Unusual sender, Attachments.
o Spamming: Spam email is unsolicited bulk messages sent without explicit consent from the recipient, which
is also known as junk email. Since the 1990s, spam is a problem faced by most email users and has been
increasing in popularity. Obtained by spambots, spam mail recipients have had their email addresses
(automated programs), which crawl the Internet to find email addresses. This is the dark side of email
marketing in which spammers use spambots to create email distribution lists. Typically, an email is sent by a
spammer to millions of email addresses with the expectation that only a few numbers of an email address
will respond or interact with the message.
43 |M.sc sem I OOPs USING JAVA

o Spoofing: Email spoofing is an email message that could be obtained from someone or somewhere other
than the intended source. It is a popular strategy that is used in spam and phishing campaigns as core email
protocols do not have a built-in method of authentication. And, when people think the email has been sent
by a legitimate or familiar source, they are more likely to open an email. Thus, it is a common tactic used for
spam and phishing emails. The email spoofing is used with the purpose of getting mail recipients to open
emails and possibly respond to a solicitation.
o Business email compromise (BEC): A BEC is an exploit in which an authorized person or attacker hacks to
a business email account and spoofs the owner's identity to defraud the company, its customers, partners of
money. Often, an attacker simply creates an account with an email address that is almost identical to one on
the corporate network, which creates trust between the victim and their email account. Sometimes, a BEC is
also known as a man-in-the-email attack. Some samples of BEC email messages that contain the word in
subject, such as urgent, transfer, request, payment, and more. There are five types of BEC scams on the basis
of the FBI, which are False Invoice Scheme, CEO Fraud, Data Theft, Attorney Impersonation, Account
Compromise.

Popular email sites


There are some free email website examples include the following:

o AOL
o Zoho
o Gmail
o ProtonMail
o Com
o Microsoft Outlook
o Yahoo Mail

Email is a platform that allows users to communicate with people or groups of people around the world.
As email security is more important but consequent, it is not inherently secure.

There are many techniques that can be used by individuals, organizations, and service providers. These
techniques provide how to protect sensitive information with email communication and accounts from
unauthorized access, loss, or destruction.

Individuals can protect their account with the help of creating strong passwords and changing them
frequently. They can use alphabetical, numerical, special symbols to make a strong password that helps to
protect your account. Users can also install and run an antivirus and antimalware software on their
computer, as well as create spam filters and folders to separate potentially malicious emails and junk mail.

Also, there are some techniques the helps organizations to secure email include implementing an email
security gateway, training employees on deploying automated email encryption solutions, and proper
email usage. By processing and scanning all received emails, email gateways check emails for threats, and
analyze that should be allowed into the system or not. A multilayered gateway is a powerful technique
44 |M.sc sem I OOPs USING JAVA

since attacks are increasing rapidly and becoming complicated and sophisticated. Some emails that cannot
be caught by the gateway, training employees on how to differentiate malicious messages, and properly
use email are the best approach, which helps users avoid threatening mails.

What can be sent in an e-mail?


An email is a platform that enables users to communicate with each other. It allows users to send text
messages, including a file or other data on the e-mail all over the world. It is also possible to attach a
picture, word processor document, PDF, program, movie, or any file stored on your computer in an e-mail.
However, due to some security issues, it may not be possible to send certain types of files on the email;
they need some additional steps. For example, the .exe file can be blocked by many companies from being
sent over the email, and you will need to compress the file into a .zip file format. Additionally, you may be
unable to send any large files or programs from being sent over e-mail as most e-mail providers have file
size restrictions.

What should be write e-mail or email?


You can use any word email or e-mail according to the style guide you are following as both are valid and
have the same meaning. However, the e-mail word has a hyphen and is a compound noun that describes
"electronic" and "mail."

How to send and receive e-mail


E-mail program
You can use an email program to send and receive an email. An email program is also known as an e-mail
client. There are many email programs available to send and receive an email, including Mozilla
Thunderbird and Microsoft Outlook. A server is used to store and deliver your messages while you use an
email client. Often, your ISP (Internet service provider) host this server but can be another Internet company
to host this server. To download the new emails, an email client requires connecting a server, whereas
online stored emails are always available on Internet-connected devices.

Online e-mail
An online e-mail service or webmail is an alternative way and the popular solution for most people in
sending and receiving e-mail. Examples of online emails are Yahoo Mail, Gmail, and Hotmail (now
Outlook.com).

Some of the popular e-mail clients?


Today, there are different software-based e-mail clients available for users, but these are not online. Below
is given a list that contains the most popular clients.

o Microsoft Outlookv
o Mail for Windows 10
o DreamMail
45 |M.sc sem I OOPs USING JAVA

o Mozilla Thunderbird
o eM Client
o Mailbird

What makes a valid e-mail address?


Users need to follow the various rule that is given below to make valid email address:

o A username followed by @ (the at sign) is most important for an email address, which is followed by the
domain name with a domain suffix. Hence, an e-mail must have a username.
o The domain name cannot be longer than 254 characters, and the username cannot be longer than 64
characters long.
o An email must have only one @ sign.
o An email should not have space and special characters like \ [ ] ( ) , : ; < >. Sometimes, few symbols such as
backslash, space, and quotation mark work must be preceded with a forward slash. But these characters are
not allowed by some email providers.
o In the email, the email address and username cannot start or end with a period.
o The two or more successive periods are not allowed in the email.

(7) Protocols and Servers


The JavaMail is an API that is used to compose, write and read electronic messages (emails).

The JavaMail API provides protocol-independent and plateform-independent framework for sending and
receiving mails.

The javax.mail and javax.mail.activation packages contains the core classes of JavaMail API.

The JavaMail facility can be applied to many events. It can be used at the time of registering the user
(sending notification such as thanks for your interest to my site), forgot password (sending password to
the users email id), sending notifications for important updates etc. So there can be various usage of java
mail api.

Do You Know ?

o How to send and receive email using JavaMail API ?


o How to send email through gmail server ?
o How to send and receive email with attachment ?
o How to send email with html content including images?
o How to forward and delete the email ?
46 |M.sc sem I OOPs USING JAVA

Protocols used in JavaMail API


There are some protocols that are used in JavaMail API.

o SMTP
o POP
o IMAP
o MIME
o NNTP and others

SMTP
SMTP is an acronym for Simple Mail Transfer Protocol. It provides a mechanism to deliver the email. We
can use Apache James server, Postcast server, cmail server etc. as an SMTP server. But if we purchase the
host space, an SMTP server is bydefault provided by the host provider. For example, my smtp server is
mail.javatpoint.com. If we use the SMTP server provided by the host provider, authentication is required
for sending and receiving emails.

POP
POP is an acronym for Post Office Protocol, also known as POP3. It provides a mechanism to receive the
email. It provides support for single mail box for each user. We can use Apache James server, cmail server
etc. as an POP server. But if we purchase the host space, an POP server is bydefault provided by the host
provider. For example, the pop server provided by the host provider for my site is mail.javatpoint.com. This
protocol is defined in RFC 1939.

IMAP
IMAP is an acronym for Internet Message Access Protocol. IMAP is an advanced protocol for receiving
messages. It provides support for multiple mail box for each user ,in addition to, mailbox can be shared by
multiple users. It is defined in RFC 2060.

MIME
Multiple Internet Mail Extension (MIME) tells the browser what is being sent e.g. attachment, format of the
messages etc. It is not known as mail transfer protocol but it is used by your mail program.

NNTP and Others


There are many protocols that are provided by third-party providers. Some of them are Network News
Transfer Protocol (NNTP), Secure Multipurpose Internet Mail Extensions (S/MIME) etc.

JavaMail Architecture
47 |M.sc sem I OOPs USING JAVA

The java application uses JavaMail API to compose, send and receive emails. The JavaMail API uses SPI
(Service Provider Interfaces) that provides the intermediatory services to the java application to deal with
the different protocols. Let's understand it with the figure given below:

JavaMail API Core Classes


There are two packages that are used in Java Mail API: javax.mail and javax.mail.internet package. These
packages contains many classes for Java Mail API. They are:

o javax.mail.Session class
o javax.mail.Message class
o javax.mail.internet.MimeMessage class
o javax.mail.Address class
o javax.mail.internet.InternetAddress class
o javax.mail.Authenticator class
o javax.mail.PasswordAuthentication class
o javax.mail.Transport class
o javax.mail.Store class
o javax.mail.Folder class etc.

(8) Creating Mailer


48 |M.sc sem I OOPs USING JAVA

How to Create a Mailer


1. Choose a layout program to create the mailer. ...
2. Determine the format and corresponding size you want for your mailer. ...
3. Create two pages in your document layout (front and back of the mailer). ...
4. Set up the side that will contain the recipient information and stamp area first

A mailer is a piece of direct mail that advertisers send to targeted groups of customers. Mailers
commonly come in the form of standard postcards or folded flyers. A mailer contains information about a
product, person, or service and is designed for quick viewing. A savvy advertiser recognizes that he could
have a very small window to grab the reader's attention, so this compact ad format can be very useful.
STEP 1.
Choose a layout program to create the mailer. Common programs include Microsoft
Word, Publisher, or Adobe InDesign.
STEP 2.
Determine the format and corresponding size you want for your mailer. For a standard
postcard, size the document between 3.5 by 5 inches and 4.25 by 6 inches (height by
width). For a folded flyer, size the document to a standard 8.5-by-11-inch piece of
paper. See "Resources" for more possible formats and sizes to consider for a United
States Postal Service approved mailer.
STEP 3.
Create two pages in your document layout (front and back of the mailer). If you chose
a folded mailer, create a line in the document to separate the top and bottom of the
document (the line is where you'll fold the mailer in half).
STEP 4.
Set up the side that will contain the recipient information and stamp area first. Insert a
small square in the right top corner for the stamp, print your return address in the top
left corner, and create a box on the right lower side to designate where your recipient
mailing labels will go. (If you chose a folded flyer, keep in mind that the bottom half of
the first page of your document is the panel that will contain the recipient's address
information.)
STEP 5.
Add a call to action or short description of your product or service to a blank area of
the front side of the mailer (the side containing recipient address and stamp) if you
want.
STEP 6.
Insert details (text and images) about your company, product, service, or person you're
advertising on the second page of the document. If you chose a folded mailer, you can
add more information to the top half of the first page.
49 |M.sc sem I OOPs USING JAVA

STEP 7.
Print the mailer on card stock paper (between 65- and 90-pound stock). Fold the mailer
in half if you chose a folded flyer and close it with a wafer seal (sticker tab). Leave this
task to a copy shop if you want a professional result.
STEP 8.
Purchase stamps for your mailers--or ask your local postal representative about
discounted rates for bulk mail--and attach your mailing labels to each piece (see
"Resources" for guidance on how to create mailing labels)

(9) writing the Mail Sender


There are various ways to send email using JavaMail API. For this purpose, you must have SMTP
server that is responsible to send mails.

You can use one of the following techniques to get the SMTP server:

o Install and use any SMTP server such as Postcast server, Apache James server, cmail server etc. (or)
o Use the SMTP server provided by the host provider e.g. my SMTP server is mail.javatpoint.com (or)
o Use the SMTP Server provided by other companies e.g. gmail etc.

Here, we are going to learn above three approaches to send email using javamail API. But we should learn
the basic steps to send email from java application.

Steps to send email using JavaMail API


There are following three steps to send email using JavaMail. They are as follows:

1. Get the session object that stores all the information of host like host name, username, password etc.
2. compose the message
3. send the message

1) Get the session object


The javax.mail.Session class provides two methods to get the object of session,
Session.getDefaultInstance() method and Session.getInstance() method. You can use any method to get
the session object.
50 |M.sc sem I OOPs USING JAVA

Method of Session class

No. Method Description

1 public static Session getDefaultInstance(Properties props) returns the default session.

2 public static Session getDefaultInstance(Properties props,Authenticator returns the default session.


auth)

3 public static Session getInstance(Properties props) returns the new session.

4 public static Session getInstance(Properties props,Authenticator auth) returns the new session.

Example of getDefaultInstance() method


1. Properties properties=new Properties();
2. //fill all the information like host name etc.
3. Session session=Session.getDefaultInstance(properties,null);
Example of getInstance() method
1. Properties properties=new Properties();
2. //fill all the information like host name etc.
3. Session session=Session.getInstance(properties,null);

2) Compose the message


The javax.mail.Message class provides methods to compose the message. But it is an abstract class so its subclass
javax.mail.internet.MimeMessage class is mostly used.

To create the message, you need to pass session object in MimeMessage class constructor. For example:

1. MimeMessage message=new MimeMessage(session);


Now message object has been created but to store information in this object MimeMessage class provides many
methods. Let's see methods provided by the MimeMessage class:

Commonly used methods of MimeMessage class

No. Method Description

1 public void setFrom(Address address) is used to set the from header field.

2 public void addRecipient(Message.RecipientType type, is used to add the given address to the
Address address) recipient type.
51 |M.sc sem I OOPs USING JAVA

3 public void addRecipients(Message.RecipientType type, is used to add the given addresses to the
Address[] addresses) recipient type.

4 public void setSubject(String subject) is used to set the subject header field.

5 public void setText(String textmessage) is used to set the text as the message content
using text/plain MIME type.

6 public void setContent(Object msg, String contentType) is used to set the content as the message
content using given MIME type.

Example to compose the message:


1. MimeMessage message=new MimeMessage(session);
2. message.setFrom(new InternetAddress("sonoojaiswal@sssit.org"));
3. message.addRecipient(Message.RecipientType.To,
4. new InternetAddress("sonoojaiswal@javatpoint.com"));
5. message.setHeader("Hi, everyone");
6. message.setText("Hi, This mail is to inform you...");

3) Send the message


The javax.mail.Transport class provides method to send the message.

Commonly used methods of Transport class

No. Method Description

1 public static void send(Message message) is used send the message.

2 public static void send(Message message, Address[] is used send the message to the given
address) addresses.

Example to send the message:


1. Transport.send(message);

Simple example of sending email in Java


In this example, we are going to learn how to send email by SMTP server installed on the machine e.g. Postcast
server, Apache James server, Cmail server etc. If you want to send email by using your SMTP server provided by the
host provider, see the example after this one.
52 |M.sc sem I OOPs USING JAVA

For sending the email using JavaMail API, you need to load the two jar files:

o mail.jar
o activation.jar

download these jar files or go to the Oracle site to download the latest version.
1. import java.util.*;
2. import javax.mail.*;
3. import javax.mail.internet.*;
4. import javax.activation.*;
5.
6. public class SendEmail
7. {
8. public static void main(String [] args){
9. String to = "sonoojaiswal1988@gmail.com";//change accordingly
10. String from = "sonoojaiswal1987@gmail.com";change accordingly
11. String host = "localhost";//or IP address
12.
13. //Get the session object
14. Properties properties = System.getProperties();
15. properties.setProperty("mail.smtp.host", host);
16. Session session = Session.getDefaultInstance(properties);
17.
18. //compose the message
19. try{
20. MimeMessage message = new MimeMessage(session);
21. message.setFrom(new InternetAddress(from));
22. message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
23. message.setSubject("Ping");
24. message.setText("Hello, this is example of sending email ");
25.
26. // Send message
27. Transport.send(message);
28. System.out.println("message sent successfully....");
29.
30. }catch (MessagingException mex) {mex.printStackTrace();}
31. }
32. }
download this example to send email
53 |M.sc sem I OOPs USING JAVA

In this example, we are going to learn how to send email by SMTP server installed on the machine e.g.
Postcast server, Apache James server, Cmail server etc. If you want to send email by using your SMTP server
provided by the host provider, see the example after this one.

To run this example, you need to load two jar files. There are 4 ways to load the jar file. One of the way is
set classpath. Let's see how to run this example:

Load the jar file c:\> set classpath=mail.jar;activation.jar;.;

compile the source file c:\> javac SendEmail.java

run by c:\> java SendEmail

Example of sending email in Java through SMTP server provided


by the host provider
If you are using the SMTP server provided by the host provider e.g. mail.javatpoint.com , you need to authenticate
the username and password. The javax.mail.PasswordAuthentication class is used to authenticate the password.

If you are sending the email using JavaMail API, load the two jar files:

o mail.jar
o activation.jar

download these jar files or go to the Oracle site to download the latest version.
1. import java.util.Properties;
2. import javax.mail.*;
3. import javax.mail.internet.*;
4.
5. public class SendMailBySite {
6. public static void main(String[] args) {
7.
8. String host="mail.javatpoint.com";
9. final String user="sonoojaiswal@javatpoint.com";//change accordingly
10. final String password="xxxxx";//change accordingly
11.
12. String to="sonoojaiswal1987@gmail.com";//change accordingly
13.
14. //Get the session object
15. Properties props = new Properties();
16. props.put("mail.smtp.host",host);
54 |M.sc sem I OOPs USING JAVA

17. props.put("mail.smtp.auth", "true");


18.
19. Session session = Session.getDefaultInstance(props,
20. new javax.mail.Authenticator() {
21. protected PasswordAuthentication getPasswordAuthentication() {
22. return new PasswordAuthentication(user,password);
23. }
24. });
25.
26. //Compose the message
27. try {
28. MimeMessage message = new MimeMessage(session);
29. message.setFrom(new InternetAddress(user));
30. message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
31. message.setSubject("javatpoint");
32. message.setText("This is simple program of sending email using JavaMail API");
33.
34. //send the message
35. Transport.send(message);
36.
37. System.out.println("message sent successfully...");
38.
39. } catch (MessagingException e) {e.printStackTrace();}
40. }
41. }
download this example to send email

As you can see in the above example, userid and password need to be authenticated. As this program
illustrates, you can send email easily. Change the username and password accordingly. Let's see how to run
it once again by simple technique:

Load the jar file c:\> set classpath=mail.jar;activation.jar;.;

compile the source file c:\> javac SendMailBySite.java

run by c:\> java SendMailBySite

(9) Swing With J-Table: J-Table , the MVC Paradigm,


55 |M.sc sem I OOPs USING JAVA

Understanding the TableModel:


Let us consider an example. We want to display the employee details in a table and also allow the user to edit the
values directly in the table. The employee details would include fields like id, name, hourly rate and part-time status.
Before we start looking at the code, we need to understand about the model of JTable. All the components in the
Swing API follow the MVC paradigm and JTable is no exception. Let us try and understand why this is needed and
how this helps us.
In simple terms, the Model-View-Controller paradigm dictates that the data be held in a Model. And the view should
display the data by querying the model. In other words, the view should not hold the data. When there is a need to
display the data, the view should invoke the methods of the model to get this information.
Let us see how the MVC model looks for a JTable:

MVC Model

This means that, the model should expose various methods which return useful information for the view. For JTable,
the model is named as TableModel which is an interface. Let us look at the class diagram of the TableModel to
understand this better:

Class Diagram of TableModel


56 |M.sc sem I OOPs USING JAVA

As we can see, there are several getXXX methods which return various data. Let us try and understand how the view (in
this case, the JTable) can make use of this.

Let us consider a scenario. The JTable should display the details of the employees. So, it should in turn query the
TableModel to get this data and display it.

Let us focus on the querying part by attempting to write a pseudocode for this. To display the data, the table needs
several details like header values, number of rows, number of columns and the actual data. The pattern would be
something like this:

get the header values


get the cell value of row number 1 and column number 1
get the cell value of row number 1 and column number 2
...
get the cell value of row number 1 and column number 4
get the cell value of row number 2 and column number 1
...
and so on till the end of the table.

So, when we attempt to convert this into actual working code, the repetitive part of getting the cell values one by one
yields itself to a loop. Also, since we are dealing with a 2 dimensional data, this means we would need 2 loops – a loop
within a loop i.e an inner loop. The outer loop will be for the rows and the inner loop will be for the columns. Thus, we
will be able to traverse the entire table.

So, the model should be able to provide the table back with all this information. In other words, the model should provide
methods which will return these values for us. If you look at the TableModel class diagram, you can find that it exactly
does this. For example, the getRowCount() method returns the number of rows in the model. Similarly, the
getColumnCount() method returns the number of columns in the model. And most importantly, the getValueAt()
method takes the row number and the column number as parameters and returns the value of that particular cell.

So, the JTable internally would probably execute a code like this at runtime to display the values:

1
int rowCount = model.getRowCount();
2 int columnCount = model.getColumnCount();
3 for(int i=0; i<rowCount; i++) {
4 for(int j=0; j<columnCount; j+) {
5 Object cellValue = model.getValueAt(i,j);
6 //now display this value graphically.
}
7 }
8
Note that, the row numbers and column numbers begin indexing at 0 and hence we start from 0.

The actual code written by the Swing API developers would be much more complex. But, this should give an idea of what
actually happens behind the scenes. And that in turn, helps us to understand how and what to write in a TableModel
implementation.

Remember that TableModel is an interface and we have to provide or implementation. Fortunately, Swing provides a
class named AbstractTableModel which provides a default implementation for many methods in this interface. So, we
can simply extend this class and implement those methods which we need to.

Before doing that, let us first define our POJO model. This class is simply a value bean which represents the actual entity:
57 |M.sc sem I OOPs USING JAVA

This class is self-explanatory. We declare a value bean named Employee and its attributes like id,name. And, we provide
corresponding getter and setter methods.

Table Model Implementation:


Let us now extend the AbstractTableModel and override the methods that we need to:

package net.codejava.swing;

import java.util.List;
1 import javax.swing.table.AbstractTableModel;
2
import net.codejava.model.Employee;
3
4 public class EmployeeTableModel extends AbstractTableModel
5 {
6 private final List<Employee> employeeList;
7
8 private final String[] columnNames = new String[] {
9 "Id", "Name", "Hourly Rate", "Part Time"
};
10 private final Class[] columnClass = new Class[] {
11 Integer.class, String.class, Double.class, Boolean.class
12 };
13
14
public Object getValueAt(int rowIndex, int columnIndex)
15
{
16 Employee row = employeeList.get(rowIndex);
if(0 == columnIndex) {
return row.getId();

This code shows a simple extension of the AbstractTableModel class. The model should hold data, so, we declare an
instance variable which holds a list of employees. And we provide a constructor which takes a list as an argument. The
no-args constructor is not provided here. This is because, we want to enforce the fact that the model is useless without
any data.
We also declare a String array columnNames to hold the names of the headers. This is then used by the
getColumnName() method to return the corresponding column header. Another array columnClass tells us which
column is of which type. This variable is then used in the getColumnClass() method to return the corresponding type.
The getColumnCount() method is supposed to return the number of columns to be displayed in the table. Instead of
hardcoding the number as 4 (as we have 4 columns in our case), we have just used the columnName.length to return
the value. This is very useful, as, later on, if we decide to increase the number of columns, we simply need to add more
values to the array. The method as such can be left untouched.

The next method to be looked at it is the getRowCount(). This method should simply return the number of rows present
in the table. And since we have a List variable, we can simply call the size() method on that and return the value. The
number of rows is simply the number of employees in the organization which translates to number of employee instances
in the list.

The final method to be looked at is getValueAt(). This method is slightly complex than the other methods. Like we
discussed earlier, this method takes a row number and column number as parameters and should simply return the value
that is to be displayed in that cell. In our case, the values come from the Employee value bean. So, we first get the
Employee instance which corresponds to this row. We get this instance from the employee list by passing in the row
number. Next, we check for the column number and make corresponding method call on the Employee instance to get
the value and return it.
58 |M.sc sem I OOPs USING JAVA

Using the Table Model:

Let us now attempt to use this model and build the table and display it:

package net.codejava.swing;

import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import net.codejava.model.Employee;

public class EditableTableExample extends JFrame


{
public EditableTableExample(

this.setTitle("Editable Table Example");


this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}

public static void main(String[] args)


{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new EditableTableExample();

We are now making use of the model that we wrote and building the display. We first create the data that is to be passed
to the table for display. So, 3 instances of Employee class are created and and these are added to an ArrayList.

Then, we create the instance of the EmployeeTableModel by passing in the list. This instance is then passed to the
JTable constructor. The JTable is then added to the JFrame and displayed.

Output:
When we run the program, we get the following output:

Output

When we examine the output, we see that the headers are displayed correctly. Then, the numbers are displayed right-
aligned and the name is displayed left-aligned. This is really useful. And the boolean value is displayed as a check-box
with the box checked if the value is true. This is really handy and something that we get out-of-the-box.

And when you run it, you can see that the table doesn't allow editing.

Editing Data:

Let us now proceed to allow editing on this table. Similar to what happens when the data is displayed, when editing
happens, the table simply delegates saving of the data to the model. So, we need to first provide methods on the model
that can facilitate this. If you look at the TableModel class diagram, it provides a method setValueAt(). The last 2
parameters are similar to getValueAt(). We need the column index and the row index to identify the cell to which the
value is to be set. The 1st parameter is the actual value that is provided by the user.
59 |M.sc sem I OOPs USING JAVA

So, what do we do with data? Similar to getValueAt(), we first identify the row and get the instance. Then, we can
invoke setter methods on the Employee row instance to persist the data to the instance. Thus, our setValueAt()
implementation looks like:

1
2 @Override
3 public void setValueAt(Object aValue, int rowIndex, int columnIndex)
4 {
5 Employee row = employeeList.get(rowIndex);
if(0 == columnIndex) {
6
row.setId((Integer) aValue);
7 }
8 else if(1 == columnIndex) {
9 row.setName((String) aValue);
10 }
else if(2 == columnIndex) {
11 row.setHourlyRate((Double) aValue);
12 }
13 else if(3 == columnIndex) {
14 row.setPartTime((Boolean) aValue);
15 }
}
16
17
As explained above, we get the row instance and then based on the columnIndex call the corresponding setter. For
example, for column 1, we call setName() on the Employee instance.

Wait a minute. When we ran the program last time, it actually didn't allow us to edit any values. So, is this enough? The
answer is no. We also need to override the isCellEditable() method as follows:

1 @Override
2 public boolean isCellEditable(int rowIndex, int columnIndex)
3 {
4 return true;
}
5
Overriding this method tells the table to allow editing by the user. So, apart from holding data, the table model also
provides information on whether the table can be edited. So, actually, it is the table model that controls the table!

Editable Table Output:

Editable Table

When you run the program, you can edit the values. This includes the check-box too!

Validating Input:

But, wait a minute. What if the user enters an invalid value? Let us now attempt to enter some alphabets in the 'Hourly
Rate' column and see what happens:

Validating Input

When we try to enter an invalid value like 'qwe', the edit is not accepted! The cursor stays in the same cell. Also, the
JTable displays a nice red border over the cell to indicate that we have entered an invalid value!
60 |M.sc sem I OOPs USING JAVA

This feature is very useful and we get this out-of-the-box. Isn't that cool?

So, our full table model code now looks like this:

1 package net.codejava.swing;
2
3 import java.util.List;
4 import javax.swing.table.AbstractTableModel;
5
6 import net.codejava.model.Employee;
7
public class EmployeeTableModel extends AbstractTableModel
8 {
9 private final List<Employee> employeeList;
10
11 private final String[] columnNames = new String[] {
12 "Id", "Name", "Hourly Rate", "Part Time"
};
13
private final Class[] columnClass = new Class[] {
14 Integer.class, String.class, Double.class, Boolean.class
15 };
16
17 public EmployeeTableModel(List<Employee> employeeList)
18 {
this.employeeList = employeeList;
19 }
20
21 @Override
22 public String getColumnName(int column)
23 {
24 return columnNames[column];
}
25
26 @Override
27 public Class<?> getColumnClass(int columnIndex)
{
return columnClass[columnIndex];
}
ote that we are not providing the EditableTableExample code again. Why? Simply because there is no change in that
code. All the decisions are made in the table model and the JTable simply queries the model for everything and just
does the display.

This is very clean. We are able to easily the separate the display and the model part. This also illustrates how the MVC
paradigm is elegant.

(10) RMI (Remote Method Invocation)


The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed application
in java. The RMI allows an object to invoke methods on an object running in another JVM.

The RMI provides remote communication between the applications using two objects stub and skeleton.

Understanding stub and skeleton


RMI uses stub and skeleton object for communication with the remote object.
61 |M.sc sem I OOPs USING JAVA

A remote object is an object whose method can be invoked from another JVM. Let's understand the stub
and skeleton object

stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed through it.
It resides at the client side and represents the remote object. When the caller invokes method on the stub
object, it does the following tasks:

1. It initiates a connection with remote Virtual Machine (JVM),


2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.

skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming requests are routed
through it. When the skeleton receives the incoming request, it does the following tasks:

1. It reads the parameter for the remote method


2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.

In the Java 2 SDK, an stub protocol was introduced that eliminates the need for

skeletons.

Understanding requirements for the distributed applications


If any application performs these tasks, it can be distributed application.

1. The application need to locate the remote method


2. It need to provide the communication with the remote objects, and
62 |M.sc sem I OOPs USING JAVA

3. The application need to load the class definitions for the objects.

The RMI application have all these features, so it is called the distributed application.

Java RMI Example


The is given the 6 steps to write the RMI program.

1. Create the remote interface


2. Provide the implementation of the remote interface
3. Compile the implementation class and create the stub and skeleton objects using the rmic tool
4. Start the registry service by rmiregistry tool
5. Create and start the remote application
6. Create and start the client application

RMI Example

In this example, we have followed all the 6 steps to create and run the rmi application. The client application
need only two files, remote interface and client application. In the rmi application, both client and server
interacts with the remote interface. The client application invokes methods on the proxy object, RMI sends
the request to the remote JVM. The return value is sent back to the proxy object and then to the client
application.

1) create the remote interface


63 |M.sc sem I OOPs USING JAVA

For creating the remote interface, extend the Remote interface and declare the RemoteException with all
the methods of the remote interface. Here, we are creating a remote interface that extends the Remote
interface. There is only one method named add() and it declares RemoteException.

1. import java.rmi.*;
2. public interface Adder extends Remote{
3. public int add(int x,int y)throws RemoteException;
4. }

2) Provide the implementation of the remote interface


Now provide the implementation of the remote interface. For providing the implementation of the Remote
interface, we need to

o Either extend the UnicastRemoteObject class,


o or use the exportObject() method of the UnicastRemoteObject class

In case, you extend the UnicastRemoteObject class, you must define a constructor that declares RemoteException.
1. import java.rmi.*;
2. import java.rmi.server.*;
3. public class AdderRemote extends UnicastRemoteObject implements Adder{
4. AdderRemote()throws RemoteException{
5. super();
6. }
7. public int add(int x,int y){return x+y;}
8. }

3) create the stub and skeleton objects using the rmic tool.

Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool invokes the RMI
compiler and creates stub and skeleton objects.

1. rmic AdderRemote

4) Start the registry service by the rmiregistry tool


Now start the registry service by using the rmiregistry tool. If you don't specify the port number, it uses a
default port number. In this example, we are using the port number 5000.

1. rmiregistry 5000

5) Create and run the server application


64 |M.sc sem I OOPs USING JAVA

Now rmi services need to be hosted in a server process. The Naming class provides methods to get and
store the remote object. The Naming class provides 5 methods.

public static java.rmi.Remote lookup(java.lang.String) throws It returns the reference of the


java.rmi.NotBoundException, java.net.MalformedURLException, remote object.
java.rmi.RemoteException;

public static void bind(java.lang.String, java.rmi.Remote) throws It binds the remote object with
java.rmi.AlreadyBoundException, java.net.MalformedURLException, the given name.
java.rmi.RemoteException;

public static void unbind(java.lang.String) throws java.rmi.RemoteException, It destroys the remote object
java.rmi.NotBoundException, java.net.MalformedURLException; which is bound with the given
name.

public static void rebind(java.lang.String, java.rmi.Remote) throws It binds the remote object to the
java.rmi.RemoteException, java.net.MalformedURLException; new name.

public static java.lang.String[] list(java.lang.String) throws It returns an array of the names


java.rmi.RemoteException, java.net.MalformedURLException; of the remote objects bound in
the registry.

In this example, we are binding the remote object by the name sonoo.

1. import java.rmi.*;
2. import java.rmi.registry.*;
3. public class MyServer{
4. public static void main(String args[]){
5. try{
6. Adder stub=new AdderRemote();
7. Naming.rebind("rmi://localhost:5000/sonoo",stub);
8. }catch(Exception e){System.out.println(e);}
9. }
10. }

6) Create and run the client application


At the client we are getting the stub object by the lookup() method of the Naming class and invoking the
method on this object. In this example, we are running the server and client applications, in the same
machine so we are using localhost. If you want to access the remote object from another machine, change
the localhost to the host name (or IP address) where the remote object is located.

1. import java.rmi.*;
65 |M.sc sem I OOPs USING JAVA

2. public class MyClient{


3. public static void main(String args[]){
4. try{
5. Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
6. System.out.println(stub.add(34,4));
7. }catch(Exception e){}
8. }
9. }

download this example of rmi

1. For running this rmi example,


2.
3. 1) compile all the java files
4.
5. javac *.java
6.
7. 2)create stub and skeleton object by rmic tool
8.
9. rmic AdderRemote
10.
11. 3)start rmi registry in one command prompt
12.
13. rmiregistry 5000
14.
15. 4)start the server in another command prompt
16.
17. java MyServer
18.
19. 5)start the client application in another command prompt
20.
21. java MyClient

Output of this RMI example

Meaningful example of RMI application with database


66 |M.sc sem I OOPs USING JAVA

Consider a scenario, there are two applications running in different machines. Let's say MachineA and
MachineB, machineA is located in United States and MachineB in India. MachineB want to get list of all the
customers of MachineA application.

Let's develop the RMI application by following the steps.

1) Create the table

First of all, we need to create the table in the database. Here, we are using Oracle10 database

2) Create Customer class and Remote interface


File: Customer.java

1. package com.javatpoint;
2. public class Customer implements java.io.Serializable{
3. private int acc_no;
4. private String firstname,lastname,email;
5. private float amount;
6. //getters and setters
7. }
Note: Customer class must be Serializable.
File: Bank.java

1. package com.javatpoint;
2. import java.rmi.*;
3. import java.util.*;
4. interface Bank extends Remote{
5. public List<Customer> getCustomers()throws RemoteException;
6. }

3) Create the class that provides the implementation of Remote interface


File: BankImpl.java

1. package com.javatpoint;
2. import java.rmi.*;
3. import java.rmi.server.*;
4. import java.sql.*;
5. import java.util.*;
6. class BankImpl extends UnicastRemoteObject implements Bank{
7. BankImpl()throws RemoteException{}
8.
9. public List<Customer> getCustomers(){
10. List<Customer> list=new ArrayList<Customer>();
67 |M.sc sem I OOPs USING JAVA

11. try{
12. Class.forName("oracle.jdbc.driver.OracleDriver");
13. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
14. PreparedStatement ps=con.prepareStatement("select * from customer400");
15. ResultSet rs=ps.executeQuery();
16.
17. while(rs.next()){
18. Customer c=new Customer();
19. c.setAcc_no(rs.getInt(1));
20. c.setFirstname(rs.getString(2));
21. c.setLastname(rs.getString(3));
22. c.setEmail(rs.getString(4));
23. c.setAmount(rs.getFloat(5));
24. list.add(c);
25. }
26.
27. con.close();
28. }catch(Exception e){System.out.println(e);}
29. return list;
30. }//end of getCustomers()
31. }

4) Compile the class rmic tool and start the registry service by rmiregistry tool

5) Create and run the Server


File: MyServer.java

1. package com.javatpoint;
2. import java.rmi.*;
3. public class MyServer{
4. public static void main(String args[])throws Exception{
5. Remote r=new BankImpl();
6. Naming.rebind("rmi://localhost:6666/javatpoint",r);
7. }}

6) Create and run the Client


File: MyClient.java

1. package com.javatpoint;
2. import java.util.*;
3. import java.rmi.*;
68 |M.sc sem I OOPs USING JAVA

4. public class MyClient{


5. public static void main(String args[])throws Exception{
6. Bank b=(Bank)Naming.lookup("rmi://localhost:6666/javatpoint");
7.
8. List<Customer> list=b.getCustomers();
9. for(Customer c:list){
10. System.out.println(c.getAcc_no()+" "+c.getFirstname()+" "+c.getLastname()
11. +" "+c.getEmail()+" "+c.getAmount());
12. }
13.
14. }}

(11) Finding Remote objects

Finding and Using Remote Objects

Now that we’ve seen how to implement a CORBA remote object and register it with an
ORB, we can turn our attention to the heart of the matter: client applications that want to use
the object. As we said earlier, every CORBA process needs a reference to an ORB. Once a
client application has access to an ORB, next it must find remote objects to interact with.
But before we can discuss finding remote objects, we need to talk a bit about what remote
object references look like in the CORBA environment.

The whole point of CORBA is to be able to distribute objects across the network and use
them from any point. In order for a local process to make requests of a remote object, it
needs to have some kind of reference to that remote object. This object reference needs to
contain enough information for the local ORB to find the ORB serving the target object and
send the request to the remote ORB using an agreed-upon protocol.

Remote Object References and Narrowing

In most situations, a CORBA client has a reference to a remote object in the form of an
object stub. The stub encapsulates the actual object reference, providing what seems like a
direct interface to the remote object within the local environment. If the client is
implemented in C++, Java, or some other object-oriented language, the object stub is a
native object in that language. Other nonobject languages represent remote object references
in whatever way is dictated in the CORBA language binding for that language.
69 |M.sc sem I OOPs USING JAVA

CORBA includes its own root object class, because some object-programming languages
may have different inheritance structures. In the Java binding for CORBA, all CORBA
object references (local or remote) implement the org.omg.CORBA.Object interface. So, when a
client of a remote CORBA object receives a stub for the object, it actually gets
an org.omg.CORBA.Object that serves as a proxy for the remote object.
The org.omg.CORBA.portable.ObjectImpl class provides default client-side implementations for
the methods defined on org.omg.CORBA.Object. Java stubs (generated from the IDL-to-Java
compiler, as discussed earlier) for CORBA objects are actually subclassed from
the ObjectImpl class. Internally, ObjectImpl deals with delegating client requests on the object
stub to the proper target object, whether it’s a local or remote object. ObjectImpl implements
the org.omg.CORBA.Object interface and inherently extends the java.lang.Object class, so it
provides a joining point between the CORBA and Java object environments.[14]

A reference to an org.omg.CORBA.Object instance that is connected to a remote object is


actually all a client needs to invoke methods on a remote object. Using the Dynamic
Invocation Interface defined by the CORBA standard, you can create method requests and
send them to the remote object directly through the generic Object interface, as we’ll discuss
later in this chapter. If your client has the actual Java interface for the remote object
available at compile time, however, you probably want to convert the Object reference into a
reference of that type, so you can use the interface to call remote methods directly.

Converting an org.omg.COBRA.Object to a specific remote interface is done by narrowing the


object reference to the corresponding interface type, using type-specific helper classes.
We’ve already seen how the Java IDL compiler, idlj, creates a helper class from an IDL
interface (e.g., AccountHelper). The helper class includes a narrow( ) method that safely
converts an org.omg.CORBA.Object reference to a reference of the given type. If the object
reference you pass into the narrow( ) method is not the type the helper expects,
an org.omg.CORBA.BAD_PARAM exception is thrown. This is a RuntimeException, so it doesn’t have
to be caught by your code, unless you’re trying to test the type of a CORBA reference for
some reason.

This narrow( ) operation highlights one of the key differences between RMI and CORBA. In
the Java environment, class bytecodes are portable, and all remote object types are objects
that can be specified by their full class names. An RMI client can automatically download
the bytecodes for a remote stub from the object server, if the class for the stub can’t be found
locally (see Chapter 3 for more details on the mechanics of remote class loading). CORBA
is a language-independent remote object scheme, so there is no portable way to specify a
remote object’s native type when a client obtains a stub reference. In Java you could do this
using the same remote classloading scheme as RMI, but there isn’t a similar scheme
70 |M.sc sem I OOPs USING JAVA

available in C or C++, for example. As a result, the stub reference is initially represented by
a basic object type that knows how to forward method requests to its server object, but
doesn’t necessarily satisfy the mapped interface for the remote object type the client is
expecting. The client application is forced to “cast” this stub to the correct local type, using
the appropriate narrow( ) method. In the Java mapping of IDL, this means calling the narrow(
) method on the corresponding helper class. The narrow( ) method converts the reference,
making a type-specific stub interface that also includes the remote object reference
information needed to forward method requests to the actual object implementation.

Accessing Remote Objects

With that background material out of the way, let’s discuss actually finding remote object
references. There are many ways that an object reference can find its way through the ORB
into a client application, but they all boil down to one of these methods:

 Getting an initial reference directly from the ORB


 Getting an object reference through a method call on another remote object
reference
 Using a stringified object reference obtained through a secondary channel and
converting it to a live object reference
ORB Initial Object References

In addition to providing core object communication services, an ORB can also provide
additional services, such as a Naming Service, a Trading Service, a Security Service, etc.
These services are represented as CORBA objects and are typically available through the
ORB directly, based on how it is configured. The ORB interface provides
the resolve_initial_references( ) method for obtaining references to the objects that
represent these services. Each CORBA service is represented by one or more object
interfaces, and these objects can be asked for using standard names. As we saw earlier when
we registered CORBA objects, the standard name for the Naming Service is
“NameService,” and the object representing access to the Naming Service is
a NamingContext or NamingContextExt object. These represent the root of the naming hierarchy.

Once you’ve initialized your ORB reference (as described earlier in Initializing the ORB),
you can ask the ORB for a list of the names of the initial objects it has available, using
the list_initial_references( ) method:

String names[] = myORB.list_initial_references( );


71 |M.sc sem I OOPs USING JAVA

This method returns an array of String objects that contain the names of all initial objects in
the ORB. These names can then be used to get references to the objects through
the resolve_initial_references( ) method.

Here’s how we used resolve_initial_references( ) to obtain a reference to the Naming


Service in our earlier examples:

ORB myORB = ORB.init(...);

org.omg.CORBA.Object nameRef =

myORB.resolve_initial_references("NameService");

Although the list_initial_references( ) and resolve_initial_references( ) methods are a


standard element of the ORB interface, how a particular ORB implements these initial
object references is not standardized. Sun’s Java IDL implementation, for example, stores an
ORB’s initial object references as root objects in its internal Naming Service.

Getting Objects from Other Remote Objects

In addition to getting remote objects directly from an ORB reference, a client can obtain
remote objects from other remote objects. The most common variation on this approach is to
get a reference to a Naming Service object and then look up objects in the naming directory
by name. Another variation (that we won’t cover in detail in this section) is to obtain an
application-specific object reference, either directly from the ORB or through the Naming
Service, and use this initial reference to request other objects. An object used in this way in a
distributed application is sometimes called a factory object.

Naming service lookups

Once you have a NamingContext reference that points to a position (either the root or a
subdirectory) in a Naming Service, you can look up objects within the context by passing
names to its resolve( ) method. As before, when we were binding objects, a name is
represented by an ordered array of NameComponent objects. Each NameComponent (both the id field
and the kind field) must exactly match the path to an object within the context in order to
successfully find the object. If an object is not found at a specified name,
an org.omg.CosNaming.NamingContextPackage.NotFound exception is thrown.
72 |M.sc sem I OOPs USING JAVA

So, if a client wants to find the account for Mary Jones, we stored in the last binding
example, which needs to do the following:

// Set up the full path to the account

NameComponent comp1 = new NameComponent("bankBranches", "");

NameComponent comp2 = new NameComponent("Cambridge", "");

NameComponent acctName = new NameComponent("Jones,M", "");

NameComponent acctPath[] = { comp1, comp2, acctName };

// Find the object in the directory

org.omg.CORBA.Object acctRef = rootNC.resolve(acctPath);

Account acct = AccountHelper.narrow(acctRef);

We’re assuming that rootNC is a reference to the root context of the Naming Service holding
the Account object references. Note the use of the narrow( ) method on AccountHelper to “cast”
the generic object reference to an Account object.

In addition to finding references to objects (leaf nodes) in the Naming Service, you can also
use the resolve( ) method on a NamingContext to get a reference to a subcontext (a
subdirectory). Just use the path to the context itself and narrow( ) it to
a NamingContext reference:

Object URLs

As we’ve seen, Sun’s implementation of Java IDL provides a nonstandard way to initialize
an ORB to reference a remote Naming Service, so that one of the ORB’s initial references is
to the root context of the remote Naming Service. But what do you do if you want an object
from a remote Naming Service and your Java IDL implementation doesn’t provide a way to
directly initialize a reference to the remote service? Or, worse yet, what if the object that you
want isn’t stored in a Naming Service or available through any other CORBA service? How
can your client get a reference to the object?

The CORBA standard comes to the rescue again. CORBA defines several ways to
represent stringified object references, or remote object URLs. In other words, you can fully
73 |M.sc sem I OOPs USING JAVA

specify a specific CORBA server object using a URL syntax, which is very similar to the
URL syntax used to specify Java RMI objects in an RMI registry (see Chapter 3 for more
details on RMI registry URLs). These object URLs are called “stringified object references”
in the CORBA specifications, because that’s exactly what they are: strings that can be sent
around the network (in email, in configuration files, etc.), and used by clients to obtain a
living reference to the object that the URL specifies. So these object URLs are called
“stringified object references” in the same way that you could call HTML document URLs
“stringified document references.”

In these URL schemes, the objects being referenced need to be hosted behind an ORB
someplace on the network, and they must have a server process running that is listening for
remote method requests for that object. In some cases; the objects and their request servers
can just be connected directly to the ORB, in other cases they have to be bound to a name in
a Naming Service, with the Naming Service acting as the method request mediator.

There are three basic forms of object URLs defined in the CORBA standards:

Interoperable Object References (IORs)

These URLs are based on a syntax for representing a remote object reference in the
form of a printable, but not human-readable, string of characters. This stringified
object reference includes enough information for a remote CORBA client to locate the
object’s home ORB and convert the string to a runtime stub reference to the object.
Two methods on the ORB interface, object_to_string( ) and string_to_object( ), let you
convert a CORBA object reference to an IOR and back into an object reference. An
object doesn’t need to be bound to a name in a Naming Service in order to have an
IOR; it simply needs to be exported through an ORB using an object adaptor, like the
POA.

corbaloc URLs

These URLs are a human-readable URL format for object references. They are similar
in purpose to IORs: an object needs to be exported through an ORB for remote access
in order to have a corbaloc URL associated with it. So corbaloc URLs point to a single
object accessible directly through an ORB, without the help of a service of some kind.
The same restrictions apply for making servants accessible through corbaloc URLs as
for IORs -- the servant object needs to be connected to an ORB through some kind of
object adaptor, like the POA.

corbaname URLs
74 |M.sc sem I OOPs USING JAVA

These URLs are extensions to the corbaloc syntax to allow for references to objects
that are registered with a CORBA Naming Service. The URL format includes
additional information that specifies the object’s location (name) in the Naming
Service.

The full syntax for all three of these CORBA object URL schemes is spelled out fully
in Chapter 15. But the following examples should demonstrate their basic use.

Example 4-7 shows AccountInit, a server that creates an instance of our AccountImplPOA and
makes it available for clients to access. In its main( ) method, it initializes the ORB, then
creates an instance of our Account servant. We’re assuming that a POA-compliant version of
Java IDL is being used, so the next thing to do is get a reference to the root POA
(using resolve_initial_references( )) and activate the POA manager, then ask the POA to
activate our servant object. By activating our servant object this way, we’re guaranteed that
any “direct” IIOP requests (through either an IOR or a corbaloc URL) will be accepted
immediately. Note that in order for the generated IOR to be acceptable to another ORB, both
your ORB and the remote ORB have to be using the same inter-ORB communication
protocol (IIOP, DCE-CIOP, etc.). In this example, we’ll assume that our client and object
server are both running IIOP.

(12) JCP, JSR, and other

Java Community Process (JCP) and Java Specification Request


(JSR)

I wanted to introduce two important things in java, the JCP and JSR in this article. A java guy
must be knowing about these and no excuse. Java community process gives us the public an
opportunity to participate in the development and maintenance of the Java platform. This is one
of the best thing in java. It gives us a voice to raise our concern, ask for a feature we love and
change the way java works.

JCP was launched by Sun Microsystems on December, 1998. JCP was created long back just after
three years from the creation of java. JCP is still alive and going great. Can we attribute the
success of java platform to JCP?

jcp.org is the website and we can register in it. Registering in website, enables us to use it in a
better way but that does not make us a JCP member. It is governed by a membership program for
75 |M.sc sem I OOPs USING JAVA

which we need to register separately. As of the moment of writing we have following options to
register as a JCP member,

 commercial entities: $5000


 educational/non-profit organizations: $2000
 individuals: $0
 existing licensees: $0
 Java User Groups: $0

Registration process is kind of cumbersome.

JCP gives annual awards in the following three categories,

 JCP member of the year


 Outstanding spec lead
 Most significant JSR

Java Specification Request (JSR)

So how do we participate? Java specification request (JSR) is the mechanism provided by JCP to
participate in it. JSR is a formal documentation that describes the technology request in detailed
manner. A JSR can be initiated by a JCP member. It goes through multiple stages and finally for
implementation. At any time there will be multiple JSRs in different stages.

I recommend you to choose a JSR which you like and join its mailing list. Let it be your first step.
Go through that JSR and try to understand it and follow it in different stages. When it gets
implemented, you will have nice hold on it and may be that will take you to the next level of
actively participating in a JSR.

Presently there are 927 JSRs in all. We can submit our own java specification request (JSR). JSR
for the next major release Java 8 is JSR 337.

Four stages of a JSR

1. Initiation – First stage of a JSR, just a proposal is initiated by JCP member.


2. Early Draft Review – Once the initiation is approved, an expert group will work on creating
a early draft of that JSR. JCP and executive committee will review the draft and approve it.
3. Public Draft – Once the early draft is approved, specification comes to this public draft
stage. The specification is given to the public for open review and it is revised, a reference
implementation is created then a final draft is taken to Executive Committee for approval.
76 |M.sc sem I OOPs USING JAVA

4. Maintenance – Once the final draft is approved, the specification enters the maintenance
phase. The specification is revised based on clarifications, requests, issues and for
enhancements.

(13) Java EE Applications


Java EE
The Java EE stands for Java Enterprise Edition, which was earlier known as J2EE and is currently known
as Jakarta EE. It is a set of specifications wrapping around Java SE (Standard Edition). The Java EE provides
a platform for developers with enterprise features such as distributed computing and web services. Java EE
applications are usually run on reference run times such as microservers or application servers. Examples
of some contexts where Java EE is used are e-commerce, accounting, banking information systems.

Specifications of Java EE
Java EE has several specifications which are useful in making web pages, reading and writing from database
in a transactional way, managing distributed queues. The Java EE contains several APIs which have the
functionalities of base Java SE APIs such as Enterprise JavaBeans, connectors, Servlets, Java Server Pages
and several web service technologies.

1. Web Specifications of Java EE

o Servlet- This specification defines how you can manage HTTP requests either in a synchronous or
asynchronous way. It is low level, and other specifications depend on it
o WebSocket- WebSocket is a computer communication protocol, and this API provides a set of APIs to
facilitate WebSocket connections.
o Java Server Faces- It is a service which helps in building GUI out of components.
77 |M.sc sem I OOPs USING JAVA

o Unified Expression Language- It is a simple language which was designed to facilitate web application
developers.

2. Web Service Specifications of Java EE

o Java API for RESTful Web Services- It helps in providing services having Representational State Transfer
schema.
o Java API for JSON Processing- It is a set of specifications to manage the information provided in JSON format.
o Java API for JSON Binding- It is a set of specifications provide for binding or parsing a JSON file into Java
classes.
o Java Architecture for XML Binding- It allows binding of xml into Java objects.
o Java API for XML Web Services- SOAP is an xml based protocol to access web services over http. This API
allows you to create SOAP web services.

3. Enterprise Specifications of Java EE

o Contexts and Dependency Injection- It provides a container to inject dependencies as in Swing.


o Enterprise JavaBean- It is a set of lightweight APIs that an object container possesses in order to provide
transactions, remote procedure calls, and concurrency control.
o Java Persistence API- These are the specifications of object-relational mapping between relational database
tables and Java classes.
o Java Transaction API- It contains the interfaces and annotations to establish interaction between transaction
support offered by Java EE. The APIs in this abstract from low-level details and the interfaces are also
considered low-level.
o Java Message Service- It provides a common way to Java program to create, send and read enterprise
messaging system's messages.

4. Other Specifications of Java EE

o Validation- This package contains various interfaces and annotations for declarative validation support
offered by Bean Validation API.
o Batch applications- It provides the means to run long running background tasks which involve a large volume
of data and which need to be periodically executed.
o Java EE Connector Architecture- This is a Java-based technological solution for connecting Java servers to
Enterprise Information System.

Setting up Java EE
Requirements
78 |M.sc sem I OOPs USING JAVA

For the installation of latest SDK of Java EE which is Java EE 6 SDK on windows, you require to have a
minimum memory of 1GB, minimum Disk space of 250MB free and JVM Java SE 6. For setting up Java EE,
you require to have a JDK and then have an IDE preferably Eclipse as it is free.

Install a Java Development Kit

1. Browse to Oracle's Java SE Development Kit downloads


2. In the section titled Java SE Development Kit 9.0.1, read the license and, if you agree, click Accept License
Agreement
3. Still, in that section, click on JDK-9.0.1_windows-x64_bin.exe (or the right download for your OS)
4. Run the downloaded JDK installer, using Run As Administrator
5. Add the Windows (or Linux) Environment Variable JAVA_HOME. Set it to the root folder of your newly-
installed JDK, which looks like C:\Program Files\Java\jdk1.8.0_51.

Install Eclipse for Java EE


1. Browse to Eclipse Downloads

2. Click on the Download button under Get Eclipse.

3. On the resulting page, click on the Download button.

Note: The version of Eclipse (32-bit or 64-bit) which you download should match the version of your
JDK. You installed JDK-9.0.1_windows-x64 above, so download the 64-bit Eclipse.

4. Run the downloaded installer using Run as Administrator.

5. Choose the version of Eclipse you wish to install. Eclipse IDE for Java EE developers is preferable for
Java work.

6. If the installation fails, try again with real-time virus scanning temporarily turned off. Remember to turn
it on again when it's done.

Java SE vs Java EE
Java SE refers to standard edition and contains basic functionalities and packages required by a beginner
or intermediate-level programmer. Java EE is an enhanced platform and a wrapper around Java SE. It has
the edge over Java SE an also has a variety of aspects in which it outshines other features.

Java SE Java EE

Java SE provide basic functionalities such as defining Java EE facilitates development of large scale
types and objects. applications.
79 |M.sc sem I OOPs USING JAVA

SE is a normal Java specification EE is built upon Java SE. It provides functionalities like
web applications, and Servlets.

It has features like class libraries, deployment Java EE is a structured application with a separate
environments, etc. client, business, and Enterprise layers.

It is mostly used to develop APIs for Desktop It is mainly used for developing web applications.
Applications like antivirus software, game, etc.

Suitable for beginning Java developers. Suitable for experienced Java developers who build
enterprise-wide applications.

It does not provide user authentication. It provides user authentication.

You might also like