You are on page 1of 12

Internet & Java Programming

Question 2:
(A) What is a Package? What are the benefits of using packages? Write down the steps in creating a package and using it in java program with an example (B) Explain the following terms with respect to exception handling a. b. c. d. Try Catch Throw Finally

Answer:
A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages.

The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the "Application Programming Interface", or "API" for short. Its packages represent the tasks most commonly associated with generalpurpose programming. For example, a String object contains state and behavior for character strings; a File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the file system; a Socket object allows for the creation and use of network sockets; various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. There are literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work.

Some of the existing packages in Java are::

java.lang - bundles the fundamental classes

java.io - classes for input , output functions are bundled in this package

Benefits of using Package


Packaging protects against name collisions. Packages hide implementation that spans multiple classes (multi-class encapsulation). Packages help organize source code.

How to create a package Suppose we have a file called HelloWorld.java, and we want to put this file in a package world. First thing we have to do is to specify the keyword package with the name of the package we want to use (worldin our case) on top of our source file, before the code that defines the real classes in the package, as shown in our HelloWorld class below:

// only comment can be here


package world; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } } Exception Handling An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following: A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications, or the JVM has run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. To understand how exception handling works in Java, you need to understand the three categories of exceptions: Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation. Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation. Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Catching Exceptions: A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

