Sunday, 4 September 2011

Unit-IV Multithreaded Programming and Applets



Introduction to Threads

Multithreading refers to two or more tasks executing concurrently within a single program. A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class. A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously.
Multithreading has several advantages over Multiprocessing such as;
  • Threads are lightweight compared to processes
  • Threads share the same address space and therefore can share both data and code
  • Context switching between threads is usually less expensive than between processes
  • Cost of thread intercommunication is relatively low that that of process intercommunication
  • Threads allow different tasks to be performed concurrently.



Thread Creation

There are two ways to create thread in java;
  • Implement the Runnable interface (java.lang.Runnable)
  • By Extending the Thread class (java.lang.Thread)

Implementing the Runnable Interface

The Runnable Interface Signature
public interface Runnable {
void run();
}
One way to create a thread in java is to implement the Runnable Interface and then instantiate an object of the class. We need to override the run() method into our class which is the only method that needs to be implemented. The run() method contains the logic of the thread.
The procedure for creating threads based on the Runnable interface is as follows:
1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object.
2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method.
3. The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned.
4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception.
Below is a program that illustrates instantiation and running of threads using the runnable interface instead of extending the Thread class. To start the thread you need to invoke the start() method on your object.
class RunnableThread implements Runnable {
 
        Thread runner;
        public RunnableThread() {
        }
        public RunnableThread(String threadName) {
               runner = new Thread(this, threadName); // (1) Create a new thread.
               System.out.println(runner.getName());
               runner.start(); // (2) Start the thread.
        }
        public void run() {
               //Display info about this particular thread
               System.out.println(Thread.currentThread());
        }
}
 
public class RunnableExample {
 
        public static void main(String[] args) {
               Thread thread1 = new Thread(new RunnableThread(), "thread1");
               Thread thread2 = new Thread(new RunnableThread(), "thread2");
               RunnableThread thread3 = new RunnableThread("thread3");
               //Start the threads
               thread1.start();
               thread2.start();
               try {
                       //delay for one second
                       Thread.currentThread().sleep(1000);
               } catch (InterruptedException e) {
               }
               //Display info about the main thread
               System.out.println(Thread.currentThread());
        }
}
Output
thread3
Thread[thread1,5,main]
Thread[thread2,5,main]
Thread[thread3,5,main]
Thread[main,5,main]private
Download Runnable Thread Program Example
This approach of creating a thread by implementing the Runnable Interface must be used whenever the class being used to instantiate the thread object is required to extend some other class.

Extending Thread Class

The procedure for creating threads based on extending the Thread is as follows:
1. A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread.
2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call.
3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running.
Below is a program that illustrates instantiation and running of threads by extending the Thread class instead of implementing the Runnable interface. To start the thread you need to invoke the start() method on your object.
class XThread extends Thread {
 
        XThread() {
        }
        XThread(String threadName) {
               super(threadName); // Initialize thread.
               System.out.println(this);
               start();
        }
        public void run() {
               //Display info about this particular thread
               System.out.println(Thread.currentThread().getName());
        }
}
 
public class ThreadExample {
 
        public static void main(String[] args) {
               Thread thread1 = new Thread(new XThread(), "thread1");
               Thread thread2 = new Thread(new XThread(), "thread2");
               //          The below 2 threads are assigned default names
               Thread thread3 = new XThread();
               Thread thread4 = new XThread();
               Thread thread5 = new XThread("thread5");
               //Start the threads
               thread1.start();
               thread2.start();
               thread3.start();
               thread4.start();
               try {
        //The sleep() method is invoked on the main thread to cause a one second delay.
                       Thread.currentThread().sleep(1000);
               } catch (InterruptedException e) {
               }
               //Display info about the main thread
               System.out.println(Thread.currentThread());
        }
}
Output
Thread[thread5,5,main]
thread1
thread5
thread2
Thread-3
Thread-2
Thread[main,5,main]
Download Java Thread Program Example
When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class:
  • Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interface
    has this option.
  • A class might only be interested in being runnable, and therefore, inheriting the full overhead of the Thread class would be excessive.
An example of an anonymous class below shows how to create a thread and start it:
( new Thread() {
public void run() {
for(;;) System.out.println(”Stop the world!”);
}
}
).start();

Thread Synchronization

With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time.
In non synchronized multithreaded application, it is possible for one thread to modify a shared object while
another thread is in the process of using or updating the object’s value. Synchronization prevents such type
of data corruption which may otherwise lead to dirty reads and significant errors.
Generally critical sections of the code are usually marked with synchronized keyword.
Examples of using Thread Synchronization is in “The Producer/Consumer Model”.
Locks are used to synchronize access to a shared resource. A lock can be associated with a shared resource.
Threads gain access to a shared resource by first acquiring the lock associated with the object/block of code.
At any given time, at most only one thread can hold the lock and thereby have access to the shared resource.
A lock thus implements mutual exclusion.
The object lock mechanism enforces the following rules of synchronization:
·  A thread must acquire the object lock associated with a shared resource, before it can enter the shared
resource. The runtime system ensures that no other thread can enter a shared resource if another thread
already holds the object lock associated with the shared resource. If a thread cannot immediately acquire
the object lock, it is blocked, that is, it must wait for the lock to become available.
·  When a thread exits a shared resource, the runtime system ensures that the object lock is also relinquished.
If another thread is waiting for this object lock, it can proceed to acquire the lock in order to gain access
to the shared resource.
Classes also have a class-specific lock that is analogous to the object lock. Such a lock is actually a
lock on the java.lang.Class object associated with the class. Given a class A, the reference A.class
denotes this unique Class object. The class lock can be used in much the same way as an object lock to
implement mutual exclusion.
There can be 2 ways through which synchronized can be implemented in Java:
  • synchronized methods
  • synchronized blocks
Synchronized statements are same as synchronized methods. A synchronized statement can only be
executed after a thread has acquired the lock on the object/class referenced in the synchronized statement.

Synchronized Methods

Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class. .If the lock is already held by another thread, the calling thread waits. A thread relinquishes the lock simply by returning from the synchronized method, allowing the next thread waiting for this lock to proceed. Synchronized methods are useful in situations where methods can manipulate the state of an object in ways that can corrupt the state if executed concurrently. This is called a race condition. It occurs when two or more threads simultaneously update the same value, and as a consequence, leave the value in an undefined or inconsistent state. While a thread is inside a synchronized method of an object, all other threads that wish to execute this synchronized method or any other synchronized method of the object will have to wait until it gets the lock. This restriction does not apply to the thread that already has the lock and is executing a synchronized method of the object. Such a method can invoke other synchronized methods of the object without being blocked. The non-synchronized methods of the object can of course be called at any time by any thread.
Below is an example shows how synchronized methods and object locks are used to coordinate access to a common object by multiple threads. If the ’synchronized’ keyword is removed, the message is displayed in random fashion.
public class SyncMethodsExample extends Thread {
 
        static String[] msg = { "Beginner", "java", "tutorial,", ".,", "com",
                       "is", "the", "best" };
        public SyncMethodsExample(String id) {
               super(id);
        }
        public static void main(String[] args) {
               SyncMethodsExample thread1 = new SyncMethodsExample("thread1: ");
               SyncMethodsExample thread2 = new SyncMethodsExample("thread2: ");
               thread1.start();
               thread2.start();
               boolean t1IsAlive = true;
               boolean t2IsAlive = true;
               do {
                       if (t1IsAlive && !thread1.isAlive()) {
                               t1IsAlive = false;
                               System.out.println("t1 is dead.");
                       }
                       if (t2IsAlive && !thread2.isAlive()) {
                               t2IsAlive = false;
                               System.out.println("t2 is dead.");
                       }
               } while (t1IsAlive || t2IsAlive);
        }
        void randomWait() {
               try {
                       Thread.currentThread().sleep((long) (3000 * Math.random()));
               } catch (InterruptedException e) {
                       System.out.println("Interrupted!");
               }
        }
        public synchronized void run() {
               SynchronizedOutput.displayList(getName(), msg);
        }
}
 
class SynchronizedOutput {
 
        // if the 'synchronized' keyword is removed, the message
        // is displayed in random fashion
        public static synchronized void displayList(String name, String list[]) {
               for (int i = 0; i < list.length; i++) {
                       SyncMethodsExample t = (SyncMethodsExample) Thread
                                      .currentThread();
                       t.randomWait();
                       System.out.println(name + list[i]);
               }
        }
}
Output
thread1: Beginner
thread1: java
thread1: tutorial,
thread1: .,
thread1: com
thread1: is
thread1: the
thread1: best
t1 is dead.
thread2: Beginner
thread2: java
thread2: tutorial,
thread2: .,
thread2: com
thread2: is
thread2: the
thread2: best
t2 is dead.
Download Synchronized Methods Thread Program Example
Class Locks

Synchronized Blocks

