Monday, 1 October 2012

Java Tools javap,javadoc,javah,jar,javaw,jdb,jad






Java javap tool
The javap tool disassembles compiled Java™ files and prints out a representation of the Java program. This may be helpful when the original source code is no longer available on a system.

-b
This option is ignored. Backward compatibility is not required, because Java on the System i5™ only supports recent version sof the Java Development Kit (JDK).
-p
On the System i5, -p is not a valid option. You must spell out -private.
-verify
This option is ignored. The javap tool does not do verification on the System i5.
The javap tool is available using the Qshell Interpreter.

Note: The use of the javap tool to disassemble classes may violate the license agreement for those classes. Consult the license agreement for the classes before using the javap tool.

Javadoc Tool


Javadoc is a tool that parses the declarations and documentation comments in a set of source files and produces a set of HTML pages describing the classes, inner classes, interfaces, constructors, methods, and fields.
You can use Javadoc doclets to customize Javadoc output. A doclet is a program written with the doclet API that specifies the content and format of the output to be generated by the javadoc tool. You can write a doclet to generate any kind of text-file output, such as HTML, SGML, XML, RTF, and MIF. SunTM provides a "standard" doclet for generating HTML-format API documentation and an experimental MIF doclet for generating MIF, PDF, PS, RTF, FrameMaker, and other formats. Doclets can also be used to perform special tasks not related to producing API documentation. For example, a diagnostic doclet could be created to check that all class members of the classes on which Javadoc operates have documentation comments.

Javadoc Enhancements
Describes the new features.
What's New in Javadoc 1.4.2
What's New in Javadoc 1.4.1
What's New in Javadoc 1.4.0
What's New in Javadoc 1.3
What's New in Javadoc 1.2.2
What's New in Javadoc 1.2

Javadoc Tool Reference Page
References pages listing all javadoc tags and command-line options. Shows how to run the Javadoc tool, with examples in Solaris and Microsoft Windows.
Javadoc 1.4.2 Tool Reference Page (Solaris)
Javadoc 1.4.2 Tool Reference Page (Microsoft Windows)

Doclet API
Doclet Overview - Provides an introduction to doclets with simple examples that illustrate the Doclet API.
Doclet API - Documentation for the com.sun.javadoc package, which comprises the Doclet API.

Taglet API
Taglet Overview - Provides an introduction to taglets with simple examples that illustrate the Taglet API.
Taglet API - Documentation for the com.sun.tools.doclets.Taglet class, which comprises the Taglet API.

Doclets
Standard Doclet - the doclet that produces the default HTML-formatted API documentation. Javadoc uses the standard doclet if no other doclet is specified with Javadoc's -doclet option.

MIF Doclet - Experimental - generates API documentation in MIF (Maker Interchange Format). These MIF files can then be opened in Adobe FrameMaker (or fmbatch) and optionally converted to PDF, PS, Microsoft RTF, Microsoft Word or WordPerfect. Not included in Java 2 SDK.

DocCheck Doclet - Experimental - reviews Javadoc comments in the source code, identifying gaps and irregularities, and producing an HTML report that displays serious and trivial problems and suggests changes.
Third Party Doclets - Developed outside of Sun.

Let Us Know about Your Doclets
We'd like to know about doclets that you create. If you would like us to consider adding a link from the doclets page to your doclet's output, send the URL to email address  .

For More Information
Located on the website:
Javadoc FAQ - Important tips and workarounds for bugs.

Javadoc Forum - Enter into discussions with fellow developers. You must join the Java Developer Connection (free) to take part. Click on "Javadoc Tool" category. This forum is monitored only occasionally by the Javadoc team. If you want a prompt reply from the Javadoc team, use the email address below.
Submitting Bugs:

What Bugs Are in Javadoc? - Please see if your bug or feature request is already in our database:
How Do I Submit Bugs and Feature Requests? - Then submit your bugs and feature requests according to these instructions.

Javadoc announcements email group - A public one-way mailing list you can subscribe to for receiving major announcements about Javadoc tool, the standard doclet, the MIF doclet, the DocCheck doclet, the localization doclet, and others. Traffic should be light.

Email Address for the Javadoc Team - While we read all comments, and try to reply to every one, replies are not guaranteed.

Javadoc Tool Home Page - Covers all versions of the Javadoc tool.



Java javah tool
The javah tool facilitates the implementation of Java™ native methods. It is compatible with the javah tool that is supplied by Sun Microsystems, Inc. with a few exceptions.


Note: Writing native methods means that your application is not 100% pure Java. It also means that your application is not directly portable across platforms. Native methods are, by nature, platform or system-specific. Using native methods may increase your development and maintenance costs for your applications.
The javah tool is available using the Qshell Interpreter. It reads a Java class file and creates a C-language header file in the current working directory. The header file that is written is an System i5™ Stream File (STMF). It must be copied to a file member before it can be included in a System i5 C program

The javah tool is compatible with the tool that is provided by Sun Microsystems, Inc. If these options are specified, however, the server ignores them.

-td
The javah tool on the System i5 does not require a temporary directory.
-stubs
Java on the System i5 only supports the Java Native Interface (JNI) form of native methods. Stubs were only required for the pre-JNI form of native methods.
-trace
Relates to the .c stub file output, which Java on the System i5 does not support.
-v
Not supported.



jar-The Java Archive Tool

Combines multiple files into a single JAR archive file.
Synopsis
Description
Options
Command Line Argument Files
Examples
See Also
SYNOPSIS

