OS/2 Warp 4: Developing with Java

From EDM2
Jump to: navigation, search

Reprint Courtesy of International Business Machines Corporation, © International Business Machines Corporation

By Herman Rodriguez, Miguel Sang

As network computers become a reality, Java will play a major role in the presentation of information, exploiting the multimedia dynamics while delivering the content. This article presents the nuts and bolts of Java, describing its technical aspects and providing Java application and applet examples.

DevJava-javad.jpg

An exciting aspect of Java technology is its ability to present a platform-neutral application environment that can exploit Internet technology as a whole and, equally as important, can permeate the appliance and consumer spaces.

As the consumer electronics market focuses on appliances, embedding the Java runtime as a fundamental element provides a standard platform that you can use to create a network of intelligent devices. For example, with Java embedded in your dishwasher's electronics, the start of the wash cycle can "inform" your heater to prepare the adequate amount of water for this task.

Appliance application developers can market platform-neutral Java programs to several hardware vendors, even though they may use different hardware to build their units. The developer's application still runs, and the market is greatly expanded.

Technical Overview

Although Java has the look and feel of C++, it has several key differences:

  • Java forces you to accept object orientation as the programming model.
  • Java eliminates the use of pointers.
  • Java encapsulates arrays in a class structure.
  • Java runtime provides automatic garbage collection; memory management is built in.
  • Java provides built-in multithreading features.
  • Java enforces strong security measures to protect against ill-behaved programs.

Figure 1. Simple Java Application

File name: Hello.java

1:   class Hello
2:   {
3:     public static void main(String argv[])
4:        {
5:          System.out.println("Hello Java!"):
6:        }
7:   }

The Java source program is compiled using JAVAC.EXE. This compilation creates a file made of Java "bytecodes" that represent your program in a way similar to the object code produced by a C or C++ compiler. However, these bytecodes are not machine instructions (or processor-specific instructions); they are commands to the Java interpreter. OS/2 Warp 4 provides a native Java interpreter. There are also Java interpreters ported to Solaris, Windows NT, Windows 95, and other platforms. Java programs run unmodified and without having to be recompiled on any of these platforms.

Java's portability becomes apparent when users connect to the Internet. A Java program runs on any platform that supports a Java-enabled browser. The primary benefit to the user is that your Java program does not have to be installed or configured. The user simply selects a link on a Web page that represents a Java program. The Java-enabled browser requests the program from the remote site and runs it seamlessly.

At runtime, the interpreter resolves symbolic references and determines the storage scheme for each Java class. Although there is a slight performance penalty in runtime reference resolution, a major benefit is that classes can be updated without affecting your code. This benefit is certainly a key feature required in a distributed environment like the Internet.

Java is Robust

DevJava-jav01.jpg

Java creates a reliable environment for running distributed applications. The features that make Java robust include the following:

  • Eliminates pointer manipulation so that memory usage is encapsulated in classes specifically built for that purpose.
  • Maintains runtime integrity by ensuring that distribution and dynamic linking have not introduced errors into the code (in addition to type checking at compile time). The interpreter ensures that bytecodes have not been tampered with and that transmission errors have not modified the code.
  • Eliminates the common problem of out-of-bounds array access attempts in C and C++. Java always catches access to invalid array elements; some are caught at compile time, and others are caught at runtime when computing index values.
  • Supports multithreading by providing synchronization modifiers in the language. At the object level, threaded applications can inherit classes specifically created for that purpose.

Specific threads' priority can be set by applications to suit specific needs, allowing unique modes of preemptive multitasking.

The Object of Every Class

Java provides a completely object-oriented programming environment. The basic Java distribution includes several classes that are grouped into packages. These packages provide the basic building blocks upon which you create your application. These packages are:

  • Language package (java.lang) - Provides the elementary classes for strings, arrays, and elementary data types of the Java language.
  • Utility package (java.util) - Provides support for vectors, stacks, hash tables, encoding, and decoding.
  • I/O package (java.io) - Provides standard input and output (I/O), as well as a file I/O.
  • Applet package (java.applet) - Provides support to interact with the browser.
  • Abstract Window Toolkit (AWT) package (java.awt) - Provides support to control the visual aspects of your application. Objects such as buttons, scroll bars, and fonts are available in this class.
  • Network package (java.net) - Provides the basic support to communicate with peer programs over the network, as well as standard protocols such as Telnet, FTP, and URL access.