Static methods synchronize on the class lock. Acquiring and relinquishing a class lock by a thread in order to execute a static synchronized method, proceeds analogous to that of an object lock for a synchronized instance method. A thread acquires the class lock before it can proceed with the execution of any static synchronized method in the class, blocking other threads wishing to execute any such methods in the same class. This, of course, does not apply to static, non-synchronized methods, which can be invoked at any time. Synchronization of static methods in a class is independent from the synchronization of instance methods on objects of the class. A subclass decides whether the new definition of an inherited synchronized method will remain synchronized in the subclass.The synchronized block allows execution of arbitrary code to be synchronized on the lock of an arbitrary object.
The general form of the synchronized block is as follows:
synchronized (<object reference expression>) {
<code block>
}
A compile-time error occurs if the expression produces a value of any primitive type. If execution of the block completes normally, then the lock is released. If execution of the block completes abruptly, then the lock is released.
A thread can hold more than one lock at a time. Synchronized statements can be nested. Synchronized statements with identical expressions can be nested. The expression must evaluate to a non-null reference value, otherwise, a NullPointerException is thrown.
The code block is usually related to the object on which the synchronization is being done. This is the case with synchronized methods, where the execution of the method is synchronized on the lock of the current object:
public Object method() {
synchronized (this) { // Synchronized block on current object
// method block
}
}
Once a thread has entered the code block after acquiring the lock on the specified object, no other thread will be able to execute the code block, or any other code requiring the same object lock, until the lock is relinquished. This happens when the execution of the code block completes normally or an uncaught exception is thrown.
Object specification in the synchronized statement is mandatory. A class can choose to synchronize the execution of a part of a method, by using the this reference and putting the relevant part of the method in the synchronized block. The braces of the block cannot be left out, even if the code block has just one statement.
class SmartClient {
BankAccount account;
// …
public void updateTransaction() {
synchronized (account) { // (1) synchronized block
account.update(); // (2)
}
}
}
In the previous example, the code at (2) in the synchronized block at (1) is synchronized on the BankAccount object. If several threads were to concurrently execute the method updateTransaction() on an object of SmartClient, the statement at (2) would be executed by one thread at a time, only after synchronizing on the BankAccount object associated with this particular instance of SmartClient.
Inner classes can access data in their enclosing context. An inner object might need to synchronize on its associated outer object, in order to ensure integrity of data in the latter. This is illustrated in the following code where the synchronized block at (5) uses the special form of the this reference to synchronize on the outer object associated with an object of the inner class. This setup ensures that a thread executing the method setPi() in an inner object can only access the private double field myPi at (2) in the synchronized block at (5), by first acquiring the lock on the associated outer object. If another thread has the lock of the associated outer object, the thread in the inner object has to wait for the lock to be relinquished before it can proceed with the execution of the synchronized block at (5). However, synchronizing on an inner object and on its associated outer object are independent of each other, unless enforced explicitly, as in the following code:
class Outer { // (1) Top-level Class
private double myPi; // (2)
protected class Inner { // (3) Non-static member Class
public void setPi() { // (4)
synchronized(Outer.this) { // (5) Synchronized block on outer object
myPi = Math.PI; // (6)
}
}
}
}
Below example shows how synchronized block and object locks are used to coordinate access to shared objects by multiple threads.
public class SyncBlockExample extends Thread {
 
        static String[] msg = { "Beginner", "java", "tutorial,", ".,", "com",
                       "is", "the", "best" };
        public SyncBlockExample(String id) {
               super(id);
        }
        public static void main(String[] args) {
               SyncBlockExample thread1 = new SyncBlockExample("thread1: ");
               SyncBlockExample thread2 = new SyncBlockExample("thread2: ");
               thread1.start();
               thread2.start();
               boolean t1IsAlive = true;
               boolean t2IsAlive = true;
               do {
                       if (t1IsAlive && !thread1.isAlive()) {
                               t1IsAlive = false;
                               System.out.println("t1 is dead.");
                       }
                       if (t2IsAlive && !thread2.isAlive()) {
                               t2IsAlive = false;
                               System.out.println("t2 is dead.");
                       }
               } while (t1IsAlive || t2IsAlive);
        }
        void randomWait() {
               try {
                       Thread.currentThread().sleep((long) (3000 * Math.random()));
               } catch (InterruptedException e) {
                       System.out.println("Interrupted!");
               }
        }
        public void run() {
               synchronized (System.out) {
                       for (int i = 0; i < msg.length; i++) {
                               randomWait();
                               System.out.println(getName() + msg[i]);
                       }
               }
        }
}
Output
thread1: Beginner
thread1: java
thread1: tutorial,
thread1: .,
thread1: com
thread1: is
thread1: the
thread1: best
t1 is dead.
thread2: Beginner
thread2: java
thread2: tutorial,
thread2: .,
thread2: com
thread2: is
thread2: the
thread2: best
t2 is dead.
Synchronized blocks can also be specified on a class lock:
synchronized (<class name>.class) { <code block> }
The block synchronizes on the lock of the object denoted by the reference <class name>.class. A static synchronized method
classAction() in class A is equivalent to the following declaration:
static void classAction() {
synchronized (A.class) { // Synchronized block on class A
// …
}
}
In summary, a thread can hold a lock on an object
  • by executing a synchronized instance method of the object
  • by executing the body of a synchronized block that synchronizes on the object
  • by executing a synchronized static method of a class

Thread States

A Java thread is always in one of several states which could be running, sleeping, dead, etc.
A thread can be in any of the following states:
  • New Thread state (Ready-to-run state)
  • Runnable state (Running state)
  • Not Runnable state
  • Dead state

New Thread

A thread is in this state when the instantiation of a Thread object creates a new thread but does not
start it running. A thread starts life in the Ready-to-run state. You can call only the start() or stop()
methods when the thread is in this state. Calling any method besides start() or stop() causes an
IllegalThreadStateException.

Runnable

When the start() method is invoked on a New Thread() it gets to the runnable state or running state by
calling the run() method. A Runnable thread may actually be running, or may be awaiting its turn to run.

Not Runnable

A thread becomes Not Runnable when one of the following four events occurs:
  • When sleep() method is invoked and it sleeps for a specified amount of time
  • When suspend() method is invoked
  • When the wait() method is invoked and the thread waits for notification of a free resource or waits for
    the completion of another thread or waits to acquire a lock of an object.
  • The thread is blocking on I/O and waits for its completion
Example: Thread.currentThread().sleep(1000);
Note: Thread.currentThread() may return an output like Thread[threadA,5,main]
The output shown in bold describes
  • the name of the thread,
  • the priority of the thread, and
  • the name of the group to which it belongs.
Here, the run() method put itself to sleep for one second and becomes Not Runnable during that period.
A thread can be awakened abruptly by invoking the interrupt() method on the sleeping thread object or at the end of the period of time for sleep is over. Whether or not it will actually start running depends on its priority and the availability of the CPU.
Hence I hereby list the scenarios below to describe how a thread switches form a non runnable to a runnable state:
·  If a thread has been put to sleep, then the specified number of milliseconds must elapse (or it must be interrupted).
·  If a thread has been suspended, then its resume() method must be invoked
·  If a thread is waiting on a condition variable, whatever object owns the variable must relinquish it by calling
either notify() or notifyAll().
·  If a thread is blocked on I/O, then the I/O must complete.

Dead State

A thread enters this state when the run() method has finished executing or when the stop() method is invoked. Once in this state, the thread cannot ever run again.

Thread Priority

In Java we can specify the priority of each thread relative to other threads. Those threads having higher
priority get greater access to available resources then lower priority threads. A Java thread inherits its priority
from the thread that created it. Heavy reliance on thread priorities for the behavior of a program can make the
program non portable across platforms, as thread scheduling is host platform–dependent.
You can modify a thread’s priority at any time after its creation using the setPriority() method and retrieve
the thread priority value using getPriority() method.
The following static final integer constants are defined in the Thread class:
  • MIN_PRIORITY (0) Lowest Priority
  • NORM_PRIORITY (5) Default Priority
  • MAX_PRIORITY (10) Highest Priority
The priority of an individual thread can be set to any integer value between and including the above defined constants.
When two or more threads are ready to be executed and system resource becomes available to execute a thread, the runtime system (the thread scheduler) chooses the Runnable thread with the highest priority for execution.
“If two threads of the same priority are waiting for the CPU, the thread scheduler chooses one of them to run in a > round-robin fashion. The chosen thread will run until one of the following conditions is true:
  • a higher priority thread becomes Runnable. (Pre-emptive scheduling)
  • it yields, or its run() method exits
  • on systems that support time-slicing, its time allotment has expired

Thread Scheduler

Schedulers in JVM implementations usually employ one of the two following strategies:
Preemptive scheduling
If a thread with a higher priority than all other Runnable threads becomes Runnable, the scheduler will
preempt the running thread (is moved to the runnable state) and choose the new higher priority thread for execution.
Time-Slicing or Round-Robin scheduling
A running thread is allowed to execute for a fixed length of time (a time slot it’s assigned to), after which it moves to the Ready-to-run state (runnable) to await its turn to run again.
A thread scheduler is implementation and platform-dependent; therefore, how threads will be scheduled is unpredictable across different platforms.

Yielding

