Developing With Java™

From EDM2
Jump to: navigation, search

by Herman Rodriguez and Miguel Sang

Volume 10 of The Developer Connection News briefly described the exciting opportunities that Java provides to application developers. This Volume 11 article presents the nuts-and-bolts of Java, describing the technical aspects that merit the attention of both the programming community and hardware vendors.

An exciting aspect of Java technology is its ability to present a platform-neutral application environment that can permeate the Internet as a whole and, equally important, can permeate the appliance and consumer spaces. As the Network Computer becomes a reality, Java is going to play a major role in the presentation of information content, exploiting the multimedia dynamics while delivering the content.

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

The appliance application developer can market the Java program to several hardware vendors, even though they may have used different hardware to build their units. The developer s application still runs, and the market is greatly expanded.

Technical Overview of Java

Although Java has the look and feel of C++, the key differences include the following:

  • Java forces the acceptance of object orientated programming
  • Java eliminates the use of pointers
  • Java encapsulates arrays in a class structure
  • Java run time provides built-in, automatic garbage collection; you no longer need to worry about memory management
  • Java provides built-in multithreading features
  • Java enforces strong security measures to protect against ill-behaved programs

The Java source program is compiled using JAVAC.EXE. This compilation creates a file made of Java bytecodes. These bytecodes represent your program in a similar way to the object code produced by your C or C++ compiler. However, these bytecodes are not machine instructions (or processor-specific instructions); they are commands to the Java interpreter. The next release of OS/2 provides a native Java interpreter. There are also Java interpreters ported to Solaris, Windows NT, Windows 95, and other platforms. Your Java program runs unmodified on any of these platforms. No recompilation is necessary.

The portability of Java becomes very apparent when connecting to the Internet. The 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 in a seamless manner.

At run time, the interpreter resolves symbolic references and determines the storage scheme for each Java class. Although there is a slight performance penalty in run-time 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

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

  • Eliminating pointer manipulation, so that memory usage is encapsulated in classes specifically built for that purpose.
  • Maintaining run-time 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.
  • Eliminating 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 run-time when computing index values.
  • Supporting multithreading by providing synchronization modifiers in the language. At the object level, threaded applications can inherit classes specifically created for that purpose.

The priority of specific threads 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. Several classes are included in the basic Java distribution and are grouped into packages. These packages provide the basic building blocks upon which you create your application. These packages are:

  • Language package (java.lang): This package provides the elementary classes for strings, arrays, and elementary data types of the Java language.
  • Utility package (java.util): This package provides support for vectors, stacks, hash tables, encoding, and decoding.
  • I/O package (java.io): This package provides standard input and output, as well as a file I/O.
  • Applet package (java.applet): This package provides support to interact with the browser.
  • Abstract Window Toolkit (AWT) package (java.awt): This package provides support to control the visual aspects of your application Objects such as buttons, scrollbars, and fonts are available in this class.
  • Network package (java.net): For communicating with other applications, this package 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 in the real world. We start by creating and analyzing the typical Hello World program. In subsequent articles, we plan to discuss the details of the language and to discuss specific classes and packages you can use in your application.

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 the program is run. A Java application is a regular program, like a C or C++ program However, unlike C or C++, a Java application requires an interpreter to run OS/2 Warp Version 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 OS/2 Warp Version 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

The following code demonstrates a 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:}

This application is compiled by invoking the Java compiler (JAVAC.EXE).

javac Hello.java

The above produces the file Hello class, which is run by invoking the Java interpreter. The result is:

Dev-Java-Fig-1.gif

Notice that the class extension is not required by the interpreter to find the application; it is assumed by the interpreter. A line-by-line analysis of the Hello.java source follows:

  • 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 Java classes will be explained further in subsequent articles.

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 following code demonstrates a 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:}

This applet is compiled by typing the following at an OS/2 command prompt:

javac HelloApplet.java

and it produces a file called HelloApplet.class. To run the applet, the following HTML file can be used:

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>

Type the following at an OS/2 command prompt to run the applet:

applet hello.html

The following is displayed on your desktop:

Dev-Java-Fig-2.gif

The details of the applet source are as follows:

  • 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 class, HelloApplet. The extends keyword is used to indicate that this class inherits from the Applet class. Java only allows 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 Interfaces will be discussed in a future article.
  • 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 string Hello Java! The method drawString is located in the Graphics class, of which objGraphics is an instance.

In the file, hello.html, the HTML statement <applet code=HelloApplet.class width=200 height=100> contains the HTML keywords applet, code, width, and height. Their meanings are:

  • 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 string Hello Java! A typical applet is more complex. Listed in their called sequence, the basic Java methods are:

  • void init()
This method is the very 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. This method 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.

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

The following examples illustrate the calling sequence for applets:

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:}

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

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:}

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 - 8) initializes the class variable HelloMsgStr2 to the string " and Welcome to Java!" Notice that the HelloMsg class inherits from the Applet class.

The init method (lines 9 - 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 will display the content of the String object PrintHelloMsg, which by now will contain the string Hello and Welcome to Java!

To compile HelloApplet2.java (example 2) and HelloMsg.java (example 1), type the following at an OS/2 command prompt:

javac HelloApplet2.java

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

To run the applet, use the following HTML file:

File name: hello2.html

<html>
<head><title>A Java Applet</title>
</head>
<body>
<applet code=HelloApplet2.class width=300 height=100>
</applet>
</body>
</html>

and then type the following at an OS/2 command prompt

applet hello2.html

The following will be displayed on your desktop:

Dev-Java-Fig-3.gif

The HelloApplet2.java and HelloMsg.java code examples demonstrated the following:

  • The applet calling-sequence for the init() and paint() methods and for the class constructor
  • Inheritance

Summary

This article described the different characteristics of Java that make it a simpler programming language to use than the more complex C++. Although Java is a simpler programming language, its 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.

Look for in-depth descriptions and applications of the Java classes in future issues of The Developer Connection News, and stay in touch with the latest news about Java from our Web site at http://ncc.hursley.ibm.com/javainfo.

Footnote

  • Solaris and Java are trademarks of Sun Microsystems, Inc.; Windows NT and Windows 95 are trademarks of Microsoft Corporation.
Note
The DevCon for OS/2 CD contains the Java Development Kit (JDK) that will be included with OS/2 Warp Version 4. This Toolkit contains the Java run time, development tools and libraries, and sample programs. You can download the Toolkit from the DevCon CD and install it on OS/2 Warp Version 3. Because the Toolkit is being continually updated, check our Web site for the most up-to-date version http://ncc.hursley.ibm.com/javainfo.

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