try { //Protected code }catch(ExceptionName e1) { //Catch block }

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter. Example: The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.

// File Name : ExcepTest.java

import java.io.*; public class ExcepTest{ public static void main(String args[]){ try{ int a[] = new int[2]; System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } }
This would produce following result:

Exception thrown Out of the block

:java.lang.ArrayIndexOutOfBoundsException: 3

The throws/throw Keywords: If a method does not handle a checked exception, the method must declare it using the throwskeyword. The throws keyword appears at the end of a method's signature. You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Try to understand the different in throws and throw keywords. The following method declares that it throws a RemoteException:

import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } //Remainder of class definition }
A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and an InsufficientFundsException:

import java.io.*; public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation } //Remainder of class definition }
The finally Keyword The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of the catch blocks and has the following syntax: try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block }finally { //The finally block always executes. } Example:

public class ExcepTest{ public static void main(String args[]){ int a[] = new int[2]; try{ System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } finally{

a[0] = 6; System.out.println("First element value: " +a[0]); System.out.println("The finally statement is executed"); } } }

This would produce following result:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed

Question 3:
What is an Event Delegation Model and what are the even classes and event interfaces? Describe the AWT controls in Java?

Answer:
Delegation Event model Event broadcasting system in java called as EVENT DELEGATION MODEL. This model is based on the Event Source and Event Listeners. Event Listener is an object that receives the message/ events. The Event Source is any object which creates the message/ event. The Event Delegation Model is based on the following things. Event Source - This class which broadcasts the events. Event Listeners - The classes which receive notifications of events. The Event Listeners are implemented to Adapter classes for the default action for a particular event. The API user is free to override the Adapter version of the method. The event listeners should extend the java.util.EventListener interface. Event Object - The object which describes the event. The event object class should extend java.util.EventObject class. Event Manager - This is the class which manages the relationship between the event and listeners. This class will register and de-register the listeners for a particular event.

The following picture explains how the event model works.

Now time to look at the programming implementation. Event Class: 1 import java.util.EventObject; 2 3 //Declare the event. It must extend EventObject. 4 public class MyEvent extends EventObject { 5 public MyEvent(Object source) { 6 super(source); 7 } 8} Event Listener: 1 package org.satish.event; 2 3 import java.util.EventListener; 4 5 //Declare the listener class. It must extend EventListener. 6 //A class must implement this interface to get MyEvents. 7 public interface MyEventListener extends EventListener { 8 public void myEventOccurred(MyEvent evt); 9} Event Manager:

1 package org.satish.event; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 //Add the event registration and notification code to a class. 7 public class EventManager { 8 // Create the listener list 9 protected List listenerList = new ArrayList(); 10 11 // This methods allows classes to register for MyEvents 12 public void addMyEventListener(MyEventListener listener) { 13 listenerList.add(listener); 14 } 15 16 // This methods allows classes to unregister for MyEvents 17 public void removeMyEventListener(MyEventListener listener) { 18 listenerList.remove(listener); 19 } 20 21 // This method is used to fire MyEvents 22 void fireMyEvent(MyEvent evt) { 23 System.out.println("Got the event." + listenerList.size()); 24 // Iterate the Listener list to fire the implemented method of each 25 // listener. 26 for (MyEventListener myEventListener : listenerList) { 27 System.out 28 .println("Firing listener method for each of the listener."); 29 myEventListener.myEventOccurred(evt); 30 } 31 } 32 } Event Source:

1 package org.satish.event; 2 3 public class EventGenerator implements Runnable{ 4 5 Thread t; 6 EventManager c; 7 public EventGenerator(EventManager c) { 8 // TODO Auto-generated constructor stub 9 this.c = c; 10 t = new Thread(this, "Event Generator"); 11 t.start(); 12 } 13 @Override 14 public void run() { 15 // TODO Auto-generated method stub 16 System.out.println("Event generator in the run method."); 17 while(true){ 18 System.out.println("Generate a event."); 19 c.fireMyEvent(new MyEvent(this)); 20 try { 21 Thread.sleep(1000); 22 } catch (InterruptedException e) { 23 // TODO: handle exception 24 } 25 } 26 } 27 }

This is the basic implementation of event delegation model. In a multi threaded environment, where more than one listener are registered to each event and the generation of event is quite fast, then you need to change your design to deal with the requirement. AWT Controls AWT stands for Abstract Window ToolKit. It is a portable GUI library between Solaris and Windows 95/NT and Mac System 7.X(soon) for stand-alone applications and/or applets. Since it can be used in applets it can be used on IRIX, SunOS, HP/UX, Linux which Netscape 2.0 supports. The Abstract Window Toolkit provides many classes for programmers to use. It is your connection between your application and the native GUI. The AWT hides you from the underlying details of the GUI your application will be running on and thus is at very high level of abstraction. It takes the lowest common denominator approach to retain portability. No floating toolbars or Balloon help here... It is a Java package and can be used in any Java program by importing java.awt.* via the import keyword. The documentation for the package is available at the Java hompage. The package will be covered briefly as this document is not considered advanced material because it

does not discuss Peers, ImageConsumers/Producers, Toolkits and other advanced AWT ilk. The Basic Controls: Buttons, Checkboxes, Choices, Lists, Menus, and Text Fields

The Basic Controls: Buttons, Checkboxes, Choices, Lists, Menus, and Text Fields The Button, Checkbox, Choice, List, MenuItem, and TextField classes provide basic controls. These are the most common ways that users give instructions to Java programs. When a user activates one of these controls -- by clicking a button or by pressing Return in a text field, for example -- it posts an event (ACTION_EVENT). An object that contains the control can react to the event by implementing the action() method.

Other Ways of Getting User Input: Canvases and Text Areas When the basic controls aren't appropriate, you can use the Canvas and TextArea classes to get user input. The TextArea class simply provides an area to display or allow editing of several lines of text. Create a subclass of the Canvas class if you need draw custom graphics to the screen -- in a paint program, image processor, or game, for example.

Yet More Components: Scrollbars and Labels The AWT provides two more handy components: scrollbars and labels. Text areas automatically have scrollbars, but you can use the Scrollbar class to make other kinds of areas scroll. Labels simply display an uneditable, unselectable line of text.

Containers: Windows and Panels The AWT provides two types of containers, both implemented as subclasses of the Container class (which is a Component subclass). The Window subclasses -- Dialog, FileDialog, and Frame -- provide windows to contain components. Panels group components within an area of an existing window. Example:
The AWT provides five layout managers. They range from very simple to very complex. This article covers only the two layout manager classes used by the examples herein: the FlowLayout class and the BorderLayout class. The FlowLayout class places components in a container from left to right. When the space in one row is exhausted, another row is started. The single-argument version of a container's add() method is used to add components. The BorderLayout class has five zones as depicted in Figure 7. The zones are named "North", "South", "East", "West", and "Center". A single component can be placed in each of these five zones. When the enclosing container is resized, each border zone is resized just enough to hold the component placed within. Any excess space is given to the center zone. The two-argument version

of a container'sadd() method is used to add components. The first argument is a String object that names the zone in which to place the component.

The code in Listing 5 uses both layout managers and includes a few more user interface components. The result is displayed below,

import java.awt.*; public class Example4 extends java.applet.Applet { public void init() { Panel p; setLayout(new BorderLayout()); p = new Panel(); p.add(new TextArea()); add("Center", p); p = new Panel(); p.add(new Button("One")); p.add(new Button("Two")); Choice c = new Choice(); c.addItem("one"); c.addItem("two"); c.addItem("three"); p.add(c);

add("South", p); } public static void main(String [] args) { Frame f = new Frame("Example 4"); Example4 ex = new Example4(); ex.init(); f.add("Center", ex); f.pack(); f.show(); } }

You might also like