A call to the static method yield(), defined in the Thread class, will cause the current thread in the Running state to move to the Runnable state, thus relinquishing the CPU. The thread is then at the mercy of the thread scheduler as to when it will run again. If there are no threads waiting in the Ready-to-run state, this thread continues execution. If there are other threads in the Ready-to-run state, their priorities determine which thread gets to execute. The yield() method gives other threads of the same priority a chance to run. If there are no equal priority threads in the “Runnable” state, then the yield is ignored.

Sleeping and Waking Up

The thread class contains a static method named sleep() that causes the currently running thread to pause its execution and transit to the Sleeping state. The method does not relinquish any lock that the thread might have. The thread will sleep for at least the time specified in its argument, before entering the runnable state where it takes its turn to run again. If a thread is interrupted while sleeping, it will throw an InterruptedException when it awakes and gets to execute. The Thread class has several overloaded versions of the sleep() method.

Waiting and Notifying

Waiting and notifying provide means of thread inter-communication that synchronizes on the same object. The threads execute wait() and notify() (or notifyAll()) methods on the shared object for this purpose. The notifyAll(), notify() and wait() are methods of the Object class. These methods can be invoked only from within a synchronized context (synchronized method or synchronized block), otherwise, the call will result in an IllegalMonitorStateException. The notifyAll() method wakes up all the threads waiting on the resource. In this situation, the awakened threads compete for the resource. One thread gets the resource and the others go back to waiting.
wait() method signatures
final void wait(long timeout) throws InterruptedException
final void wait(long timeout, int nanos) throws InterruptedException
final void wait() throws InterruptedException
The wait() call can specify the time the thread should wait before being timed out. An another thread can invoke an interrupt() method on a waiting thread resulting in an InterruptedException. This is a checked exception and hence the code with the wait() method must be enclosed within a try catch block.
notify() method signatures
final void notify()
final void notifyAll()
A thread usually calls the wait() method on the object whose lock it holds because a condition for its continued execution was not met. The thread leaves the Running state and transits to the Waiting-for-notification state. There it waits for this condition to occur. The thread relinquishes ownership of the object lock. The releasing of the lock of the shared object by the thread allows other threads to run and execute synchronized code on the same object after acquiring its lock.
The wait() method causes the current thread to wait until another thread notifies it of a condition change.
A thread in the Waiting-for-notification state can be awakened by the occurrence of any one of these three incidents:
1. Another thread invokes the notify() method on the object of the waiting thread, and the waiting thread is selected as the thread to be awakened.
2. The waiting thread times out.
3. Another thread interrupts the waiting thread.
Notify
Invoking the notify() method on an object wakes up a single thread that is waiting on the lock of this object.
A call to the notify() method has no consequences if there are no threads in the wait set of the object.
The notifyAll() method wakes up all threads in the wait set of the shared object.
Below program shows three threads, manipulating the same stack. Two of them are pushing elements on the stack, while the third one is popping elements off the stack. This example illustrates how a thread waiting as a result of calling the wait() method on an object, is notified by another thread calling the notify() method on the same object
class StackClass {
 
        private Object[] stackArray;
        private volatile int topOfStack;
        StackClass(int capacity) {
               stackArray = new Object[capacity];
               topOfStack = -1;
        }
        public synchronized Object pop() {
               System.out.println(Thread.currentThread() + ": popping");
               while (isEmpty()) {
                       try {
                               System.out.println(Thread.currentThread()
                                              + ": waiting to pop");
                               wait();
                       } catch (InterruptedException e) {
                               e.printStackTrace();
                       }
               }
               Object obj = stackArray[topOfStack];
               stackArray[topOfStack--] = null;
               System.out.println(Thread.currentThread()
                               + ": notifying after pop");
               notify();
               return obj;
        }
        public synchronized void push(Object element) {
               System.out.println(Thread.currentThread() + ": pushing");
               while (isFull()) {
                       try {
                               System.out.println(Thread.currentThread()
                                              + ": waiting to push");
                               wait();
                       } catch (InterruptedException e) {
                               e.printStackTrace();
                       }
               }
               stackArray[++topOfStack] = element;
               System.out.println(Thread.currentThread()
                               + ": notifying after push");
               notify();
        }
        public boolean isFull() {
               return topOfStack >= stackArray.length - 1;
        }
        public boolean isEmpty() {
               return topOfStack < 0;
        }
}
 
abstract class StackUser extends Thread {
 
        protected StackClass stack;
        StackUser(String threadName, StackClass stack) {
               super(threadName);
               this.stack = stack;
               System.out.println(this);
               setDaemon(true);
               start();
        }
}
 
class StackPopper extends StackUser { // Stack Popper
 
        StackPopper(String threadName, StackClass stack) {
               super(threadName, stack);
        }
        public void run() {
               while (true) {
                       stack.pop();
               }
        }
}
 
class StackPusher extends StackUser { // Stack Pusher
 
        StackPusher(String threadName, StackClass stack) {
               super(threadName, stack);
        }
        public void run() {
               while (true) {
                       stack.push(new Integer(1));
               }
        }
}
 
public class WaitAndNotifyExample {
 
        public static void main(String[] args) {
               StackClass stack = new StackClass(5);
               new StackPusher("One", stack);
               new StackPusher("Two", stack);
               new StackPopper("Three", stack);
               System.out.println("Main Thread sleeping.");
               try {
                       Thread.sleep(500);
               } catch (InterruptedException e) {
                       e.printStackTrace();
               }
               System.out.println("Exit from Main Thread.");
        }
}
Download Wait Notify methods Thread Program Example
The field topOfStack in class StackClass is declared volatile, so that read and write operations on this variable will access the master value of this variable, and not any copies, during runtime.
Since the threads manipulate the same stack object and the push() and pop() methods in the class StackClassare synchronized, it means that the threads synchronize on the same object.
How the program uses wait() and notify() for inter thread communication.
(1) The synchronized pop() method - When a thread executing this method on the StackClass object finds that the stack is empty, it invokes the wait() method in order to wait for some other thread to fill the stack by using the synchronized push. Once an other thread makes a push, it invokes the notify method.
(2)The synchronized push() method - When a thread executing this method on the StackClass object finds that the stack is full, i t invokes the wait() method to await some other thread to remove an element to provide space for the newly to be pushed element.
Once an other thread makes a pop, it invokes the notify method.

Joining

A thread invokes the join() method on another thread in order to wait for the other thread to complete its execution.
Consider a thread t1 invokes the method join() on a thread t2. The join() call has no effect if thread t2 has already completed. If thread t2 is still alive, then thread t1 transits to the Blocked-for-join-completion state.
Below is a program showing how threads invoke the overloaded thread join method.
public class ThreadJoinDemo {
 
        public static void main(String[] args) {
               Thread t1 = new Thread("T1");
               Thread t2 = new Thread("T2");
               try {
                       System.out.println("Wait for the child threads to finish.");
                       t1.join();
                       if (!t1.isAlive())
                               System.out.println("Thread T1 is not alive.");
                       t2.join();
                       if (!t2.isAlive())
                               System.out.println("Thread T2 is not alive.");
               } catch (InterruptedException e) {
                       System.out.println("Main Thread interrupted.");
               }
               System.out.println("Exit from Main Thread.");
        }
}
Download Java Thread Join Method Program Example
Output
Wait for the child threads to finish.
Thread T1 is not alive.
Thread T2 is not alive.
Exit from Main Thread.

Deadlock

There are situations when programs become deadlocked when each thread is waiting on a resource that cannot become available. The simplest form of deadlock is when two threads are each waiting on a resource that is locked by the other thread. Since each thread is waiting for the other thread to relinquish a lock, they both remain waiting forever in the Blocked-for-lock-acquisition state. The threads are said to be deadlocked.
Thread t1 at tries to synchronize first on string o1 and then on string o2. The thread t2 does the opposite. It synchronizes first on string o2 then on string o1. Hence a deadlock can occur as explained above.
Below is a program that illustrates deadlocks in multithreading applications
public class DeadLockExample {
 
        String o1 = "Lock ";
        String o2 = "Step ";
        Thread t1 = (new Thread("Printer1") {
 
               public void run() {
                       while (true) {
                               synchronized (o1) {
                                      synchronized (o2) {
                                              System.out.println(o1 + o2);
                                      }
                               }
                       }
               }
        });
        Thread t2 = (new Thread("Printer2") {
 
               public void run() {
                       while (true) {
                               synchronized (o2) {
                                      synchronized (o1) {
                                              System.out.println(o2 + o1);
                                      }
                               }
                       }
               }
        });
        public static void main(String[] args) {
               DeadLockExample dLock = new DeadLockExample();
               dLock.t1.start();
               dLock.t2.start();
        }
}
Download Java Thread deadlock Program Example
Note: The following methods namely join, sleep and wait name the InterruptedException in its throws clause and can have a timeout argument as a parameter. The following methods namely wait, notify and notifyAll should only be called by a thread that holds the lock of the instance on which the method is invoked. The Thread.start method causes a new thread to get ready to run at the discretion of the thread scheduler. The Runnable interface declares the run method. The Thread class implements the Runnable interface. Some implementations of the Thread.yield method will not yield to a thread of lower priority. A program will terminate only when all user threads stop running. A thread inherits its daemon status from the thread that created it
Java Collection Framework:
A collection represents a group of objects, known as its elements. This framework is provided in the java.util package. Objects can be stored, retrieved, and manipulated as elements of collections. Collection is a Java Interface. Collections can be used in various scenarios like Storing phone numbers, Employee names database etc. They are basically used to group multiple elements into a single unit. Some collections allow duplicate elements while others do not. Some collections are ordered and others are not.
A Collections Framework mainly contains the following 3 parts
A Collections Framework is defined by a set of interfaces, concrete class implementations for most of the interfaces and a set of standard utility methods and algorithms. In addition, the framework also provides several abstract implementations, which are designed to make it easier for you to create new and different implementations for handling collections of data.
Java Exceptions:
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.
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) {
<font size=-1>
 
      System.out.println("Computing Division.");
      int average  = totalSum/totalNumber;
        System.out.println("Average : "+ average);
    }
}
Download DivideException.java
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

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.