Create jar file
jar c[v0M]f jarfile [-C dir] inputfiles [-Joption]
jar c[v0]mf manifest jarfile [-C dir] inputfiles [-Joption]
jar c[v0M] [-C dir] inputfiles [-Joption]
jar c[v0]m manifest [-C dir] inputfiles [-Joption]
Update jar file
jar u[v0M]f jarfile [-C dir] inputfiles [-Joption]
jar u[v0]mf manifest jarfile [-C dir] inputfiles [-Joption]
jar u[v0M] [-C dir] inputfiles [-Joption]
jar u[v0]m manifest [-C dir] inputfiles [-Joption]
Extract jar file
jar x[v]f jarfile [inputfiles] [-Joption]
jar x[v] [inputfiles] [-Joption]
List table of contents of jar file
jar t[v]f jarfile [inputfiles] [-Joption]
jar t[v] [inputfiles] [-Joption]
Add index to jar file
jar i jarfile [-Joption]
where:

cuxtiv0Mmf
Options that control the jar command.
jarfile
Jar file to be created (c), updated (u), extracted (x), or have its table of contents viewed (t). The f option and filename jarfile are a pair -- if either is present, they must both appear. Note that omitting f and jarfile accepts a "jar file" from standard input (for x and t) or sends the "jar file" to standard output (for c and u).
inputfiles
Files or directories, separated by spaces, to be combined into jarfile (for c and u), or to be extracted (for x) or listed (for t) from jarfile. All directories are processed recursively. The files are compressed unless option O (zero) is used.
manifest
Pre-existing manifest file whose name: value pairs are to be included in MANIFEST.MF in the jar file. The m option and filename manifesfile are a pair -- if either is present, they must both appear. The letters m and f must appear in the same order that manifest and jarfile appear.
-C dir
Temporarily changes directories to dir while processing the following inputfiles argument. Multiple -C dir inputfiles sets are allowed.
-Joption
Option to be passed into the Java runtime environment. (There must be no space between -J and option).
DESCRIPTION

The jar tool combines multiple files into a single JAR archive file. jar is a general-purpose archiving and compression tool, based on ZIP and the ZLIB compression format. However, jar was designed mainly to facilitate the packaging of java applets or applications into a single archive. When the components of an applet or application (.class files, images and sounds) are combined into a single archive, they may be downloaded by a java agent (like a browser) in a single HTTP transaction, rather than requiring a new connection for each piece. This dramatically improves download times. jar also compresses files and so further improves download time. In addition, it allows individual entries in a file to be signed by the applet author so that their origin can be authenticated. The syntax for the jar tool is almost identical to the syntax for the tar command. A jar archive can be use as a class path entry, whether it is compressed or not.
Typical usage to combine files into a jar file is:

C:\Java> jar cf myFile.jar *.class
In this example, all the class files in the current directory are placed into the file named "myFile.jar". A manifest file entry named META-INF/MANIFEST.MF is automatically generated by the jar tool and is always the first entry in the jar file. The manifest file is the place where any meta-information about the archive is stored as name: value pairs. Refer to the JAR file specification for details about how meta-information is stored in the manifest file.
If you have a pre-existing manifest file whose name: value pairs you want the jar tool to include for the new jar archive, you can specify it using the m option:

C:\Java> jar cmf myManifestFile myFile.jar *.class
Be sure that any pre-existing manifest file that you use ends with a new line. The last line of a manifest file will not be parsed if it doesn't end with a new line character. Note that when you specify "cfm" instead of "cmf" (i.e., you invert the order of the "m" and "f" options), you need to specify the name of the jar archive first, followed by the name of the manifest file:
C:\Java> jar cfm myFile.jar myManifestFile *.class
The manifest is in a text format inspired by RFC822 ASCII format, so it is easy to view and process manifest-file contents.
To extract the files from a jar file, use x, as in:

C:\Java> jar xf myFile.jar
To extract only certain files from a jar file, supply their filenames:

C:\Java> jar xf myFile.jar foo bar
Beginning with version 1.3 of the Java 2 SDK, the jar utility supports JarIndex, which allows application class loaders to load classes more efficiently from jar files. If an application or applet is bundled into multiple jar files,  only the necessary jar files will be downloaded and opened to load classes. This performance optimization is enabled by running jar with the i option. It will generate package location information for the specified main jar file and all the jar files it depends on, which need to be specified in the Class-Path attribute of the main jar file's manifest.

C:\Java> jar i main.jar
In this example, an INDEX.LIST file is inserted into the META-INF directory of main.jar.
The application class loader will use the information stored in this file for efficient class loading.  Refer to the JarIndex specification for details about how location information is stored in the index file.

A standard way to copy directories is to first compress files in dir1 to standard out, then extract from standard in to dir2 (omitting f from both jar commands):

C:\Java> (cd dir1; jar c .) | (cd dir2; jar x)
Examples of using the jar tool to operate on jar files and jar file manifests are provided below and in the Jar trail of the Java Tutorial.




The java and javaw commands
An overview of the java and javaw commands.

Purpose
The java and javaw tools start a Java application by starting a Java Runtime Environment and loading a specified class.

The javaw command is identical to java, except that javaw has no associated console window. Use javaw when you do not want a command prompt window to be displayed. The javaw launcher displays a window with error information if it fails.

Usage
The JVM searches for the initial class (and other classes that are used) in three sets of locations: the bootstrap class path, the installed extensions, and the user class path. The arguments that you specify after the class name or jar file name are passed to the main function.

The java and javaw commands have the following syntax:

java [ options ] <class> [ arguments ... ]
java [ options ] -jar <file.jar> [ arguments ... ]
javaw [ options ] <class> [ arguments ... ]
javaw [ options ] -jar <file.jar> [ arguments ... ]
Parameters
[options]
Command-line options to be passed to the runtime environment.
<class>
Startup class. The class must contain a main() method.
<file.jar>
Name of the jar file to start. It is used only with the -jar option. The named jar file must contain class and resource files for the application, with the startup class indicated by the Main-Class manifest header.
[arguments ...]
Command-line arguments to be passed to the main() function of the startup class.

Obtaining version information
You obtain the IBM® build and version number for your Java installation using the -version or -fullversion options. You can also obtain version information for all jar files on the class path by using the -Xjarversion option.

Specifying Java options and system properties
You can specify Java options and system properties on the command line, by using an options file, or by using an environment variable.
Standard options

The definitions for the standard options.
Globalization of the java command
The java and javaw launchers accept arguments and class names containing any character that is in the character set of the current locale. You can also specify any Unicode character in the class name and arguments by using Java escape sequences.





Network programming in Java






Network programming in Java


Package:
import java.net.*;
Can use these classes to (a) communicate with any server, (b) construct your own server.

Java network programming reference

Java Reference
Java Standard Edition
Tutorials
Networking tutorial
JDK 6 docs
Networking
API
java.net package
exampledepot.com
java.net examples

Example - Find IP address

Find numeric (IP) host address given text address.
InetAddress.getByName(hostname)

From Graba:



import java.net.*;
import java.io.*;

public class ip 
{
  public static void main ( String[] args ) throws IOException 
  {
    String hostname = args[0];

    try 
    {
      InetAddress ipaddress = InetAddress.getByName(hostname);
      System.out.println("IP address: " + ipaddress.getHostAddress());
    }
    catch ( UnknownHostException e )
    {
      System.out.println("Could not find IP address for: " + hostname);
    }
  }
}
Run it:


$ javac ip.java

$ java ip www.computing.dcu.ie 
IP address: 136.206.11.240

Q. Write program to find text given numeric.

See DNS lookup.


getLocalHost

To find your own numeric IP address in Java:
getLocalHost 
Works on DCU Win.
Works on DCU Solaris.
Doesn't seem to work on DCU Linux. Can anyone tell me why?

Other ways to find your IP address:

On DCU Linux (lab machines):
$ ip addr list eth0
On DCU Linux (ssh student.computing.dcu.ie):
$ hostname -f
shows we are in dcu.ie

$ cat /etc/resolv.conf
shows my DNS server is in 136.206
On Windows:
$ ipconfig
Click a remote site. e.g. My PHP pages to give:
REMOTE_ADDR
HTTP_X_FORWARDED_FOR

My local host is not to be confused with: 127.0.0.1


TCP Sockets

Connection-oriented.
Must explicitly socket.close()
Socket class

Example - Query open ports

Port scanner - look at some machines in DCU to find ports that are "open" - providing a service.
Does this by trying to open a socket to that port.



import java.net.*;
import java.io.*;

public class ports 
{
  public static void main ( String[] args ) throws IOException 
  {
    String hostname = args[0];

    Socket s = null;

    try 
    {
      // this is to see if host exists:
      InetAddress ipaddress = InetAddress.getByName(hostname);

//      int p =  21;            // ftp
//      int p =  22;            // ssh / sftp
//      int p =  23;            // telnet
//      int p =  25;            // smtp
        int p =  80;            // http
//      int p = 110;            // pop3
//      int p = 143;            // imap

                try
                {
                  s = new Socket(hostname, p);
                  System.out.println("A server is running on port " + p + ".");
                  s.close();
                }
                catch (IOException e)
                {
                  System.out.println("No server on port " + p + ".");
                }
    }
    catch ( UnknownHostException e )
    {
      System.out.println("Could not find host: " + hostname);
    }

        if (s != null)
        {
                try
                {
                        s.close();
                }
                catch ( IOException ioEx )
                {
                }
        }
  }
}
Can now look for http servers:


$ java ports www.dcu.ie
A server is running on port 80.

$ java ports dgrayweb.computing.dcu.ie
A server is running on port 80.

$ java ports mailhost.computing.dcu.ie
A server is running on port 80.

POP3 servers:


$ java ports mailhost.computing.dcu.ie
A server is running on port 110.

Search for IMAP servers.

Search for ssh servers from outside DCU for:

student.computing.dcu.ie
Caution when scanning ports: Some sites don't like this.
Scanning lots of ports looks like hostile intent.
If firewall blocks a port, program will wait until timeout - could take a while.

what is metadata(annotation) in java





Metadata Annotations
Java EE Connector Architecture 1.6 introduces a set of annotations to minimize the need for deployment descriptors.

The @Connector annotation can be used by the resource adapter developer to specify that the JavaBeans component is a resource adapter JavaBeans component. This annotation is used for providing metadata about the capabilities of the resource adapter. Optionally, you can provide a JavaBeans component implementing the ResourceAdapter interface, as in the following example:

@Connector(
   description = "Sample adapter using the JavaMail API",
   displayName = "InboundResourceAdapter",
   vendorName = "My Company, Inc.",
   eisType = "MAIL",
   version = "1.0"
)
public class ResourceAdapterImpl 
        implements ResourceAdapter, java.io.Serializable {
    ...
    ...
}
The @ConnectionDefinition annotation defines a set of connection interfaces and classes pertaining to a particular connection type, as in the following example:

@ConnectionDefinition(
    connectionFactory = JavaMailConnectionFactory.class,
    connectionFactoryImpl = JavaMailConnectionFactoryImpl.class,
    connection = JavaMailConnection.class,
    connectionImpl = JavaMailConnectionImpl.class
)
public class ManagedConnectionFactoryImpl implements
        ManagedConnectionFactory, Serializable {
    ...
}
The @AdministeredObject annotation designates a JavaBeans component as an administered object.

The @Activation annotation contains configuration information pertaining to inbound connectivity from an EIS instance, as in the following example:

@Activation(
        messageListeners = {JavaMailMessageListener.class}
)
public class ActivationSpecImpl 
        implements ActivationSpec, Serializable {
    ...
    @ConfigProperty()
    // serverName property value
    private String serverName = "";

    @ConfigProperty()
    // userName property value
    private String userName = "";

    @ConfigProperty()
    // password property value
    private String password = "";

    @ConfigProperty()
    // folderName property value
    private String folderName = "INBOX";

    // protocol property value
    @ConfigProperty(
            description = "Normally imap or pop3"
    )
    private String protocol = "imap";
    ...
}
The @ConfigProperty annotation can be used on JavaBeans components to provide additional configuration information that may be used by the deployer and resource adapter provider. The preceding example code shows several @ConfigProperty annotations.

The specification allows a resource adapter to be developed in mixed-mode form, that is the ability for a resource adapter developer to use both metadata annotations and deployment descriptors in applications. An application assembler or deployer may use the deployment descriptor to override the metadata annotations specified by the resource adapter developer.

The deployment descriptor for a resource adapter, if present, is named ra.xml. The metadata-complete attribute defines whether the deployment descriptor for the resource adapter module is complete or whether the class files available to the module and packaged with the resource adapter need to be examined for annotations that specify deployment information.

For the complete list of annotations and JavaBeans components introduced in the Java EE 6 platform, see the Java EE Connector architecture 1.6 specification.

Generics in Java






It would be nice if we could write a single sort method that could sort the elements in an Integer array, a String array or an array of any type that supports ordering.

Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods or, with a single class declaration, a set of related types, respectively.

Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time.

Using Java Generic concept we might write a generic method for sorting an array of objects, then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the array elements.

Generic Methods:
You can write a single generic method declaration that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. Following are the rules to define Generic Methods:

All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example).

Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name.

The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.

A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types not primitive types (like int, double and char).

Example:

Following example illustrate how we can print array of different type using a single Generic method:

public class GenericMethodTest
{
   // generic method printArray                         
   public static < E > void printArray( E[] inputArray )
   {
      // Display array elements              
         for ( E element : inputArray ){        
            System.out.printf( "%s ", element );
         }
         System.out.println();
    }

    public static void main( String args[] )
    {
        // Create arrays of Integer, Double and Character
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

        System.out.println( "Array integerArray contains:" );
        printArray( intArray  ); // pass an Integer array

        System.out.println( "\nArray doubleArray contains:" );
        printArray( doubleArray ); // pass a Double array

        System.out.println( "\nArray characterArray contains:" );
        printArray( charArray ); // pass a Character array
    } 
}
This would produce following result:

Array integerArray contains:
1 2 3 4 5 6

Array doubleArray contains:
1.1 2.2 3.3 4.4 

Array characterArray contains:
H E L L O
Bounded Type Parameters:
There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound.

Example:

Following example illustrate how extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). This example is Generic method to return the largest of three Comparable objects:

public class MaximumTest
{
   // determines the largest of three Comparable objects
   public static <T extends Comparable<T>> T maximum(T x, T y, T z)
   {                      
      T max = x; // assume x is initially the largest       
      if ( y.compareTo( max ) > 0 ){
         max = y; // y is the largest so far
      }
      if ( z.compareTo( max ) > 0 ){
         max = z; // z is the largest now                 
      }
      return max; // returns the largest object   
   }
   public static void main( String args[] )
   {
      System.out.printf( "Max of %d, %d and %d is %d\n\n", 
                   3, 4, 5, maximum( 3, 4, 5 ) );

       System.out.printf( "Maxm of %.1f,%.1f and %.1f is %.1f\n\n",
                   6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) );

       System.out.printf( "Max of %s, %s and %s is %s\n","pear",
         "apple", "orange", maximum( "pear", "apple", "orange" ) );
   }
}
This would produce following result:

Maximum of 3, 4 and 5 is 5

Maximum of 6.6, 8.8 and 7.7 is 8.8

Maximum of pear, apple and orange is pear
Generic Classes:
A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.

As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters.

Example:

Following example illustrate how we can define a generic class:

public class Box<T> {

  private T t;

  public void add(T t) {
    this.t = t;
  }

  public T get() {
    return t;
  }

  public static void main(String[] args) {
     Box<Integer> integerBox = new Box<Integer>();
     Box<String> stringBox = new Box<String>();
    
     integerBox.add(new Integer(10));
     stringBox.add(new String("Hello World"));

     System.out.printf("Integer Value :%d\n\n", integerBox.get());
     System.out.printf("String Value :%s\n", stringBox.get());
  }
}

This would produce following result:

Integer Value :10

String Value :Hello World

Design Patterns in Java





Java Design Patterns
Adopt Adapter 
Software usually consists of a mixture of in-house and purchased software that must work together to produce a seamless user interface. But disparate software packages are not aware of each other's object models, so they can't work together—without adapters. Adapters let objects from unrelated software packages collaborate by adapting one interface to another. Learn how the Adapter design pattern can save you a lot of time and effort by combining disparate software systems. 
David Geary, September 2003

