1. Java - Data Structures
The data structures provided by the Java utility package are very powerful and perform a wide range of functions. These data structure...
Everything is in this blog
1. Java - Data Structures
The data structures provided by the Java utility package are very powerful and perform a wide range of functions. These data structure...
2. Java Collections Framework
Prior to Java 2, Java provided ad hoc classes such as Dictionary, Vector, Stack , and Properties to store and manipulate groups of ob...
3. Java - Generics
It would be nice if we could write a single sort method that could sort the elements in an Integer array, a String array or an array o...
4. Java - Serialization
Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the ob...
5. Java - Networking
The term network programming refers to writing programs that execute across multiple devices (computers), in which the devices are a...
6. Java - Sending Email
To send an e-mail using your Java Application is simple enough but to start with you should have JavaMail API and Java Activation Fram...
Replace these every slider sentences with your featured post descriptions.Go to Blogger edit html and find these sentences.Now replace these with your own descriptions.
Replace these every slider sentences with your featured post descriptions.Go to Blogger edit html and find these sentences.Now replace these with your own descriptions.
Replace these every slider sentences with your featured post descriptions.Go to Blogger edit html and find these sentences.Now replace these with your own descriptions.

| SN | Interfaces with Description |
|---|---|
| 1 | The Collection Interface This enables you to work with groups of objects; it is at the top of the collections hierarchy. |
| 2 | The List Interface This extends Collection and an instance of List stores an ordered collection of elements. |
| 3 | The Set This extends Collection to handle sets, which must contain unique elements |
| 4 | The SortedSet This extends Set to handle sorted sets |
| 5 | The Map This maps unique keys to values. |
| 6 | The Map.Entry This describes an element (a key/value pair) in a map. This is an inner class of Map. |
| 7 | The SortedMap This extends Map so that the keys are maintained in ascending order. |
| 8 | The Enumeration This is legacy interface and defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. This legacy interface has been superceded by Iterator. |
| SN | Classes with Description |
|---|---|
| 1 | AbstractCollection
Implements most of the Collection interface. |
| 2 | AbstractList
Extends AbstractCollection and implements most of the List interface. |
| 3 | AbstractSequentialList
Extends AbstractList for use by a collection that uses
sequential rather than random access of its elements. |
| 4 | LinkedList Implements a linked list by extending AbstractSequentialList. |
| 5 | ArrayList Implements a dynamic array by extending AbstractList. |
| 6 | AbstractSet
Extends AbstractCollection and implements most of the Set interface. |
| 7 | HashSet Extends AbstractSet for use with a hash table. |
| 8 | LinkedHashSet Extends HashSet to allow insertion-order iterations. |
| 9 | TreeSet Implements a set stored in a tree. Extends AbstractSet. |
| 10 | AbstractMap
Implements most of the Map interface. |
| 11 | HashMap Extends AbstractMap to use a hash table. |
| 12 | TreeMap Extends AbstractMap to use a tree. |
| 13 | WeakHashMap Extends AbstractMap to use a hash table with weak keys. |
| 14 | LinkedHashMap Extends HashMap to allow insertion-order iterations. |
| 15 | IdentityHashMap Extends AbstractMap and uses reference equality when comparing documents. |
| SN | Classes with Description |
|---|---|
| 1 | Vector This implements a dynamic array. It is similar to ArrayList, but with some differences. |
| 2 | Stack Stack is a subclass of Vector that implements a standard last-in, first-out stack. |
| 3 | Dictionary Dictionary is an abstract class that represents a key/value storage repository and operates much like Map. |
| 4 | Hashtable Hashtable was part of the original java.util and is a concrete implementation of a Dictionary. |
| 5 | Properties Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String. |
| 6 | BitSet A BitSet class creates a special type of array that holds bit values. This array can increase in size as needed. |
| SN | Algorithms with Description |
|---|---|
| 1 | The Collection Algorithms Here is a list of all the algorithm implementation. |
| SN | Iterator Methods with Description |
|---|---|
| 1 | Using Java Iterator Here is a list of all the methods with examples provided by Iterator and ListIterator interfaces. |
| SN | Iterator Methods with Description |
|---|---|
| 1 | Using Java Comparator Here is a list of all the methods with examples provided by Comparator Interface. |

public class GenericMethodTest { // generic method printArray public static < E > void printArray( E[] inputArray ) { // Display array elements for ( E element : inputArray ){ System.out.printf( "%s ", element ); } System.out.println(); } public static void main( String args[] ) { // Create arrays of Integer, Double and Character Integer[] intArray = { 1, 2, 3, 4, 5 }; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 }; Character[] charArray = { 'H', 'E', 'L', 'L', 'O' }; System.out.println( "Array integerArray contains:" ); printArray( intArray ); // pass an Integer array System.out.println( "\nArray doubleArray contains:" ); printArray( doubleArray ); // pass a Double array System.out.println( "\nArray characterArray contains:" ); printArray( charArray ); // pass a Character array } }This would produce the following result:
Array integerArray contains: 1 2 3 4 5 6 Array doubleArray contains: 1.1 2.2 3.3 4.4 Array characterArray contains: H E L L O
public class MaximumTest { // determines the largest of three Comparable objects public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; // assume x is initially the largest if ( y.compareTo( max ) > 0 ){ max = y; // y is the largest so far } if ( z.compareTo( max ) > 0 ){ max = z; // z is the largest now } return max; // returns the largest object } public static void main( String args[] ) { System.out.printf( "Max of %d, %d and %d is %d\n\n", 3, 4, 5, maximum( 3, 4, 5 ) ); System.out.printf( "Maxm of %.1f,%.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) ); System.out.printf( "Max of %s, %s and %s is %s\n","pear", "apple", "orange", maximum( "pear", "apple", "orange" ) ); } }This would produce the following result:
Maximum of 3, 4 and 5 is 5 Maximum of 6.6, 8.8 and 7.7 is 8.8 Maximum of pear, apple and orange is pear
public class Box<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); Box<String> stringBox = new Box<String>(); integerBox.add(new Integer(10)); stringBox.add(new String("Hello World")); System.out.printf("Integer Value :%d\n\n", integerBox.get()); System.out.printf("String Value :%s\n", stringBox.get()); } }This would produce the following result:
Integer Value :10 String Value :Hello World

public final void writeObject(Object x) throws IOExceptionThe above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object:
public final Object readObject() throws IOException, ClassNotFoundExceptionThis method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type.
public class Employee implements java.io.Serializable { public String name; public String address; public transient int SSN; public int number; public void mailCheck() { System.out.println("Mailing a check to " + name + " " + address); } }Notice that for a class to be serialized successfully, two conditions must be met:
import java.io.*; public class SerializeDemo { public static void main(String [] args) { Employee e = new Employee(); e.name = "Reyan Ali"; e.address = "Phokka Kuan, Ambehta Peer"; e.SSN = 11122333; e.number = 101; try { FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.printf("Serialized data is saved in /tmp/employee.ser"); }catch(IOException i) { i.printStackTrace(); } } }
import java.io.*; public class DeserializeDemo { public static void main(String [] args) { Employee e = null; try { FileInputStream fileIn = new FileInputStream("/tmp/employee.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); e = (Employee) in.readObject(); in.close(); fileIn.close(); }catch(IOException i) { i.printStackTrace(); return; }catch(ClassNotFoundException c) { System.out.println("Employee class not found"); c.printStackTrace(); return; } System.out.println("Deserialized Employee..."); System.out.println("Name: " + e.name); System.out.println("Address: " + e.address); System.out.println("SSN: " + e.SSN); System.out.println("Number: " + e.number); } }This would produce the following result:
Deserialized Employee... Name: Reyan Ali Address:Phokka Kuan, Ambehta Peer SSN: 0 Number:101Here are following important points to be noted:

| SN | Methods with Description |
|---|---|
| 1 | public ServerSocket(int port) throws IOException
Attempts to create a server socket bound to the specified port. An
exception occurs if the port is already bound by another application. |
| 2 | public ServerSocket(int port, int backlog) throws IOException
Similar to the previous constructor, the backlog parameter specifies how many
incoming clients to store in a wait queue. |
| 3 | public ServerSocket(int port, int backlog, InetAddress address) throws IOException
Similar to the previous constructor, the InetAddress
parameter specifies the local IP address to bind to. The InetAddress is
used for servers that may have multiple IP addresses, allowing the
server to specify which of its IP addresses to accept client requests on |
| 4 | public ServerSocket() throws IOException
Creates an unbound server socket. When using this constructor, use the bind() method when you
are ready to bind the server socket |
| SN | Methods with Description |
|---|---|
| 1 | public int getLocalPort()
Returns the port that the server socket is listening on. This method
is useful if you passed in 0 as the port number in a constructor and let
the server find a port for you. |
| 2 | public Socket accept() throws IOException
Waits for an incoming client. This method blocks until either a
client connects to the server on
the specified port or the socket times out, assuming that the time-out
value has been set using the setSoTimeout() method. Otherwise, this
method blocks indefinitely |
| 3 | public void setSoTimeout(int timeout)
Sets the time-out value for how long the server socket waits for a client during the accept(). |
| 4 | public void bind(SocketAddress host, int backlog) Binds the socket to the specified server and port in the SocketAddress object. Use this method if you instantiated the ServerSocket using the no-argument constructor. |
| SN | Methods with Description |
|---|---|
| 1 | public Socket(String host, int port) throws UnknownHostException, IOException.
This method attempts to connect to the specified server at the
specified port. If this constructor does not throw an exception, the
connection is successful and the client is connected to the server. |
| 2 | public Socket(InetAddress host, int port) throws IOException
This method is identical to the previous constructor, except that the host is denoted by an InetAddress object. |
| 3 | public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException.
Connects to the specified host and port,
creating a socket on the local host at the specified address and port. |
| 4 | public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException.
This method is identical to the previous constructor, except that the
host is denoted by an InetAddress object instead of a String |
| 5 | public Socket()
Creates an unconnected socket. Use the connect() method to connect this socket to a server. |
| SN | Methods with Description |
|---|---|
| 1 | public void connect(SocketAddress host, int timeout) throws IOException
This method connects the socket to the specified host. This method is
needed only when you instantiated the Socket using the no-argument
constructor. |
| 2 | public InetAddress getInetAddress()
This method returns the address of the other computer that this socket is connected to. |
| 3 | public int getPort()
Returns the port the socket is bound to on the remote machine. |
| 4 | public int getLocalPort()
Returns the port the socket is bound to on the local machine. |
| 5 | public SocketAddress getRemoteSocketAddress()
Returns the address of the remote socket. |
| 6 | public InputStream getInputStream() throws IOException
Returns the input stream of the socket. The input stream is connected to the output
stream of the remote socket. |
| 7 | public OutputStream getOutputStream() throws IOException
Returns the output stream of the socket. The output stream is connected to the
input stream of the remote socket |
| 8 | public void close() throws IOException
Closes the socket, which makes this Socket object no longer capable of connecting again to any server |
| SN | Methods with Description |
|---|---|
| 1 | static InetAddress getByAddress(byte[] addr)
Returns an InetAddress object given the raw IP address . |
| 2 | static InetAddress getByAddress(String host, byte[] addr)
Create an InetAddress based on the provided host name and IP address. |
| 3 | static InetAddress getByName(String host)
Determines the IP address of a host, given the host's name. |
| 4 | String getHostAddress()
Returns the IP address string in textual presentation. |
| 5 | String getHostName()
Gets the host name for this IP address. |
| 6 | static InetAddress InetAddress getLocalHost()
Returns the local host. |
| 7 | String toString()
Converts this IP address to a String. |
// File Name GreetingClient.java import java.net.*; import java.io.*; public class GreetingClient { public static void main(String [] args) { String serverName = args[0]; int port = Integer.parseInt(args[1]); try { System.out.println("Connecting to " + serverName + " on port " + port); Socket client = new Socket(serverName, port); System.out.println("Just connected to " + client.getRemoteSocketAddress()); OutputStream outToServer = client.getOutputStream(); DataOutputStream out = new DataOutputStream(outToServer); out.writeUTF("Hello from " + client.getLocalSocketAddress()); InputStream inFromServer = client.getInputStream(); DataInputStream in = new DataInputStream(inFromServer); System.out.println("Server says " + in.readUTF()); client.close(); }catch(IOException e) { e.printStackTrace(); } } }
// File Name GreetingServer.java import java.net.*; import java.io.*; public class GreetingServer extends Thread { private ServerSocket serverSocket; public GreetingServer(int port) throws IOException { serverSocket = new ServerSocket(port); serverSocket.setSoTimeout(10000); } public void run() { while(true) { try { System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "..."); Socket server = serverSocket.accept(); System.out.println("Just connected to " + server.getRemoteSocketAddress()); DataInputStream in = new DataInputStream(server.getInputStream()); System.out.println(in.readUTF()); DataOutputStream out = new DataOutputStream(server.getOutputStream()); out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!"); server.close(); }catch(SocketTimeoutException s) { System.out.println("Socket timed out!"); break; }catch(IOException e) { e.printStackTrace(); break; } } } public static void main(String [] args) { int port = Integer.parseInt(args[0]); try { Thread t = new GreetingServer(port); t.start(); }catch(IOException e) { e.printStackTrace(); } } }Compile client and server and then start server as follows:
$ java GreetingServer 6066 Waiting for client on port 6066...Check client program as follows:
$ java GreetingClient localhost 6066 Connecting to localhost on port 6066 Just connected to localhost/127.0.0.1:6066 Server says Thank you for connecting to /127.0.0.1:6066 Goodbye!

// File Name SendEmail.java import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendEmail { public static void main(String [] args) { // Recipient's email ID needs to be mentioned. String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned String from = "web@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try{ // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Now set the actual message message.setText("This is actual message"); // Send message Transport.send(message); System.out.println("Sent message successfully...."); }catch (MessagingException mex) { mex.printStackTrace(); } } }Compile and run this program to send a simple e-mail:
$ java SendEmail Sent message successfully....If you want to send an e-mail to multiple recipients then following methods would be used to specify multiple e-mail IDs:
void addRecipients(Message.RecipientType type, Address[] addresses) throws MessagingExceptionHere is the description of the parameters:
// File Name SendHTMLEmail.java import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendHTMLEmail { public static void main(String [] args) { // Recipient's email ID needs to be mentioned. String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned String from = "web@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try{ // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Send the actual HTML message, as big as you like message.setContent("Compile and run this program to send an HTML e-mail:This is actual message
", "text/html" ); // Send message Transport.send(message); System.out.println("Sent message successfully...."); }catch (MessagingException mex) { mex.printStackTrace(); } } }
$ java SendHTMLEmail Sent message successfully....
// File Name SendFileEmail.java import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendFileEmail { public static void main(String [] args) { // Recipient's email ID needs to be mentioned. String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned String from = "web@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try{ // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setText("This is message body"); // Create a multipar message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); String filename = "file.txt"; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // Send the complete message parts message.setContent(multipart ); // Send message Transport.send(message); System.out.println("Sent message successfully...."); }catch (MessagingException mex) { mex.printStackTrace(); } } }Compile and run this program to send an HTML e-mail:
$ java SendFileEmail Sent message successfully....
props.setProperty("mail.user", "myuser"); props.setProperty("mail.password", "mypwd");Rest of the e-mail sending mechanism would remain as explained above.