Checked and Unchecked Exceptions

Checked exceptions are subclass’s of Exception excluding class RuntimeException and its subclasses. Checked Exceptions forces programmers to deal with the exception that may be thrown. Example: Arithmetic exception. When a checked exception occurs in a method, the method must either catch the exception and take the appropriate action, or pass the exception on to its caller
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. Unchecked exceptions , however, the compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause. In fact, the programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBounds Exception. They are either irrecoverable (Errors) and the program should not attempt to deal with them, or they are logical programming errors. (Runtime Exceptions). Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
Exception Statement Syntax
Exceptions are handled using a try-catch-finally construct, which has the Syntax
try {
<code>
} catch (<exception type1> <parameter1>) { // 0 or more
<statements>
}
} finally { // finally block
<statements>
}
try Block
The java code that you think may produce an exception is placed within a try block for a
suitable catch block to handle the error.
If no exception occurs the execution proceeds with the finally block else it will look for the
matching catch block to handle the error. Again if the matching catch handler is not found execution
proceeds with the finally block and the default exception handler throws an exception.. If an exception is
generated within the try block, the remaining statements in the try block are not executed.
catch Block
Exceptions thrown during execution of the try block can be caught and handled in a catch block. On exit from a catch block, normal execution continues and the finally block is executed
(Though the catch block throws an exception).
finally Block
A finally block is always executed, regardless of the cause of exit from the try block, or whether any catch block was executed. Generally finally block is used for freeing resources, cleaning up, closing connections etc. If the finally clock executes a control transfer statement such as a return or a break statement, then this control
statement determines how the execution will proceed regardless of any return or control statement present in the try or catch.
The following program illustrates the scenario.
try {
    <code>
} catch (<exception type1> <parameter1>) { // 0 or more
    <statements>
 
}
} finally {                               // finally block
    <statements>
}

Download
DivideException2.java
Output
Computing Division.
Exception : / by zero
Finally Block Executes. Exception Occurred
result : -1
Below is a program showing the Normal Execution of the Program.
Please note that no NullPointerException is generated as was expected by most people
public class DivideException2 {
 
    public static void main(String[] args) {
      int result  = division(100,0);        // Line 2
        System.out.println("result : "+result);
    }
 
    public static int division(int totalSum, int totalNumber) {
      int quotient = -1;
      System.out.println("Computing Division.");
      try{
            quotient  = totalSum/totalNumber;
 
      }
      catch(Exception e){
            System.out.println("Exception : "+ e.getMessage());
      }
      finally{
            if(quotient != -1){
                  System.out.println("Finally Block Executes");
                  System.out.println("Result : "+ quotient);
            }else{
                  System.out.println("Finally Block Executes. Exception Occurred");
                  return quotient;
            }
 
      }
      return quotient;
    }
}
Output
null (And not NullPointerException)

Rules for try, catch and finally Blocks

1. For each try block there can be zero or more catch blocks, but only one finally block. 
 
2. The catch blocks and finally block must always appear in conjunction with a try block.
 
3. A try block must be followed by either at least one catch block or one finally block.
 
4. The order exception handlers in the catch block must be from the most specific exception 
Java exception handling mechanism enables you to catch exceptions in java using try, catch, finally block. be An exception consists of a block of code called a try block, a block of code called a catch block, and the finally block. Let’s examine each of these in detail.
public class DivideException1 {
 
    public static void main(String[] args) {
      division(100,0);        // Line 2
        System.out.println("Main Program Terminating");
    }
 
    public static void division(int totalSum, int totalNumber) {
      int quotient = -1;
      System.out.println("Computing Division.");
      try{
            quotient  = totalSum/totalNumber;
            System.out.println("Result is : "+quotient);
      }
      catch(Exception e){
            System.out.println("Exception : "+ e.getMessage());
      }
      finally{
            if(quotient != -1){
                  System.out.println("Finally Block Executes");
                  System.out.println("Result : "+ quotient);
            }else{
                  System.out.println("Finally Block Executes. Exception Occurred");
            }
 
      }
    }
}
Download DivideException1.javaOutput
Output
Computing Division.
Exception : / by zero
Finally Block Executes. Exception Occurred
Main Program Terminating
As shown above when the divide by zero calculation is attempted, an ArithmeticException is thrown. and program execution is transferred to the catch statement. Because the exception is thrown from the try block, the remaining statements of the try block
are skipped. The finally block executes.
Defining new EXCEPTIONS!!
We can have our own custom Exception handler to deal with special exception conditions instead of using existing exception classes. Custom exceptions usually extend the Exception class directly or any subclass of Exception (making it checked).
The super() call can be used to set a detail message in the throwable. Below is an example that shows the use of Custom exception’s along with how the throw and throws clause are used.
class BadTemperature extends Exception{
      BadTemperature( String reason ){
            super ( reason );
    }
}
 
class TooHot extends BadTemperature{
 
      TooHot(){
            super ("Default messaeg : Hot");
    }
 
      TooHot(String message){
            super (message);
    }
}
 
class TooCold extends BadTemperature{ 
 
      TooCold(){
            super ("Default messaeg : Cold");
    }
 
      TooCold(String message){
            super (message);
    }
}
 
class TempertureObject{ 
 
      int temperature;
 
    TempertureObject( int temp ) {
      temperature = temp;
    }
 
    void test() throws TooHot, TooCold {
      if ( temperature < 70 ) throw new TooCold("Very Cold");
        if ( temperature > 80 ) throw new TooHot("Very Hot");
    }
}
 
public class ExceptionExample1{   
 
      private static void temperatureReport( TempertureObject batch ){
            try{   batch.test();
            System.out.println( "Perfect Temperature" );
        }
        catch ( BadTemperature bt ){
            System.out.println( bt.getMessage( ) );
        }
    }
 
    public static void main( String[] args ){
      temperatureReport( new TempertureObject( 100 ) );
        temperatureReport( new TempertureObject( 50 ) );
        temperatureReport( new TempertureObject( 75 ) );
    }
}
Download ExceptionExample.javaOutput
Output
Very Hot
Very Cold
Perfect Temperature

throw, throws statement

A program can explicitly throw an exception using the throw statement besides the implicit exception thrown.
The general format of the throw statement is as follows:
throw <exception reference>;
The Exception reference must be of type Throwable class or one of its subclasses. A detail message can be passed to the constructor when the exception object is created.
throw new TemperatureException(”Too hot”);
A throws clause can be used in the method prototype.
Method() throws <ExceptionType1>,…, <ExceptionTypen> {
}
Each <ExceptionTypei> can be a checked or unchecked or sometimes even a custom Exception. The exception type specified in the throws clause in the method prototype can be a super class type of the actual exceptions thrown. Also an overriding method cannot allow more checked exceptions in its throws clause than the inherited method does.
When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a matching catch block that can handle the exception. Any associated finally block of a try block encountered along the search path is executed. If no handler is found, then the exception is dealt with by the default exception handler at the top level. If a handler is found, execution resumes with the code in its catch block. Below is an example to show the use of a throws and a throw statement.
public class DivideException3 {
 
    public static void main(String[] args) {
      try{
            int result  = division(100,10);
            result  = division(100,0);
            System.out.println("result : "+result);
      }
        catch(ArithmeticException e){
            System.out.println("Exception : "+ e.getMessage());
      }
    }
 
    public static int division(int totalSum, int totalNumber) throws ArithmeticException {
      int quotient = -1;
      System.out.println("Computing Division.");
      try{
            if(totalNumber == 0){
                  throw new ArithmeticException("Division attempt by 0");
            }
            quotient  = totalSum/totalNumber;
 
      }
      finally{
            if(quotient != -1){
                  System.out.println("Finally Block Executes");
                  System.out.println("Result : "+ quotient);
            }else{
                  System.out.println("Finally Block Executes. Exception Occurred");
            }
 
      }
      return quotient;
    }
}
Download DivideException3.javaOutput
Output
Computing Division.
Finally Block Executes
Result : 10
Computing Division.
Finally Block Executes. Exception Occurred
Exception : Division attempt by 0