With these features in mind, it is time to move to the practical application of Java. We'll start by creating and analyzing the typical "Hello World" program.

Programming in Java

You can create two types of programs with Java: an application and an applet. The main difference between them is the way each program is run. A Java application is a regular program such as a C or C++ program; however, unlike C or C++, a Java application requires an interpreter to run. OS/2 Warp 4 includes a Java interpreter called JAVA.EXE (or JAVAPM.EXE for programs that use the AWT classes).

A Java applet is a more restricted Java program. Because an applet is intended to be delivered over the Internet, it is small and does not have access to all the functions normally available to a regular program. These restrictions give a Java applet the security level required to avoid intentional data corruption and malicious programming, such as viruses.

A Java applet is usually run by a Java-enabled browser, whereas a Java application is usually run by a Java interpreter. OS/2 Warp 4 includes an applet viewer (APPLET.EXE) that allows you to run Java applets without a Java-enabled browser.

Once loaded, the program runs inside a Java virtual machine. The virtual machine is a controlled environment where the Java bytecodes are interpreted and translated into machine language.

A Java Application

Figure 1 demonstrates a simple Java application. Compile the application by entering javac Hello.java to invoke the Java compiler (JAVAC.EXE).

The code produces the Hello.class file, which is run by invoking the Java interpreter. The result is shown in Figure 2. Notice that the .class extension is not required by the interpreter to find the application; it is assumed by the interpreter. Following is a line-by-line analysis of the Hello.java source:

Figure 3. (first) Simple Java Applet

File name: HelloApplet.java

1:	import java.applet.*;
2:	import java.awt.*;
3:	public class HelloApplet extends Applet
4:	{
5:	     public void paint (Graphics objGraphics)
6:	     {
7:	        objGraphics.drawString("Hello Java!" , 10, 40);
8:	        }
9:	}

Figure 4. (second) HTML File to Run Applet

File name: hello.html

1:	{html}
2:	{head}{title}A Java Applet{/title}
3:	{/head}
4:	{body}
5:	{applet code=HelloApplet.class width=200 height=100}
6:	{/applet}
7:	{/body}
8:	{/html}
  • class Hello - Declares a Java class called Hello. The outer curly braces, { and }, define the scope of the code that belongs to the Hello class.
  • public static void main(String argv[]) -- Defines a method. Several Java keywords are used to define a method. In this code example, public indicates that this method can be invoked from any other class; static specifies that this method applies to the class globally, instead of at the instance level; void indicates this method does not return any value; and main is used to define the method to be called when the program is initially run.
  • System.out.println("Hello Java!");
    • Invokes the println method of the PrintStream class. The PrintStream class is instantiated as out in the class named System. The System class is instantiated as System. The Object class is the root of every Java class. In other words, every Java class inherits from the Object class. A semicolon ends all Java statements.

A Java Applet

The code in Figure 3 demonstrates a simple Java applet. To compile the applet, type javac HelloApplet.java at an OS/2 command prompt; it produces a file called HelloApplet.class. To run the applet, use the HTML file shown in Figure 4.

Type applet hello.html at an OS/2 command prompt to run the applet. The screen in Figure 5 displays on your desktop.

Figure 5. Applet Display

Figure 5. Applet Display

Following are the details of the applet source:

  • import java.applet.*; import java.awt.*; - Imports the java.applet and java.awt packages that contain the Applet and Graphics classes respectively. In short, packages are the means by which several different Java classes can be stored together. java.applet refers to the Applet package and java.awt refers to the Abstract Window Toolkit (AWT) package.
  • public class HelloApplet extends Applet - Declares the HelloApplet class. The extends keyword indicates that this class inherits from the Applet class. Java allows only single inheritance, thereby eliminating many of the problems associated with multiple inheritance. Java provides a mechanism called Interfaces to allow some of the functionality available with multiple inheritance.
  • public void paint (Graphics objGraphics) - Declares the paint method. This method is called by the AWT when the applet needs to be redrawn. In this example, when paint is called, it in turn calls:
objGraphics.drawString("Hello Java!", 10, 40); -- Draws the Hello Java! string. 
                                                  The drawString method is located in the Graphic class, 
                                                  of which objGraphics is an instance.