Follow the Chain of Responsibility 
The Chain of Responsibility (CoR) pattern decouples the sender and receiver of a request by interposing a chain of objects between them. In this installment of Java Design Patterns, David Geary discusses the CoR pattern and two implementations of that pattern in the Java APIs—one from client-side Java and the other from server-side Java. 
David Geary, August 2003

Make your apps fly 
Allocating numerous objects can be detrimental to your application's performance. In this installment of Java Design Patterns, David Geary shows you how to implement the Flyweight design pattern to greatly reduce the number of objects your application creates, which decreases your application's memory footprint and increases performance. 
David Geary, July 2003

Façade clears complexity 
The Façade design pattern simplifies complex APIs by providing a simplified interface to a complex subsystem. In this installment of Java Design Patterns, David Geary explores a built-in Swing façade for creating dialog boxes and a custom façade for getting a Swing application off the ground. 
David Geary, May 2003

Simply Singleton 
Sometimes it's appropriate to have exactly one instance of a class: window managers, print spoolers, and filesystems are prototypical examples. Typically, those types of objects—known as singletons—are accessed by disparate objects throughout a software system, and therefore require a global point of access. Of course, just when you're certain you will never need more than one instance, it's a good bet you'll change your mind. 
David Geary, April 2003

An inside view of Observer 
The Observer pattern lets you build extensible software with pluggable objects by allowing communication between loosely coupled objects. In his latest Java Design Patterns column, David Geary explores the Observer pattern, how it's used throughout the Java 2 SDK, and how you can implement the pattern in your own code. 
David Geary, March 2003

A look at the Composite design pattern 
The Composite design pattern lets you treat primitive and composite objects exactly the same. In his latest Java Design Patterns column, David Geary explores how to implement the Composite pattern and how to use it with the Tiles tag library from the Apache Struts application framework. 
David Geary, September 2002

Take command of your software 
The Command pattern lets an application framework make requests of application-specific objects, without the framework knowing the objects' exact type or the application-specific behavior they implement. In his latest Java Design Patterns column, David Geary explores how to use the Command pattern both in client-side Java to attach application-specific behavior to Swing menu items and in server-side Java to implement application-specific behavior with the Apache Struts application framework. 
David Geary, June 2002

Strategy for success 
The Strategy design pattern embodies two fundamental tenets of object-oriented (OO) design: encapsulate the concept that varies and program to an interface, not an implementation. In this article, David Geary shows how to use the Strategy pattern to implement an extensible design. 
David Geary, April 2002

Take control with the Proxy design pattern 
The Proxy design pattern lets you substitute a proxy for an object. In that capacity, proxies prove useful in many situations, ranging from Web services to Swing icons. In this latest Java Design Patterns installment, David Geary explores the Proxy pattern. 
David Geary, February 2002

Amaze your developer friends with design patterns 
Design patterns are proven techniques for implementing robust, malleable, reusable, and extensible object-oriented software. To launch his Java Design Patterns column, David Geary introduces design patterns to Java developers and explores Strategy, Composite, and Decorator -- three common, yet powerful, design patterns employed throughout the JDK. 

The java.text Package





The java.text package is new in Java 1.1. It contains classes that support the parsing and formatting of data. These classes also support the internationalization of Java programs. Internationalization refers to the process of making a program flexible enough to run correctly in any locale. An internationalized program must, however, be localized to enable it to run in a particular locale. The internationalization capabilities in Java are quite significant, especially in this age of the global Internet.

Many of the classes in java.text are meant to handle formatting string representations of dates, times, numbers, and messages based on the conventions of a locale. The Format class is the superclass of all of the classes that generate and parse string representations of various types of data.

The DateFormat class formats and parses dates and times according to the customs and language of a particular locale. By the same token, the NumberFormat class formats and parses numbers, including currency values, in a locale-dependent manner. The MessageFormat class creates a textual message from a pattern string, while ChoiceFormat maps numerical ranges to strings. By themselves, these classes do not provide different results for different locales. However, they can be used in conjunction with ResourceBundle objects from java.util that generate locale-specific pattern strings.

The Collator class handles collating strings according to the rules of a particular locale. Different languages have different characters and different rules for sorting those characters; Collator and its subclass, RuleBasedCollator, are designed to take those differences into account when collating strings. In addition, the CollationKey class optimizes the sorting of a large collection of strings.

The BreakIterator class finds various boundaries, such as word boundaries and line boundaries, in textual data. As you might expect, BreakIterator locates these boundaries according to the rules of a particular locale.

java.lang package






Interfaces in java.lang

Cloneable
Runnable
Classes in java.lang


  • Boolean
  • Byte
  • Character
  • Class
  • ClassLoader
  • Compiler
  • Double
  • Float
  • Integer
  • Long
  • Math
  • Number
  • Object
  • Process
  • Runtime
  • SecurityManager
  • Short
  • String
  • StringBuffer
  • System
  • Thread
  • ThreadGroup
  • Throwable
  • Void


Exceptions in java.lang


  • ArithmeticException
  • ArrayIndexOutOfBoundsException
  • ArrayStoreException
  • ClassCastException
  • ClassNotFoundException
  • CloneNotSupportedException
  • Exception
  • IllegalAccessException
  • IllegalArgumentException
  • IllegalMonitorStateException
  • IllegalStateException
  • IllegalThreadStateException
  • IndexOutOfBoundsException
  • InstantiationException
  • InterruptedException
  • NegativeArraySizeException
  • NoSuchFieldException
  • NoSuchMethodException
  • NullPointerException
  • NumberFormatException
  • RuntimeException
  • SecurityException
  • StringIndexOutOfBoundsException