Using break and return with Exceptions

This example demonstrates the use of the break, continue and return statements with exceptions. Note that the finally block is executed always except when the return statement is executed.
public class ExceptionExample6 {
 
      public static void main(String[] args) {
 
            int x = 10, y = 2;
            int counter = 0;
            boolean flag = true;
            while (flag) {
            start:
                  try {
                        if ( y > 1 )
                               break start;
                        if ( y < 0 )
                               return;
                        x = x / y;
                        System.out.println ( "x : " + x + " y : "+y );
                  }
                  catch ( Exception e ) {
                        System.out.println ( e.getMessage() );
                  }
                  finally {
                        ++counter;
                        System.out.println ( "Counter : " + counter );
                  }
                  --y;
            }
      }
}
Download ExceptionExample6.javaOutput
Output
Counter : 1
x : 10 y : 1
Counter : 2
/ by zero
Counter : 3
Counter : 4

Handling Multiple Exceptions

It should be known by now that we can have multiple catch blocks for a particular try block to handle many different kind of exceptions that can be generated. Below is a program to demonstrate the use of multiple catch blocks.
import java.io.DataInputStream;
import java.io.IOException;
 
import javax.swing.JOptionPane;
public class ExceptionExample7{
    static int numerator, denominator;
 
    public ExceptionExample7( int t, int b ){
      numerator = t;
      denominator = b;
    }
 
    public int divide( ) throws ArithmeticException{
      return numerator/denominator;
    }
 
    public static void main( String args[] ){
 
      String num, denom;
 
      num = JOptionPane.showInputDialog(null, "Enter the Numerator");
      denom = JOptionPane.showInputDialog(null, "Enter the Denominator");
 
            try{
                numerator = Integer.parseInt( num );
                denominator = Integer.parseInt( denom );
            }
            catch ( NumberFormatException nfe ){
                System.out.println( "One of the inputs is not an integer" );
                return;
            }
        catch ( Exception e ){
                System.out.println( "Exception: " + e.getMessage( ) );
                return;
        }
 
            ExceptionExample7 d = new ExceptionExample7( numerator, denominator );
            try{
                double result = d.divide( );
                JOptionPane.showMessageDialog(null, "Result : " + result);
            }
            catch ( ArithmeticException ae ){
                  System.out.println( "You can't divide by zero" );
            }
            finally{
                  System.out.println( "Finally Block is always Executed" );
          }
    }
}
Download ExceptionExample7.java
Java Singletone Design Patterns:
Java has several design patterns Singleton Pattern being the most commonly used. Java Singleton pattern belongs to the family of design patterns, that govern the instantiation process. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM.
The class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object.
One such scenario where it might prove useful is when we develop the help Module in a project. Java Help is an extensible, platform-independent help system that enables authors and developers to incorporate online help into applications.
Singletons can be used to create a Connection Pool. If programmers create a new connection object in every class that requires it, then its clear waste of resources. In this scenario by using a singleton connection class we can maintain a single connection object which can be used throughout the application.
Implementing Singleton Pattern
To implement this design pattern we need to consider the following 4 steps:
<br /><font size=-1>
Step 1: Provide a default Private constructor
public class SingletonObjectDemo {

        // Note that the constructor is private
        private SingletonObjectDemo() {
               // Optional Code
        }
}
Step 2: Create a Method for getting the reference to the Singleton Object
public class SingletonObjectDemo {

        private static SingletonObject singletonObject;
        // Note that the constructor is private
        private SingletonObjectDemo() {
               // Optional Code
        }
        public static SingletonObjectDemo getSingletonObject() {
               if (singletonObject == null) {
                       singletonObject = new SingletonObjectDemo();
               }
               return singletonObject;
        }
}
We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.
Step 3: Make the Access method Synchronized to prevent Thread Problems.
public static synchronized SingletonObjectDemo getSingletonObject()
It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration
Step 4: Override the Object clone method to prevent cloning

We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown below
SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();
This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.
class SingletonClass {

        private static SingletonClass singletonObject;
 A private Constructor prevents any other class from instantiating. */
        private SingletonClass() {
               //      Optional Code
        }
        public static synchronized SingletonClass getSingletonObject() {
               if (singletonObject == null) {
                       singletonObject = new SingletonClass();
               }
               return singletonObject;
        }
        public Object clone() throws CloneNotSupportedException {
               throw new CloneNotSupportedException();
        }
}

public class SingletonObjectDemo {

        public static void main(String args[]) {
               //             SingletonClass obj = new SingletonClass();
                //Compilation error not allowed
               SingletonClass obj = SingletonClass.getSingletonObject();
               // Your Business Logic
               System.out.println("Singleton object obtained");
        }
}

Download
SingletonObjectDemo.java
Another approach
We don’t need to do a lazy initialization of the instance object or to check for null in the get method. We can also make the singleton class final to avoid sub classing that may cause other problems.
public class SingletonClass {

        private static SingletonClass ourInstance = new SingletonClass();
        public static SingletonClass getInstance() {
               return singletonObj;
        }
        private SingletonClass() {
        }
}
In Summary, the job of the Singleton class is to enforce the existence of a maximum of one object of the same type at any given time. Depending on your implementation, your class and all of its data might be garbage collected. Hence we must ensure that at any point there must be a live reference to the class when the application is running.
http://www.javabeginner.com/images/design_patterns.gif
http://www.javabeginner.com/images/singletonuml.gif

Applet versus Application

Applets as previously described, are the small programs while applications are larger programs. Applets don't have the main method while in an application execution starts with the main method. Applets can run in our browser's window or in an appletviewer. To run the applet in an appletviewer will be an advantage for debugging. Applets are designed for the client site programming purpose while the applications don't have such type of criteria.
Applet are the powerful tools because it covers half of the java language picture. Java applets are the best way of creating the programs in java. There are a less number of java programmers that have the hands on experience on java applications. This is not the deficiency of java applications but the global utilization of internet. It doesn't mean that the java applications don't have the place. Both (Applets and the java applications) have the same importance at their own places. Applications are also the platform independent as well as byte oriented just like the applets.
Applets are designed just for handling the client site problems. while the java applications are designed to work with the client as well as server. Applications are designed to exists in a secure area. while the applets are typically used.
Applications and applets have much of the similarity such as both have most of the same features and share the same resources. Applets are created by extending the java.applet.Applet class while the java applications start execution from the main method. Applications are not too small to embed into a html page so that the user can view the application in your browser. On the other hand applet have the accessibility criteria of the resources. The key feature is that while they have so many differences but both can perform the same purpose.
Review of Java Applets: You have previously learned about the java applets. To create an applet just create a class that extends the java.applet.Applet class and inherit all the features available in the parent class. The following programs make all the things clear.
import java.awt.*;
import java.applet.*;