In the hello.html file, the HTML statement {applet code=HelloApplet.class width=200 height=100} contains the HTML keywords applet, code, width, and height.

  • applet declares a Java applet.
  • code declares the full name of the Java applet.
  • width defines the width of the applet window.
  • height defines the height of the applet window.

More Java Applets

To do something useful, an applet must always override at least one of the standard methods. In the previous example, the paint method was overridden to draw the Hello Java! string. A typical applet is more complex. Listed in called sequence, the basic Java methods are:

  • void init() - This method is the first one to be called once the applet is loaded. Variables can be initialized here. Be aware that if this class is inherited by another class, this method can be overridden in that class and, therefore, is never called.
  • void start() - This method tells the applet to start running. It is called every time the applet's HTML page is loaded and is visible on the Web browser or applet viewer.
  • void stop() - This method is called when the applet's HTML page is no longer the current page. This is the place for the applet to suspend any threads it might have.
  • void destroy() - This method is called when the applet is no longer needed. The applet should free any resources and terminate.

As in C++, Java also allows you to specify a class constructor. The constructor is called before any of the methods listed previously and, unlike the init() method, it cannot be overridden. To define a constructor, create a public method in the class with the same name as the class.

The examples in Figures 6 and 7 illustrate the calling sequence for applets.

Example 1 defines a class called HelloMsg. This class uses the String class (located in the java.lang package) to declare a variable that points to an instance of it. The code on lines 5 through 8 defines the constructor for this class. In this example, the constructor creates an instance of the String class and initializes it to the Hello string.

Example 2 defines a class called HelloApplet2 that inherits from the HelloMsg class. In doing so, HelloApplet2 inherits the methods and variables from the HelloMsg class. The constructor for HelloApplet2 (lines 5 through 8) initializes the HelloMsgStr2 class variable to the string " and Welcome to Java!". Notice that the HelloMsg class inherits from the Applet class.

The init method (lines 9 through 12) creates a new String instance and initializes it with the concatenation of the String objects HelloMsgStr (inherited from HelloMsg) and HelloMsgStr2.

Once the applet is loaded and the paint method is called, line 15 displays the content of the String object PrintHelloMsg, which by then will contain the "Hello and Welcome to Java!" string.

Type javac HelloApplet2.java at an OS/2 command prompt to compile HelloApplet2.java (Figure 7) and HelloMsg.java (Figure 6).

Notice that you did not specify HelloMsg.java. The Java compiler automatically searches for the HelloMsg class and will build from the source file if necessary.

Figure 6. Example 1 -- Defining HelloMsg

File name: HelloMsg.Java

1:	import java.applet.*;
2:	public class HelloMsg extends Applet
3:	{
4:	   String HelloMsgStr;
5:	   public HelloMsg()
6:	   {
7:	      HelloMsgStr = new String("Hello");
8:	    }
9:	}

Figure 7. Example 2 -- Defining HelloApplet2

File name: HelloApplet2.java

1:	import java.awt.*;
2:	public class HelloApplet2 extends HelloMsg
3:	{
4:	   String HelloMsgStr2, PrintHelloMsg;
5:	   public HelloApplet2()
6:	   {
7:	     HelloMsgStr2 = new String(" and Welcome to Java!");
8:	   }
9:	   public void init()
10:	   {
11:		PrintHelloMsg = new String(HelloMsgStr + HelloMsgStr2);
12:	    }
13:	    public void paint (Graphics objGraphics)
14:	   {
15:		objGraphics.drawString(PrintHelloMsg, 10, 40);
16:	    }
17:	}

To run the applet, use the HTML file in Figure 8, then type applet hello2.html at an OS/2 command prompt. The screen in Figure 8 displays on your desktop.

Figure 8.

Figure 8.

The HelloApplet2.java and HelloMsg.java code examples demonstrate inheritance as well as the applet calling sequence for the init() and paint() methods and for the class constructor.

Summary

This article describes the characteristics that make Java a simpler programming language to use than the more complex C++. Although a simpler programming language, Java's features (such as being object-oriented) allow it to handle complex programs. These features, along with its platform independence, make Java the ideal platform for Internet programming.

Note: This article was reprinted from Volume 11 of the Developer Connection News. To subscribe to the Developer Connection News, call (800) 6DEVCON (633-8266) from within the U.S., or see our Web site, http://www.developer.ibm.com/DevCon, for worldwide ordering information.