Errors in java.lang


  • AbstractMethodError
  • ClassCircularityError
  • ClassFormatError
  • Error
  • ExceptionInInitializerError
  • IllegalAccessError
  • IncompatibleClassChangeError
  • InstantiationError
  • InternalError
  • LinkageError
  • NoClassDefFoundError
  • NoSuchFieldError
  • NoSuchMethodError
  • OutOfMemoryError
  • StackOverflowError
  • ThreadDeath
  • UnknownError
  • UnsatisfiedLinkError
  • VerifyError
  • VirtualMachineError

inner classes in java







There are 4 kind of classes that can be defined in a Java program, roughly can be termed as the inner classes.

--  Inner classes provides an elegant and powerful feature to the Java programming language. 
-- These inner classes are referred by different names in different situations. 
-- They are summarized here:
  1. Static member classes
  2. Member classes
  3. Local classes
  4. Anonymous classes

-- The term "nested classes" sometimes refers to these inner classes.

Static member classes

  -- This class (or interface) is defined as a static member variable of another class.
Member classes

--  This is sometimes defined as a non-static member of an enclosing class. This type of inner class is analogous to an instance method or field.

Local classes
-- This class is defined within a block of Java code so like a local variable, it is visible only within that block.

Anonymous classes
-- An anonymous class is a  local class having no name; 
-- Syntactically it combines the syntax required for defining a class and the syntax required to instantiate an object. 

string handling in java





String Handling in JAVA

String Handling is an important part of any programming language.
String
Strings are widely used in JAVA Programming, are a sequence of characters. String Class is defined in java.lang package so it is implicitly available for all programs

String class has following features:-
It is Final class
Due to Final, String class can not be inherited.
It Extends object class.
It implements Serializable, Comparable and CharSequence interfaces.
It is immutable.
It is also a datatype in java

String Example 1:Creating new String
String a=”Ashish”;
String b=new String();
String c=new String(“Ashish”);

String Example 2:Comparing String
String a=”Ashish”;
String b=”Ashish”;
String c=new String(“Ashish”);
if(a==b) System.out.println(“Same reference “);
if(a==c) System.out.println(“Same Reference of A and C “);
else System.out.println(“Not Same Reference “);

There are two ways to create a String object in Java- 
1.Using the new operator. For example,
String str1 = new String("Ashish");.
2.Using a string literal. For example,
String str2="Ashish"; (string literal)

But these both "Ashish" have different reference. So if we compare str1 & str2, this is not equal. because str1 is created using new operator.

This diagram show the difference-




String Class Methods & Example
Click here

StringBuffer Class in JAVA
The java.lang.StringBuffer classes should be used when you have to make a lot of modifications to strings of characters. As,String objects are immutable , so if you choose to do a lot of manipulations with String Objects, you will end up with a lot of abandoned String objects in the String pool.

StringBuffer Example
StringBuffer sb=new StringBuffer(“Hiiii”);
sb.append(“Javacup”);
System.out.println(sb); //HiiiiJavacup

collections framework in java







Collections Framework

Java provides the Collections Framework. In the Collection Framework, a collection represents the group of the objects. And a collection framework is the unified architecture that represent and manipulate collections. The collection framework provides a standard common programming interface to many of the most common abstraction without burdening the programmer with many procedures and interfaces. It provides a system for organizing and handling collections. This framework is based on:

Interfaces that categorize common collection types.
Classes which proves implementations of the Interfaces.
Algorithms which proves data and behaviors need when using collections i.e. search, sort, iterate etc.
Following is the hierarchical representation for the relationship of all four interfaces of the collection framework which illustrates the whole implementation of the framework.

      

During the designing of a software (application) it need to be remember the following relationship of the four basic interfaces of the framework are as follows:


  • The Collection interface which is the collection of objects. That permits the duplication of the value or objects.
  • Set is the interface of the collections framework which extends the Collection but forbids duplicates.
  • An another interface is the List which also extends the Collection. It allows the duplicates objects on different position because it introduces the positional indexing.
  • And Map is also a interface of the collection framework which extends neither Set nor Collection.

Some interfaces and classes of the collection framework are as follows:

INTERFACESCLASSES
Collection Interface
Iterator Interface
Set Interface
List Interface
ListIterator Interface
Map Interface
SortedSet Interface
SortedMap Interface
HashSet Class
TreeSet Class
ArrayList Class
LinkedList Class
HashMap Class
TreeMap Class
Vector Class
Stack Class


Every interfaces and classes are explained next in the roseidia.net java tutorial one by one in the various examples.

Advantage of the Collections Framework:

The collections framework offers developers the following benefits:


  • It increases the readability of your collections by providing a standard set of interfaces which has to be used by many programmers in different applications.
  • It makes your code more flexible. You can make the code flexible by using many interfaces and classes of the collection framework.
  • It offers many specific implementations of the interfaces. It allows you to choose the collection that is most fitting and which offers the highest performance for your purposes.

Interfaces of the collections framework are very easy to use. These interfaces can be transparently substituted to increase the developed application performance.

applets in java


An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java API at its disposal.

There are some important differences between an applet and a standalone Java application, including the following:

An applet is a Java class that extends the java.applet.Applet class.

A main() method is not invoked on an applet, and an applet class will not define main().

Applets are designed to be embedded within an HTML page.

When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user's machine.

A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime environment.

The JVM on the user's machine creates an instance of the applet class and invokes various methods during the applet's lifetime.

Applets have strict security rules that are enforced by the Web browser. The security of an applet is often referred to as sandbox security, comparing the applet to a child playing in a sandbox with various rules that must be followed.

Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

Life Cycle of an Applet:
Four methods in the Applet class give you the framework on which you build any serious applet:

init: This method is intended for whatever initialization is needed for your applet. It is called after the param tags inside the applet tag have been processed.

start: This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other pages.

stop: This method is automatically called when the user moves off the page on which the applet sits. It can, therefore, be called repeatedly in the same applet.

destroy: This method is only called when the browser shuts down normally. Because applets are meant to live on an HTML page, you should not normally leave resources behind after a user leaves the page that contains the applet.

paint: Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser. The paint() method is actually inherited from the java.awt.

A "Hello, World" Applet:
The following is a simple applet named HelloWorldApplet.java:

import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet
{
   public void paint (Graphics g)
   {
      g.drawString ("Hello World", 25, 50);
   }
}
These import statements bring the classes into the scope of our applet class:

java.applet.Applet.

java.awt.Graphics.

Without those import statements, the Java compiler would not recognize the classes Applet and Graphics, which the applet class refers to.

The Applet CLASS:
Every applet is an extension of the java.applet.Applet class. The base Applet class provides methods that a derived Applet class may call to obtain information and services from the browser context.

These include methods that do the following:

  • Get applet parameters
  • Get the network location of the HTML file that contains the applet
  • Get the network location of the applet class directory
  • Print a status message in the browser
  • Fetch an image
  • Fetch an audio clip
  • Play an audio clip
  • Resize the applet


Additionally, the Applet class provides an interface by which the viewer or browser obtains information about the applet and controls the applet's execution. The viewer may:

  • request information about the author, version and copyright of the applet
  • request a description of the parameters the applet recognizes
  • initialize the applet
  • destroy the applet
  • start the applet's execution
  • stop the applet's execution


The Applet class provides default implementations of each of these methods. Those implementations may be overridden as necessary.

The "Hello, World" applet is complete as it stands. The only method overridden is the paint method.

Invoking an Applet:
An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet viewer or Java-enabled browser.

The <applet> tag is the basis for embedding an applet in an HTML file. Below is an example that invokes the "Hello, World" applet:

<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class" width="320" height="120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
Based on the above examples, here is the live applet example: Applet Example.

Note: You can refer to HTML Applet Tag to understand more about calling applet from HTML.

The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width and height are also required to specify the initial size of the panel in which an applet runs. The applet directive must be closed with a </applet> tag.

If an applet takes parameters, values may be passed for the parameters by adding <param> tags between <applet> and </applet>. The browser ignores text and other tags between the applet tags.

Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything that appears between the tags, not related to the applet, is visible in non-Java-enabled browsers.

The viewer or browser looks for the compiled Java code at the location of the document. To specify otherwise, use the codebase attribute of the <applet> tag as shown:

<applet codebase="http://amrood.com/applets"
code="HelloWorldApplet.class" width="320" height="120">
If an applet resides in a package other than the default, the holding package must be specified in the code attribute using the period character (.) to separate package/class components. For example:

<applet code="mypackage.subpackage.TestApplet.class" 
           width="320" height="120">
Getting Applet Parameters:
The following example demonstrates how to make an applet respond to setup parameters specified in the document. This applet displays a checkerboard pattern of black and a second color.

The second color and the size of each square may be specified as parameters to the applet within the document.

CheckerApplet gets its parameters in the init() method. It may also get its parameters in the paint() method. However, getting the values and saving the settings once at the start of the applet, instead of at every refresh, is convenient and efficient.

The applet viewer or browser calls the init() method of each applet it runs. The viewer calls init() once, immediately after loading the applet. (Applet.init() is implemented to do nothing.) Override the default implementation to insert custom initialization code.

The Applet.getParameter() method fetches a parameter given the parameter's name (the value of a parameter is always a string). If the value is numeric or other non-character data, the string must be parsed.

The following is a skeleton of CheckerApplet.java:

import java.applet.*;
import java.awt.*;
public class CheckerApplet extends Applet
{
   int squareSize = 50;// initialized to default size
   public void init () {}
   private void parseSquareSize (String param) {}
   private Color parseColor (String param) {}
   public void paint (Graphics g) {}
}
Here are CheckerApplet's init() and private parseSquareSize() methods:

public void init ()
{
   String squareSizeParam = getParameter ("squareSize");
   parseSquareSize (squareSizeParam);
   String colorParam = getParameter ("color");
   Color fg = parseColor (colorParam);
   setBackground (Color.black);
   setForeground (fg);
}
private void parseSquareSize (String param)
{
   if (param == null) return;
   try {
      squareSize = Integer.parseInt (param);
   }
   catch (Exception e) {
     // Let default value remain
   }
}
The applet calls parseSquareSize() to parse the squareSize parameter. parseSquareSize() calls the library method Integer.parseInt(), which parses a string and returns an integer. Integer.parseInt() throws an exception whenever its argument is invalid.

Therefore, parseSquareSize() catches exceptions, rather than allowing the applet to fail on bad input.

The applet calls parseColor() to parse the color parameter into a Color value. parseColor() does a series of string comparisons to match the parameter value to the name of a predefined color. You need to implement these methods to make this applet works.

Specifying Applet Parameters:
The following is an example of an HTML file with a CheckerApplet embedded in it. The HTML file specifies both parameters to the applet by means of the <param> tag.

<html>
<title>Checkerboard Applet</title>
<hr>
<applet code="CheckerApplet.class" width="480" height="320">
<param name="color" value="blue">
<param name="squaresize" value="30">
</applet>
<hr>
</html>
Note: Parameter names are not case sensitive.

Application Conversion to Applets:
It is easy to convert a graphical Java application (that is, an application that uses the AWT and that you can start with the java program launcher) into an applet that you can embed in a web page.

Here are the specific steps for converting an application to an applet.

Make an HTML page with the appropriate tag to load the applet code.

Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet cannot be loaded.

Eliminate the main method in the application. Do not construct a frame window for the application. Your application will be displayed inside the browser.

Move any initialization code from the frame window constructor to the init method of the applet. You don't need to explicitly construct the applet object.the browser instantiates it for you and calls the init method.

Remove the call to setSize; for applets, sizing is done with the width and height parameters in the HTML file.

Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates when the browser exits.

If the application calls setTitle, eliminate the call to the method. Applets cannot have title bars. (You can, of course, title the web page itself, using the HTML title tag.)

Don't call setVisible(true). The applet is displayed automatically.

Event Handling:
Applets inherit a group of event-handling methods from the Container class. The Container class defines several methods, such as processKeyEvent and processMouseEvent, for handling particular types of events, and then one catch-all method called processEvent.

Inorder to react an event, an applet must override the appropriate event-specific method.

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;


public class ExampleEventHandling extends Applet 
implements MouseListener {

    StringBuffer strBuffer;

    public void init() {
addMouseListener(this);
strBuffer = new StringBuffer();
        addItem("initializing the apple ");
    }

    public void start() {
        addItem("starting the applet ");
    }

    public void stop() {
        addItem("stopping the applet ");
    }

    public void destroy() {
        addItem("unloading the applet");
    }

    void addItem(String word) {
        System.out.println(word);
        strBuffer.append(word);
        repaint();
    }

    public void paint(Graphics g) {
//Draw a Rectangle around the applet's display area.
        g.drawRect(0, 0, 
  getWidth() - 1,
  getHeight() - 1);

//display the string inside the rectangle.
        g.drawString(strBuffer.toString(), 10, 20);
    }

   
    public void mouseEntered(MouseEvent event) {
    }
    public void mouseExited(MouseEvent event) {
    }
    public void mousePressed(MouseEvent event) {
    }
    public void mouseReleased(MouseEvent event) {
    }

    public void mouseClicked(MouseEvent event) {
addItem("mouse clicked! ");
    }
}
Now let us call this applet as follows:

<html>
<title>Event Handling</title>
<hr>
<applet code="ExampleEventHandling.class" 
width="300" height="300">
</applet>
<hr>
</html>
Initially the applet will display "initializing the applet. Starting the applet." Then once you click inside the rectangle "mouse clicked" will be displayed as well.

Based on the above examples, here is the live applet example: Applet Example.

Displaying Images:
An applet can display images of the format GIF, JPEG, BMP, and others. To display an image within the applet, you use the drawImage() method found in the java.awt.Graphics class.

Following is the example showing all the steps to show images:

import java.applet.*;
import java.awt.*;
import java.net.*;
public class ImageDemo extends Applet
{
  private Image image;
  private AppletContext context;
  public void init()
  {
      context = this.getAppletContext();
      String imageURL = this.getParameter("image");
      if(imageURL == null)
      {
         imageURL = "java.jpg";
      }
      try
      {
         URL url = new URL(this.getDocumentBase(), imageURL);
         image = context.getImage(url);
      }catch(MalformedURLException e)
      {
         e.printStackTrace();
         // Display in browser status bar
         context.showStatus("Could not load image!");
      }
   }
   public void paint(Graphics g)
   {
      context.showStatus("Displaying image");
      g.drawImage(image, 0, 0, 200, 84, null);
      g.drawString("www.javalicense.com", 35, 100);
   }  
}
Now let us call this applet as follows:

<html>
<title>The ImageDemo applet</title>
<hr>
<applet code="ImageDemo.class" width="300" height="200">
<param name="image" value="java.jpg">
</applet>
<hr>
</html>
Based on the above examples, here is the live applet example: Applet Example.

Playing Audio:
An applet can play an audio file represented by the AudioClip interface in the java.applet package. The AudioClip interface has three methods, including:

  • public void play(): Plays the audio clip one time, from the beginning.
  • public void loop(): Causes the audio clip to replay continually.
  • public void stop(): Stops playing the audio clip.


To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet class. The getAudioClip() method returns immediately, whether or not the URL resolves to an actual audio file. The audio file is not downloaded until an attempt is made to play the audio clip.

Following is the example showing all the steps to play an audio:

import java.applet.*;
import java.awt.*;
import java.net.*;
public class AudioDemo extends Applet
{
   private AudioClip clip;
   private AppletContext context;
   public void init()
   {
      context = this.getAppletContext();
      String audioURL = this.getParameter("audio");
      if(audioURL == null)
      {
         audioURL = "default.au";
      }
      try
      {
         URL url = new URL(this.getDocumentBase(), audioURL);
         clip = context.getAudioClip(url);
      }catch(MalformedURLException e)
      {
         e.printStackTrace();
         context.showStatus("Could not load audio file!");
      }
   }
   public void start()
   {
      if(clip != null)
      {
         clip.loop();
      }
   }
   public void stop()
   {
      if(clip != null)
      {
         clip.stop();
      }
   }
}
Now let us call this applet as follows:

<html>
<title>The ImageDemo applet</title>
<hr>
<applet code="ImageDemo.class" width="0" height="0">
<param name="audio" value="test.wav">
</applet>
<hr>
</html>
You can use your test.wav at your PC to test the above example.
There was an error in this gadget