class Myclass extends Applet {
public void init() {
/* All the variables, methods and images initialize here 
will be called only once because this method is called only 

  once when the applet is first initializes */
}
public void start() {
/* The components needed to be initialize more than once 
in your applet are written here or if the reader 

  switches back and forth in the applets. This method
 can be called more than once.*/

}

public void stop() {
/* This method is the counterpart to start(). The code, 
used to stop the execution is written here*/

}

public void destroy() {
/* This method contains the code that result in to release 
the resources to the applet before it is

finished. This method is called only once. */
}
public void paint(Graphics g) {
/* Write the code in this method to draw, write, or color 
things on the applet pane are */

}
}
In the above applet you have seen that there are five methods. In which two ( init() and destroy ) are called only once while remaining three (start() , stop() , and paint() ) can be called any number of times as per the requirements. The major difference between the two (applet and application) is that java applications are designed to work under the homogenous and more secure areas. On contrary to that, java applets are designed to run the heterogeneous and probably unsecured environment. Internet has imposed several restrictions on it.
Applets are not capable of reading and writing the user's file system. This means that the applet neither can access nor place anything locally. To illustrate this lets take an example.. Many Window based C applications uses the .INF file as the initialization file to store the information about the application and any user preferences in 16-bit Windows or the Registry in 32-bit Windows. While in case of current applet it is not possible.
One more thing to point here is that applets are unable to use the native methods, run any program on the user system or load shared libraries. The major security concern here is that the local shared libraries and the native methods may results in the loophole in the java security model.
Applets are not capable of  communicating the server than one from which they are originating. There are the cases in which an encryption key is used for the verification purpose for a particular applet to a server. But accessing a remote server is not possible.
The conclusion is that the java applets provides a wide variety of formats for program execution and a very tight security model on the open environment as on the Internet.
Introduction to Java Application : Java applications have the majority of differences with the java applets. If we talk at the source code level, then we don't extend any class of the standard java library that means we are not restricted to use the already defined method or to override them for the execution of the program. Instead we make set of classes that contains the various parts of the program and attach the main method with these classes for the execution of the code written in these classes. The following program illustrate the structure of the java application.
public class MyClass {
/* Various methods and variable used by the class 
MyClass are written here */

class myClass {
/* This contains the body of the class myClass */
}

public static void main(String args[]) {
/* The application starts it's actual execution 
from this place. **/

}
}
The main method here is nothing but the system method used to invoke the application. The code that results an action should locate in the main method. Therefore this method is more than the other method in any java application. If we don't specify the main method in our application, then on running the application will through an exception like this one:
In the class MyClass: void main(String args[]) is undefined
But at higher level major concern is that in a typical java application security model, an application can access the user's file system and can use native methods. On properly configuring the user's environment and the java application it will allow access to all kind of stuff from the Internet.
In most of the cases it is seen that the java application seems like a typical C/C++ application. Now we are going to create plenty of applications to exemplify some of the methods and features of a specific Java application. All of them are console based Java applications because here we are not going to cover the AWT.
Java Applications : An Example
Lets create an application that executes at the command prompt. Lets create a new file named ClassA.java.
public class ClassA{
  //write the variables for Class
  String Name;
  int AccNumber;
  float Bal;
  //This method display the information on the screen.
  void display(){
  System.out.println("Name: " + Name);
  System.out.println("Account Number: " + AccNumber);
  System.out.println("Balance: " + Bal);
  }
  public static void main(String args[]) {
  //Create an instance of ClassA
  ClassA a = new ClassA();
  //Assigning values to the variables in class ClassA
  a.Name = "Vinod";
  a.AccNumber = 467256282;
  a.Bal =635;
  //Draw the top border
  for (int i = 0; i < 20; i++)
  System.out.print("--");
  //Title
  System.out.println(" PARTICULARS");
  //Call method to display the information
  a.display();
  //Draw bottom border
  for (int i = 0; i < 20; i++)
  System.out.print("--");
  //Ending remark
  System.out.println("End of display");
  }
}
If the file ClassA.java and the javac.exe are in the same directory then compile the program just by giving the following command.
javac ClassA.java
If the file ClassA.java and javac.exe are not in same directory the set the path of java  \bin directory in the environment variable and include the directory contained the file ClassA.java in the command prompt then apply the above command.
After compiling the program, just apply the following command.
java ClassA
This will result in the following output.
---------------------------------------- PARTICULARS
Name: Vinod
Account Number: 467256282
Balance: 635.0
----------------------------------------End of display
The above example ClassA.java uses the three variables Name, AccNumber, and Bal and a display method to display the values of the variables. Everything is all right in the above example. Here is a closer look about the line System.out.println(). System is a class which is kept in java.lang package, out is an object of System class that is used to print the message on the standard  output and println() is the method of the System class.
Note the points given below:
  • The file ClassA.java makes the .class file after compilation.
  • There is no need of specifying the extension when interpreting the file.
  • While distributing the file just provide the compiled file (.class file) and the interpreter.
System class contains the following variables and methods.
Variables of the System class
Variables
Utilization
public static PrintStream in
 It is used to read the data from the standard input stream
public static PrintStream out
 It is used to write the data on the standard output stream
public static PrintStream err
It is used to print the error message on the standard output stream.
Methods defined in the System class
Methods
Utilization
getProperties()
 It returns a Properties class with the system properties.
