Sunday, January 8, 2012

Java - Networking (Socket Programming)


The term network programming refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.

The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details, allowing you to write programs that focus on solving the problem at hand.

The java.net package provides support for the two common network protocols:

TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.

UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications.

This tutorial gives good understanding on the following two subjects:

Socket Programming: This is most widely used concept in Networking and it has been explained in very detail.

URL Processing: This would be covered separately. Click here to learn about URL Processing in Java language.

The Collection Classes:


Java provides a set of standard collection classes that implement Collection interfaces. Some of the classes provide full implementations that can be used as-is and others are abstract class, providing skeletal implementations that are used as starting points for creating concrete collections.

The standard collection classes are summarized in the following table:



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.

Java - Collections Framework


Prior to Java 2, Java provided ad hoc classes such as Dictionary, Vector, Stack, andProperties to store and manipulate groups of objects. Although these classes were quite useful, they lacked a central, unifying theme. Thus, the way that you used Vector was different from the way that you used Properties.
The collections framework was designed to meet several goals.
  1. The framework had to be high-performance. The implementations for the fundamental collections (dynamic arrays, linked lists, trees, and hash tables) are highly efficient.
  2. The framework had to allow different types of collections to work in a similar manner and with a high degree of interoperability.
  3. Extending and/or adapting a collection had to be easy.
Toward this end, the entire collections framework is designed around a set of standard interfaces. Several standard implementations such as LinkedList, HashSet, and TreeSet, of these interfaces are provided that you may use as-is and you may also implement your own collection, if you choose.
A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:
  1. Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.
  2. Implementations i.e. Classes: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.
  3. Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface.
In addition to collections, the framework defines several map interfaces and classes. Maps store key/value pairs. Although maps are not collections in the proper use of the term, but they are fully integrated with collections.

Wednesday, December 14, 2011

Exceptions in Java -II

Throwable Class 

The Throwable class provides a String variable that can be set by the subclasses to provide a detail message that provides more information of the exception occurred. All classes of throwables define a one-parameter constructor that takes a string as the detail message.

The class Throwable provides getMessage() function to retrieve an exception. It has a printStackTrace() method to print the stack trace to the standard error stream. Lastly It also has a toString() method to print a short description of the exception. For more information on what is printed when the following messages are invoked, please refer the java docs.

Syntax

String getMessage()

void printStackTrace()

String toString()

Class Exception

The class Exception represents exceptions that a program faces due to abnormal or special conditions during execution. Exceptions can be of 2 types: Checked (Compile time Exceptions)/ Unchecked (Run time Exceptions).

Class RuntimeException

Runtime exceptions represent programming errors that manifest at runtime. For example

ArrayIndexOutOfBounds, NullPointerException and so on are all subclasses of the java.lang.RuntimeException class, which is a subclass of the Exception class. These are basically business logic programming errors.

Class Error

Errors are irrecoverable condtions that can never be caught. Example: Memory leak, LinkageError etc. Errors are direct subclass of Throwable class.

A Program Showing How the JVM throws an Exception at runtime

public class DivideException {

    public static void main(String[] args) {
        division(100,4);        // Line 1
        division(100,0);        // Line 2
        System.out.println("Exit main().");
    }

    public static void division(int totalSum, int totalNumber) {

        System.out.println("Computing Division.");
        int average  = totalSum/totalNumber;
        System.out.println("Average : "+ average);
    }
}
++++++++++++++++++++++++
An ArithmeticException is thrown at runtime when Line 11 is executed because integer division by 0 is an illegal operation. The “Exit main()” message is never reached in the main method
Output
Computing Division.
java.lang.ArithmeticException: / by zero
Average : 25
Computing Division.
at DivideException.division(DivideException.java:11)
at DivideException.main(DivideException.java:5)

Exception in thread “main”


Exceptions in java

Exceptions in java are any abnormal, unexpected events or extraordinary conditions that may occur at runtime. They could be file not found exception, unable to get connection exception and so on. On such conditions java throws an exception object. Java Exceptions are basically Java objects. No Project can never escape a java error exception.

Java exception handling is used to handle error conditions in a program systematically by taking the necessary action. Exception handlers can be written to catch a specific exception such as Number Format exception, or an entire group of exceptions by using a generic exception handlers. Any exceptions not specifically handled within a Java program are caught by the Java run time environment

An exception is a subclass of the Exception/Error class, both of which are subclasses of the Throwable class. Java exceptions are raised with the throw keyword and handled within a catch block.

Tuesday, November 29, 2011

Creating a Thread



Java defines two ways in which this can be accomplished:
  • You can implement the Runnable interface.
  • You can extend the Thread class, itself.

Create Thread by Implementing Runnable:

The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class need only implement a single method called run( ), which is declared like this:
public void run( )
You will define the code that constitutes the new thread inside run() method. It is important to understand that run() can call other methods, use other classes, and declare variables, just like the main thread can.
After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread defines several constructors. The one that we will use is shown here:
Thread(Runnable threadOb, String threadName);
Here threadOb is an instance of a class that implements the Runnable interface and the name of the new thread is specified by threadName.
After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. The start( ) method is shown here:
void start( );

Example:

Here is an example that creates a new thread and starts it running:
// Create a new thread.
class NewThread implements Runnable {
   Thread t;
   NewThread() {
      // Create a new, second thread
      t = new Thread(this, "Demo Thread");
      System.out.println("Child thread: " + t);
      t.start(); // Start the thread
   }
   
   // This is the entry point for the second thread.
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
            // Let the thread sleep for a while.
            Thread.sleep(500);
         }
     } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
     }
     System.out.println("Exiting child thread.");
   }
}

class ThreadDemo {
   public static void main(String args[]) {
      new NewThread(); // create a new thread
      try {
         for(int i = 5; i > 0; i--) {
           System.out.println("Main Thread: " + i);
           Thread.sleep(1000);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}
This would produce following result:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

How to find the most appropriate Keywords?

  🔍 Step 1: Understand Your Business and Audience Define your products, services, or content . Identify your target audien...