getProperty (String key, String default)
Returns a String with a value for the specified property. Or, returns the default if the specified property is not set.
setProperties (Properties props)
Sets the system properties based on the specified properties.
gc()
Manually invokes the garbage collector. Note that unless garbage collection is manually enabled or disabled, it is done automatically by the Java virtual machine.
exit(int status)
Exits the application with the specified status code (0 if successful).
currentTimeMillis()
Returns a long that holds the value in milliseconds since January 1, 1970.
arraycopy (Object src, int src
Position, Object dst,
dstPosition, int len)
Copies an array.
runFinalization ()
Runs the finalization methods of any object pending finalization.
Importing Other packages to your Java Application: Lets create a simple application that displays the date. In this application you will see how to import packages in your application. Java libraries provide a built in method currentTimeMillis(). This method returns the number of seconds since January 1970 representing in 64-bit integer long format.
public class PrintDate {
  public static void main(String args[]) {
  //Draw the upper border
  for (int i = 0; i < 40; i++)
  System.out.print("--");
  //Display the timeT
  System.out.println("Time in milliseconds since January 1, 1970:
  " 
+ System.currentTimeMillis());
  //Draw the lower border
  for (int i = 0; i < 40; i++)
  System.out.print("--");
  }
Compile the above program by giving the following command.
javac PrintDate.java
By giving the following command you will see the following output.
java PrintDate
Here is the output of the above program:
--------------------------------------------------------------------
Time in milliseconds since January 1, 1970: 1181398838332
--------------------------------------------------------------------
To avoid the overflow and inaccuracy here we took integer data type as long. It is a 64-bit signed integer  and will contain the values up to the year 200,000,000 accurately. So we should not worry right now because this problem will take a long time to occur.
Now come to the point: Suppose the user wanted today's date in your application then no need to worry because java provides the built in class Date in the package java.util that provides this functionality. Since java.util is not a default package so we have to import it explicitly to use the functionality of the class Date. You will be known about the syntax of importing the package in your application. There is no difference of importing the package in both Java Application and the Java Applet. But don't worry i will provide you the code of importing the package in your application or applet. Here is the code of importing the package.
import java.util.Date;
Write this code in the beginning of your application, then your application can access to all the non-private member of Date class.
Now I would like to give one more example of the java application that will have access the private members of the Date class.
import java.util.Date;
public class PrintDate2 {
  Date todayDate = new Date();
  public static void main(String args[]){
  //Draw the upper border
  for (int i = 0; i < 40; i++)
  System.out.print("--");
  //Instantiate the class PrintDate2
  PrintDate2 d = new PrintDate2();
  //Display the Date
  System.out.println("Today's Date: " + d.todayDate);
  //Draw the lower border
  for (int i = 0; i < 40; i++)
  System.out.print("--");
  }
}
Compile and run the above application. On running the above application displays the current date and also shows the upper and lower border.
Here is the output of the above program:
------------------------------------------------------
Today's Date: Sat Jun 09 16:31:51 BST 2007
------------------------------------------------------
Using args[] to pass Command Line Arguments: Any application can have one more attribute that is they can receive the command line argument pass to it. Let us consider the case of an application named ClassA to which we have to pass the arguments while running the application then what have to be done. In this case we pass the argument by using the command line argument technique.
public class CommandLine {
  public static void main(String args[]){
  //Draw the upper border
  for (int i = 0; i < 40; i++)
  System.out.print("--");
  //Check to see if no argument was passed
  if (args.length == 0){
  System.out.println("Enter the argument ");
  }
  // Loop to display the argument passed to the command line 
  for (int i = 0; i < args.length; i++)
  System.out.println(" " + args[i]);
  //Draw the bottom border
  for (int i = 0; i < 40; i++)
  System.out.print("--");
  }
}
Here is the code used to pass the arguments by using the command line argument technique.
java CommandLine This is my first program 
C:\Upload>java CommandLine This is my first program
---------------------------------------------------------
This
is
my
first
program
---------------------------------------------------------
What happens when we pass the arguments within the double quotes.
java CommandLine "This is my first program"
C:\Upload>java CommandLine "This is my first program"
-----------------------------------------------------------
This is my first program
-----------------------------------------------------------
So the conclusion is that if we pass the argument on the command line by using the first technique then the arguments are stored like this.
args[0]=This
args[1]=is
args[0]=my
args[0]=first
args[0]=program
While we pass the argument on the command line by using the second technique then the arguments are stored like this
args[0]=This is my first program. To more clearly understand see the third technique:
javac CommandLine This is "my first program"
C:\Upload>java CommandLine This is "my first program"
----------------------------------------------------------
This
is
my first program
----------------------------------------------------------
The third output clears that the arguments in the above output are stored like this:
args[0]=This
args[1]=is
args[0]=my first program
Summary: In this chapter you studied about the differences and the similarities between the java applets and application. and what is the roll of java application and the java applet in java programming. Java applications are flexible in linking with the java native code and security than applets. So the overall conclusion is that both java applications and java applets have the same priority but at their own places. If java application is more flexible at one place then it has some drawback at other place where its counterpart java applet provides the more flexibility.

What is an Applet - Java Applet Tutorial

Introduction
Applet is java program that can be embedded into HTML pages. Java applets runs on the java enables web browsers such as mozila and internet explorer. Applet is designed to run remotely on the client browser, so there are some restrictions on it. Applet can't access system resources on the local computer. Applets are used to make the web site more dynamic and entertaining.
Advantages of Applet:
  • Applets are cross platform and can run on Windows, Mac OS and Linux platform
  • Applets can work all the version of Java Plugin
  • Applets runs in a sandbox, so the user does not need to trust the code, so it can work without security approval
  • Applets are supported by most web browsers
  • Applets are cached in most web browsers, so will be quick to load when returning to a web page
  • User can also have full access to the machine if user allows
Disadvantages of Java Applet:
  • Java plug-in is required to run applet
  • Java applet requires JVM so first time it takes significant startup time
  • If applet is not already cached in the machine, it will be downloaded from internet and will take time
  • Its difficult to desing and build good user interface in applets compared to HTML technology

The Life cycle of An Applet

Introduction
In this Section you will learn about the lifecycle of an applet and different methods of an applet. Applet runs in the browser and its lifecycle method are called by JVM when it is loaded and destroyed. Here are the lifecycle methods of an Applet:

init(): This method is called to initialized an applet

start(): This method is called after the initialization of the applet.

stop(): This method can be called multiple times in the life cycle of an Applet.
destroy(): This method is called only once in the life cycle of the applet when applet is destroyed.
init () method: The life cycle of an applet is begin  on that time when the applet is first loaded into the browser and called the init() method. The init() method is called only one time in the life cycle on an applet. The init() method is basically called to read the PARAM tag in the html file. The init () method retrieve the passed parameter through the PARAM tag of html file using get Parameter() method All the initialization such as initialization of variables and the objects like image, sound file are loaded in the init () method .After the initialization of the init() method user can interact  with the Applet and mostly applet contains the init() method.

Start () method:
The start method of an applet is called after the initialization method init(). This method may be called multiples time when the Applet needs to be started or restarted. For Example if the user wants to return to the Applet, in this situation the start Method() of an Applet will be called by the web browser and the user will be back on the applet. In the start method user can interact within the applet.
Stop () method:  The stop() method can be called multiple times in the life cycle of applet like the start () method. Or should be called at least one time. There is only miner difference between the start() method and stop () method. For example the stop() method is called by the web browser on that time When the user leaves one applet to go another applet and the start() method is called on that time when the user wants to go back into the first program or Applet.

destroy() method: The destroy() method is called  only one time in the life cycle of Applet like init() method. This method is called only on that time when the browser needs to Shut down.

Java and HTML: The Basics

Before going any further lets start with the basics of HTML first. In this section we will come to know about all the tags which are required for the applet to be displayed within the browser. HTML provides a tag that enables the developer  to "embed" the applet within the page. This tag is known as the APPLET tag.
HTML Tags
  • HTML tags are used to mark-up HTML elements
  • HTML tags are surrounded by the two characters < and >
  • The surrounding characters are called angle brackets
  • HTML tags normally come in pairs like <b> and </b>
  • The first tag in a pair is the start tag, the second tag is the end tag
  • The text between the start and end tags is the element content
  • HTML tags are not case sensitive, <b> means the same as <B>
HTML Elements
Recall the HTML example from the previous previous section:
<html>
<head>
<title>Title of page</title>
</head>
<body>
This is my first homepage. <b>This text is bold</b>
</body>
</html>


Now lets see what are HTML elements:

<b>This text is bold</b>
The HTML element starts with a start tag <b> and ends with </b> tag.
The content of the HTML element is: This text is bold
The <b> tag is used to define an HTML element that should be displayed as bold.
Another HTML element is:
<body>
This is my first homepage.
<b>This text is bold</b>
</body>
This HTML element starts with the start tag <body> and ends with the end tag </body>.
Here the <body> tag defines the HTML element that contains the body of the HTML document.
Setting Up the Title: The <HEAD> and the <TITLE> Tags
We have already learned that how to use the <HEAD> and the <TITLE> Tags to display the information on the document. However, I would like to tell you that the browser starts processing the HTML document when it sees the <HTML> tag. Furthermore, we use the HEAD tag after the HTML tag which contains the information though the information doesn't appear directly on the page.
However, any information which we insert in the TITLE tag gets displayed on the blue bar of the Web browser. As shown below.
<HTML>
<HEAD>
<TITLE>This is my first homepage!</TITLE>
</HEAD>
</HTML> 

The <BODY> Tag
Now lets add a little bit of more information to our document. For this we will use BODY tag as you are already familiar with. As shown below.
<HTML>
<HEAD>
<TITLE>This is my applet's first home!</TITLE>
</HEAD>
<BODY>
</BODY>
</HTML> 

Well the above HTML code will display a blank screen. To make the text more live we use number of HTML tags. The two most commonly used tags are the heading tags and paragraph tags which are described below.
Headings
As by the name headings always appear at the top of any any text or paragraph. There are six levels of headings in HTML. These headings are defined with the <h1> to <h6> tags. The <h1> defines the largest heading and <h6> defines the smallest heading. The tags are given below.
<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>
<h4>This is a heading</h4>
<h5>This is a heading</h5>
<h6>This is a heading</h6>


NOTE : HTML automatically adds an extra blank line before and after a heading.
<html>
        <head>
               <title>HTML Heading Example</title>
        </head>
        <body>
               <h1>This is Heading 1</h1>
               <h2>This is Heading 2</h2>
               <h3>This is Heading 3</h3>
               <h4>This is Heading 4</h4>
               <h5>This is Heading 5</h5>
               <h6>This is Heading 6</h6>
        </body>
</html>
Output for the above code:
http://www.roseindia.net/java/example/java/applet/test1.gif
Paragraphs
One of the most common tags used to contain regular text in HTML is the paragraph tag. The <p> tag is used to insert a paragraph as shown below.
<p>This is a paragraph</p>
<p>This is another paragraph</p>

<html>
        <head>
               <title>This is my applet's first home!</title>
        </head>
        <body>
               <p>You are learning html.</p>
               <p>This is the paragraph.</p>
        </body>
</html>

Output For The Above HTML Code:
http://www.roseindia.net/java/example/java/applet/test3.gif
Line Breaks
The <br> tag is used for line break. This tag is used to end a line i.e. to end a line without starting a new paragraph. The <br> tag forces a line break wherever you place it. They have no ending tag because they do not actually contain anything. The <br> tag is an empty tag. It has no closing tag.
<p>My <br> new page<br> with line breaks</p>
<html>
        <head>
               <title>Breaking a line</title>
        </head>
        <body>
               <p>Let us break<br/>the line.</p>
        </body>
</html>
Output For The Above HTML Code:
http://www.roseindia.net/java/example/java/applet/test4.gif
Comments in HTML
To explain your code, you can use comments which can help you when you edit the source code at a some time later. To insert a comment in the HTML source code, the comment tag is used. However a comment gets ignored by the browser. For instance.

Java Applet - Creating First Applet Example

Introduction
First of all we will know about the applet. An applet is a program written in java programming language and embedded within HTML page. It run on the java enabled web browser such as Netscape navigator or Internet Explorer.
In this example you will see, how to write an applet program. Java source of applet is then compiled into java class file and we specify the name of class in the applet tag of html page. The java enabled browser loads class file of applet and run in its sandbox.


Here is the java code of program :
import java.applet.*;
import java.awt.*;

public class FirstApplet extends Applet{
  public void paint(Graphics g){
  g.drawString("Welcome in Java Applet.",40,20);
  }
}
Here is the HTML code of the program:
<HTML>
<HEAD>
</HEAD>
<BODY>
<APPLET
ALIGN="CENTER" CODE="FirstApplet.class" WIDTH="800" HEIGHT="500"></APPLET>
</BODY>
</HTML>
Download this example.

Applet - Passing Parameter in Java Applet

Introduction
Java applet has the feature of retrieving the parameter values passed from the html page. So, you can pass the parameters from your html page to the applet embedded in your page. The param tag(<parma name="" value=""></param>) is used to pass the parameters to an applet. For the illustration about the concept of applet and passing parameter in applet, a example is given below.
In this example, we will see what has to be done in the applet code to retrieve the value from parameters. Value of a parameter passed to an applet can be retrieved using getParameter() function. E.g. code:
String strParameter = this.getParameter("Message");
Printing the value:
Then in the function paint (Graphics g), we prints the parameter value to test the value passed from html page. Applet will display "Hello! Java Applet"  if no parameter is passed to the applet else it will display the value passed as parameter. In our case applet should display "Welcome in Passing parameter in java applet example." message.
Here is the code for the Java Program : 
import java.applet.*; 
import java.awt.*; 
 
public class appletParameter extends Applet {
  private String strDefault = "Hello! Java Applet.";
  public void paint(Graphics g) {
  String strParameter = this.getParameter("Message");
  if (strParameter == null)
  strParameter = strDefault;
  g.drawString(strParameter, 50, 25);
  } 
}
Here is the code for the html program : 
<HTML>
<HEAD>
<TITLE>
Passing Parameter in Java Applet</TITLE>
</HEAD>
<BODY>

This is the applet:<P>
<APPLET code="appletParameter.class" width="800" height="100">
<PARAM name="message" value="Welcome in Passing parameter in java applet example.">
</APPLET>
</BODY>
</HTML>
There is the advantage that if need to change the output then you will have to change only the value of the param tag in html file not in java code.

Compile the program :
javac appletParameter.java
Output after running the program :
To run the program using appletviewer, go to command prompt and type appletviewer appletParameter.html Appletviewer will run the applet for you and and it should show output like Welcome in Passing parameter in java applet example. Alternatively you can also run this example from your favorite java enabled browser.

Keyboard Input

The source code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
 
public class Keyboard1 extends Applet
   implements KeyListener, MouseListener {
 
   int width, height;
   int x, y;
   String s = "";
 
   public void init() {
      width = getSize().width;
      height = getSize().height;
      setBackground( Color.black );
 
      x = width/2;
      y = height/2;
 
      addKeyListener( this );
      addMouseListener( this );
   }
 
   public void keyPressed( KeyEvent e ) { }
   public void keyReleased( KeyEvent e ) { }
   public void keyTyped( KeyEvent e ) {
      char c = e.getKeyChar();
      if ( c != KeyEvent.CHAR_UNDEFINED ) {
         s = s + c;
         repaint();
         e.consume();
      }
   }
 
   public void mouseEntered( MouseEvent e ) { }
   public void mouseExited( MouseEvent e ) { }
   public void mousePressed( MouseEvent e ) { }
   public void mouseReleased( MouseEvent e ) { }
   public void mouseClicked( MouseEvent e ) {
      x = e.getX();
      y = e.getY();
      s = "";
      repaint();
      e.consume();
   }
 
   public void paint( Graphics g ) {
      g.setColor( Color.gray );
      g.drawLine( x, y, x, y-10 );
      g.drawLine( x, y, x+10, y );
      g.setColor( Color.green );
      g.drawString( s, x, y );
   }
}
 
Try clicking and typing into the applet. You'll probably have to click at least once before you begin typing, to give the applet the keyboard focus.
Here's a second applet that nicely integrates most of what we've learned so far.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
 
public class Keyboard2 extends Applet
   implements KeyListener, MouseListener, MouseMotionListener {
 
   int width, height;
   int N = 25;
   Color[] spectrum;
   Vector listOfPositions;
   String s = "";
   int skip = 0;
 
   public void init() {
      width = getSize().width;
      height = getSize().height;
      setBackground( Color.black );
 
      spectrum = new Color[ N ];
      for ( int i = 0; i < N; ++i ) {
         spectrum[i] = new Color( Color.HSBtoRGB(i/(float)N,1,1) );
      }
 
      listOfPositions = new Vector();
 
      addKeyListener( this );
      addMouseListener( this );
      addMouseMotionListener( this );
   }
 
   public void keyPressed( KeyEvent e ) { }
   public void keyReleased( KeyEvent e ) { }
   public void keyTyped( KeyEvent e ) {
      char c = e.getKeyChar();
      if ( c != KeyEvent.CHAR_UNDEFINED ) {
         s = s + c;
         repaint();
         e.consume();
      }
   }
 
   public void mouseEntered( MouseEvent e ) { }
   public void mouseExited( MouseEvent e ) { }
   public void mouseClicked( MouseEvent e ) {
      s = "";
      repaint();
      e.consume();
   }
   public void mousePressed( MouseEvent e ) { }
   public void mouseReleased( MouseEvent e ) { }
   public void mouseMoved( MouseEvent e ) {
 
      // only process every 5th mouse event
      if ( skip > 0 ) {
         -- skip;  // this is shorthand for "skip = skip-1;"
         return;
      }
      else skip = 5;
 
      if ( listOfPositions.size() >= N ) {
         // delete the first element in the list
         listOfPositions.removeElementAt( 0 );
      }
 
      // add the new position to the end of the list
      listOfPositions.addElement( new Point( e.getX(), e.getY() ) );
 
      repaint();
      e.consume();
   }
   public void mouseDragged( MouseEvent e ) { }
 
   public void paint( Graphics g ) {
      if ( s != "" ) {
         for ( int j = 0; j < listOfPositions.size(); ++j ) {
            g.setColor( spectrum[ j ] );
            Point p = (Point)(listOfPositions.elementAt(j));
            g.drawString( s, p.x, p.y );
         }
      }
   }
}
 
Click, type, and move the mouse. You might see some flickering. Depending on the speed of your computer, you might also find that the mouse position is being sampled too quickly or too slowly. The upcoming lessons will give you tools to fix both of these problems.

3D Graphics

The source code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.Math;
 
class Point3D {
   public int x, y, z;
   public Point3D( int X, int Y, int Z ) {
      x = X;  y = Y;  z = Z;
   }
}
 
class Edge {
   public int a, b;
   public Edge( int A, int B ) {
      a = A;  b = B;
   }
}
 
public class WireframeViewer extends Applet
   implements MouseListener, MouseMotionListener {
 
   int width, height;
   int mx, my;  // the most recently recorded mouse coordinates
 
   Image backbuffer;
   Graphics backg;
 
   int azimuth = 35, elevation = 30;
 
   Point3D[] vertices;
   Edge[] edges;
 
   public void init() {
      width = getSize().width;
      height = getSize().height;
 
      vertices = new Point3D[ 8 ];
      vertices[0] = new Point3D( -1, -1, -1 );
      vertices[1] = new Point3D( -1, -1,  1 );
      vertices[2] = new Point3D( -1,  1, -1 );
      vertices[3] = new Point3D( -1,  1,  1 );
      vertices[4] = new Point3D(  1, -1, -1 );
      vertices[5] = new Point3D(  1, -1,  1 );
      vertices[6] = new Point3D(  1,  1, -1 );
      vertices[7] = new Point3D(  1,  1,  1 );
 
      edges = new Edge[ 12 ];
      edges[ 0] = new Edge( 0, 1 );
      edges[ 1] = new Edge( 0, 2 );
      edges[ 2] = new Edge( 0, 4 );
      edges[ 3] = new Edge( 1, 3 );
      edges[ 4] = new Edge( 1, 5 );
      edges[ 5] = new Edge( 2, 3 );
      edges[ 6] = new Edge( 2, 6 );
      edges[ 7] = new Edge( 3, 7 );
      edges[ 8] = new Edge( 4, 5 );
      edges[ 9] = new Edge( 4, 6 );
      edges[10] = new Edge( 5, 7 );
      edges[11] = new Edge( 6, 7 );
 
      backbuffer = createImage( width, height );
      backg = backbuffer.getGraphics();
      drawWireframe( backg );
 
      addMouseListener( this );
      addMouseMotionListener( this );
   }
 
   void drawWireframe( Graphics g ) {
 
      // compute coefficients for the projection
      double theta = Math.PI * azimuth / 180.0;
      double phi = Math.PI * elevation / 180.0;
      float cosT = (float)Math.cos( theta ), sinT = (float)Math.sin( theta );
      float cosP = (float)Math.cos( phi ), sinP = (float)Math.sin( phi );
      float cosTcosP = cosT*cosP, cosTsinP = cosT*sinP,
             sinTcosP = sinT*cosP, sinTsinP = sinT*sinP;
 
      // project vertices onto the 2D viewport
      Point[] points;
      points = new Point[ vertices.length ];
      int j;
      int scaleFactor = width/4;
      float near = 3;  // distance from eye to near plane
      float nearToObj = 1.5f;  // distance from near plane to center of object
      for ( j = 0; j < vertices.length; ++j ) {
         int x0 = vertices[j].x;
         int y0 = vertices[j].y;
         int z0 = vertices[j].z;
 
         // compute an orthographic projection
         float x1 = cosT*x0 + sinT*z0;
         float y1 = -sinTsinP*x0 + cosP*y0 + cosTsinP*z0;
 
         // now adjust things to get a perspective projection
         float z1 = cosTcosP*z0 - sinTcosP*x0 - sinP*y0;
         x1 = x1*near/(z1+near+nearToObj);
         y1 = y1*near/(z1+near+nearToObj);
 
         // the 0.5 is to round off when converting to int
         points[j] = new Point(
            (int)(width/2 + scaleFactor*x1 + 0.5),
            (int)(height/2 - scaleFactor*y1 + 0.5)
         );
      }
 
      // draw the wireframe
      g.setColor( Color.black );
      g.fillRect( 0, 0, width, height );
      g.setColor( Color.white );
      for ( j = 0; j < edges.length; ++j ) {
         g.drawLine(
            points[ edges[j].a ].x, points[ edges[j].a ].y,
            points[ edges[j].b ].x, points[ edges[j].b ].y
         );
      }
   }
 
   public void mouseEntered( MouseEvent e ) { }
   public void mouseExited( MouseEvent e ) { }
   public void mouseClicked( MouseEvent e ) { }
   public void mousePressed( MouseEvent e ) {
      mx = e.getX();
      my = e.getY();
      e.consume();
   }
   public void mouseReleased( MouseEvent e ) { }
   public void mouseMoved( MouseEvent e ) { }
   public void mouseDragged( MouseEvent e ) {
      // get the latest mouse position
      int new_mx = e.getX();
      int new_my = e.getY();
 
      // adjust angles according to the distance travelled by the mouse
      // since the last event
      azimuth -= new_mx - mx;
      elevation += new_my - my;
 
      // update the backbuffer
      drawWireframe( backg );
 
      // update our data
      mx = new_mx;
      my = new_my;
 
      repaint();
      e.consume();
   }
 
   public void update( Graphics g ) {
      g.drawImage( backbuffer, 0, 0, this );
      showStatus("Elev: "+elevation+" deg, Azim: "+azimuth+" deg");
   }
 
   public void paint( Graphics g ) {
      update( g );
   }
}
 
Notice that the compiler generates 3 .class files: one for each of the classes defined.
Click and drag on the applet to rotate the cube.



No comments: