Chapter 6

Java for Visual Baisc Programmers


CONTENTS


At first glance, the Java language may seem entirely foreign to Visual Basic programmers, but both languages share a number of features. This chapter is provided as a resource for experienced Visual Basic programmers who are interested in learning to develop applications using Java. After a short period of time, Visual Basic developers will see that the language provides them with a new wealth of information and tools that were previously unavailable to them. However, there are tradeoffs (as there always are!). Special attention will be paid to major differences between Java and Visual Basic in order to provide the Visual Basic developer with the skills needed to begin programming in Java.

Visual Basic versus Java, or Object-Based versus Object-Oriented

To compare these two powerful languages, we must first make a decision: what should we look at first? Obviously, the syntax of every programming language is completely different. However, because these two languages implement different methodologies, a study of syntax will be delayed until later on in the chapter.

The argument can be made that most modern programming languages can be separated into several major groups. These range from object-oriented to what will be called "object-based" to standard procedural languages. Figure 6.1 shows some popular languages and which groups they roughly conform to.

Figure 6.1 : Scale of modern programming languages.

Because syntax (where to put semicolons, and so on) is a relatively minor issue, the initial emphasis will be placed on understanding exactly what the term "object-oriented" means.

Object-oriented languages enable the programmer to create programming objects that can be reused within a single application or across multiple applications. Java refers to these objects as a class. Classes are user-defined data types that contain both data and methods. Listing 6.1 shows a sample pseudo-class named Auto.


Listing 6.1. A sample Java class named Auto.
class Auto
{
   int Number_Of_Doors;
   int Number_Of_Seats;
   boolean Radio;
   int    Year;
   String  Model;
   float GetGasMileage();
   void Accelerate();
   void Stop();
}

As you can see, this class Auto contains data (Number_Of_Doors, Number_Of_Seats, Radio, and Year) as well as methods (GetGasMileage, Accelerate, and Stop). Some people like to think of these as "nouns" and "verbs." Visual Basic enables the programmer to create objects that mix data and member functions. For example, by building a form with a text field and a button on it, the programmer has just built an object. This object can be referenced by other objects and reused across multiple applications. This is why Visual Basic is said to be object-based and not procedural. So, what does it take to qualify as object-oriented?

For a language to be object-oriented, it is generally accepted that it should have several primary features:

Encapsulation

Encapsulation is the process of encapsulating data and operations within a manageable interface. The class Auto meets this description fully. If a programmer wanted to instantiate (create) a new Auto for use in his program, he would simply add a member variable of type Auto. Object-oriented languages also allow the class creator to limit access to data and operations within the class. Some data and operations within each class are considered private or "for internal use only." This allows the interface of that class to be controlled for outside use.

Inheritance

Inheritance is the process of deriving new objects from existing objects. This allows the class developer to reuse code that has already been created for the parent (or base) class. Here object-based and object-oriented languages begin to differ. In Visual Basic, for example, once an "object" within the program is created, the programmer is severely limited if he would like to inherit from it. However, in Java we can extend classes as much as necessary. Unlike C++, however, Java will only allow a class to have one parent. This is known as "single inheritance." As an example, the class Truck shown in Listing 6.2 demonstrates inheritance in Java.


Listing 6.2. The Truck class inherits from Auto.
class Truck extends Auto
{
   boolean Four_Wheel_Drive;
   Color   color;
}

This code means that class Truck was designed to be a "child" of class Auto. Therefore, it will inherit all of the public data and methods that exist in the Auto class.

Polymorphism

Polymorphism is defined as "the occurrence of different forms, stages, or types in individual organisms or in organisms of the same species." This essentially means that although the Truck class now inherited all of the data and methods from Auto, it is free to reimplement them as it chooses. You could extend Truck as shown in Listing 6.3.


Listing 6.3. Adding to the Truck class.
class Truck extends Auto
{
   boolean Four_Wheel_Drive;
   Color   color;
   void Accelerate();
}

The purpose of the Accelerate function in the Truck class might be different (for instance, the acceleration speed might be affected if Four_Wheel_Drive is on). Therefore, any time that any other class or method calls the Truck.Accelerate method, the Truck's Accelerate method will be called, not Auto's. (This is true even if class Auto's method GetGasMileage() called Accelerate().)

Comparing ActiveX to Java Classes

When Microsoft introduced the VBX for use within the Visual Basic programming environment, it created an entire industry of component manufacturers. The VBX standard was straightforward and allowed developers to implement encapsulation of distributable programming tools. Each VBX/OCX implements its own properties and methods and allows the programmer to trap events. Although OCXs (now called ActiveX controls) are implemented using Microsoft OLE, these controls still appear to the developer as a set of properties, methods, and events encapsulated in one single programming object.

A Java class allows developers some advantages over an ActiveX control. Ignoring for the moment various features built into the language such as threading and exception handling, Java classes fully support inheritance and polymorphism. How important is this? Currently, hundreds of Java class source files are freely available on the World Wide Web. This list grows daily, and it is growing quickly. Java developers envision a world where Java class clearinghouses are available to quickly download classes that can be extended by individual developers. In addition to this, various third-party Java class libraries are already appearing for the support of various operations such as multimedia, networking, and database access. All of this code is completely reusable and extensible (not to mention platform-independent!).

When a Java class is downloaded from a Web server, it is able to communicate freely with the server that it was downloaded from. This is extremely useful for database access, running CGI scripts, or retrieving additional classes. ActiveX controls, meanwhile, are allowed to communicate with any machine containing Distributed Component Object Model (DCOM) objects. ActiveX controls are also basically allowed full access to the user's system, unlike Java applets, which are restricted.

ActiveX controls do have some distinct advantages, however. Any ActiveX container application can communicate with and display an ActiveX control within its window. This means that Web browsers that are ActiveX-enabled (such as Microsoft Internet Explorer 3.0) will be able to display Excel spreadsheets directly on an HTML page. ActiveX controls uploaded to a user's Web browser can also communicate with any application that supports COM (Component Object Model) interfaces.

Currently, it appears that Microsoft intends to wrap Java classes with an ActiveX layer to allow Java developers to take advantage of the features mentioned here. This will be done through the magic of the Microsoft Windows Virtual Machine for Java and the underlying Component Object Model.

Understanding Java Program Flow

One of the biggest hurdles for non-object-oriented developers to clear is simply understanding exactly what is going on within an object-oriented application. At times, it appears that methods are being called by some invisible force within your computer. GUI environments such as Windows, Macintosh, and Motif just add to this apparent state of confusion because operating system events are constantly being funneled to the application responsible for trapping those events.

The Applet Life Cycle

Think about what is actually required to create a simple Visual Basic form. The form is first created, and any controls that need to be added to it are done at this time. By default, this form is automatically created and shown when the application is run. How does this happen? As you might expect, there is a lot more going on in the background than meets the eye.

The first thing you must understand is how applications run in multitasking operating environments. The Windows environment continually handles messages from a variety of hardware and software sources. It then in turn "forwards" these messages on to each application that is currently "listening." Your application actually has a single entry point that Windows first calls. The basic operations that go on inside this entry point look something like this (please pardon the extreme pseudo-code!):

Entry Point HEY_WINDOWS!(int MESSAGE)
{
/* Process all of the messages your application needs */
if MESSAGE = FORM_CREATE then...
else if MESSAGE = FORM_SHOW then...
else if MESSAGE = FORM_DESTROY then...
...
}

As you can see, Visual Basic provides an easy-to-use GUI over the top of these low-level events. By clicking on a form's events screen, you will see a simple column of events that the Visual Basic designers chose for your form to handle. Experienced Visual Basic programmers know that you can actually process any Windows event you choose to handle, but this set of events is the most commonly used.

C++, Delphi, and Visual Basic programs all use this message-passing system in the exact same ways. What is interesting about all three of these is the way that the respective languages allow designers to hide implementation details from application developers. The Java language is an extension of this methodology. However, instead of the Windows operating system handling messages and passing them directly to a Visual Basic application, programmers in Java receive their GUI messages from something called the Advanced Windowing Toolkit (AWT). For more detailed information on what is contained in the AWT, see Chapters 7, "Developing Java Applets," 8, "Developing Java Applications," and 28, "Package java.awt." The AWT is a set of Java classes that use data and methods to encapsulate common GUI functionality.

Java applets and applications inherit from the AWT directly. Each Java applet can implement what are known as lifecycle methods to control the starting, stopping, and ending of the applet's "life."

The flow of a Java application can best be understood by stepping through one line by line. Listing 6.4 shows the entire contents of the MouseTrack sample application provided with the JDK. Figure 6.2 shows this applet running within the Netscape Web Browser. MouseTrack notifies the player if the mouse-click missed the square, and plays a tune if the player was successful. As can be seen in the following short amount of code, there is quite a bit of work being done here, including screen drawing, mouse-click handling, and the playing of sound files.

Figure 6.2 : The Mouse Track application.


Listing 6.4. The JDK sample application MouseTrack.
1:  import java.awt.Graphics;
2:  import java.lang.Math;
3:
4:  public class MouseTrack extends java.applet.Applet {
5:
6:      int mx, my;
7:      int onaroll;
8:
9:      public void init() {
10:         onaroll = 0;
11:         resize(500, 500);
12:     }
13:
14:     public void paint(Graphics g) {
15:         g.drawRect(0, 0, size().width - 1, size().height - 1);
16:         mx = (int)(Math.random()*1000) % (size().width -
     (size().width/10));
17:         my = (int)(Math.random()*1000) % (size().height -
     (size().height/10));
18:         g.drawRect(mx, my, (size().width/10) - 1, (size().height/10) - 1);
19:     }
20:
21:    /*
22:     * Mouse methods
23:     */
24:     public boolean mouseDown(java.awt.Event evt, int x, int y) {
25:         requestFocus();
26:         if((mx < x && x < mx+size().width/10-1) &&
     (my < y && y < my+size().height/10-1)) {
27:             if(onaroll > 0) {
28:                 switch(onaroll%4) {
29:                 case 0:
30:                     play(getCodeBase(), "sounds/tiptoe.thru.the.tulips.au");
31:                     break;
32:                 case 1:
33:                     play(getCodeBase(), "sounds/danger,danger...!.au");
34:                     break;
35:                 case 2:
36:                     play(getCodeBase(), "sounds/adapt-or-die.au");
37:                     break;
38:                 case 3:
39:                     play(getCodeBase(), "sounds/cannot.be.completed.au");
40:                     break;
41:                 }
42:                 onaroll++;
43:                 if(onaroll > 5)
44:                     getAppletContext().showStatus("You're on your way to
     THE HALL OF FAME:" + onaroll + "Hits!");
45:                else
46:                    getAppletContext().showStatus("YOU'RE ON A ROLL:"
     + onaroll + "Hits!");
47:             }
48:             else {
49:                 getAppletContext().showStatus("HIT IT AGAIN! AGAIN!");
50:                 play(getCodeBase(), "sounds/that.hurts.au");
51:                 onaroll = 1;
52:             }
53:         }
54:         else {
55:             getAppletContext().showStatus
     ("You hit nothing at (" + x + ", " + y + "), exactly");
56:             play(getCodeBase(), "sounds/thin.bell.au");
57:             onaroll = 0;
58:         }
59:         repaint();
60:         return true;
61:     }
62:
63:     public boolean mouseMove(java.awt.Event evt, int x, int y) {
64:         if((x % 3 == 0) && (y % 3 == 0))
65:             repaint();
66:         return true;
67:     }
68:
69:     public void mouseEnter() {
70:         repaint();
71:     }
72:
73:     public void mouseExit() {
74:         onaroll = 0;
75:         repaint();
76:     }
77:
78:     /**
79:      * Focus methods
80:      */
81:     public void keyDown(int key) {
82:         requestFocus();
83:         onaroll = 0;
84:         play(getCodeBase(), "sounds/ip.au");
85:     }
86: }

As can be seen by examining the code listing for this applet, there is quite a bit of work going on here. Events are being trapped, multimedia work is being done, and objects are being painted on the screen. Examining each section of code should allow the reader to gain an appreciation for the power of the Java language.

In lines 1 and 2, MouseTrack imports the AWT's Graphics class and a Math class for calculation purposes. This operation is never done in Visual Basic because inheritance is not allowed. In other words, when an object is declared as type Form, the Visual Basic compiler automatically knows what code to go grab in order to compile. In an object-oriented system, MouseTrack could be the child of any number of classes. However, because it is an applet, it must inherit directly, or indirectly, from Applet.

In line 4, MouseTrack is declared to inherit from the java.applet.Applet class. By default, this identifies this class as the main class of this application.

In lines 6 and 7, member variables are declared. These variables are visible to everything inside the class. In addition, any other application that created a MouseTrack class within it could have access to these variables.

In line 9, the init() method is declared. By inheriting from the Applet class, each applet inherits four "life-cycle" functions: init(), start(), stop(), and destroy(). Init() is called once after an applet is initially loaded.

In lines 10 and 11, the applet is initialized. Note the resize() member call. Don't be confused just because this method isn't declared within this class. The Resize method is inherited from the Applet class.

In line 14, there is another "magic" method call. Where is this coming from? Notice that nowhere in this entire class is the paint() method actually invoked. However, the repaint() method is called in several situations. The paint() method is called whenever the AWT thinks the window needs to be redrawn, or when a repaint() is requested.

Lines 15 through 18 are used to draw the square at random locations on the screen. Note the use of the Math.random() method here. This is why the java.lang.Math class was imported on line 2.

In line 24, the mouseDown method is called whenever the AWT detects a mouse click over this applet's screen area.

In line 25, the requestFocus() method is called. This method is equivalent to Visual Basic's SetFocus().

In lines 26 through 42, some checks are done to determine whether the user successfully clicked inside the square. What is especially interesting is the play() call in lines 30, 33, 36, and 39. At first glance, this call simply plays a sound file depending on the frequency of the user's hits. However, note the call getCodeBase(). This instructs the play function to retrieve the sound file from the applet's base location. In other words, if the applet was retrieved from a Web server in Tokyo, play the sound file located there. In one function call, you have reached across the world, retrieved a sound file, and played it on a user's computer…platform notwithstanding. This type of functionality would have been unimaginable a couple of years ago, but such is the pace of change.

In lines 43 through 61, depending on the user's hit count, several messages are displayed. The showStatus() method will print the message in the appletContext's status window. With most Web browsers, this message will be displayed in the lower-left corner status window (see Figure 6.2 where the text "Applet MouseTrack running" is displayed).

In line 63, mouseMove() is called whenever a MouseMove message is generated.

In lines 64 through 66, the mouseMove() method forces a repaint every three units (probably pixels). By examining the contents of the paint() method, you can see that this will redraw the square on the screen.

In line 69, the mouseEnter() method is called whenever the mouse cursor enters the screen area of this applet. This function also forces a repaint.

In line 73, the mouseExit() method is called whenever the mouse leaves the screen area of the applet. This function will force a repaint and reset the user's score.

In lines 81 through 86, the keyDown() method is called whenever any key is hit. The applet will request focus and, once again, a sound will be played to notify the user.

This applet may be much simpler than a typical Visual Basic form, but it provides some useful illustrations. Hopefully, the Visual Basic developer will see that the overall development goal remains the same. GUI events still need to be handled, and many of the user interface elements remain the same. Object-oriented programming is a skill that Visual Basic developers will need to acquire, but Windows application development skills do provide valuable insight into the Java AWT.

Language Features and Syntax

It is now time to compare basic features of the Java language versus features of the Visual Basic language. The first item to be examined is data types.

Data Types

Java contains a small set of basic language types. (Ignore for now the fact that each new object declared in Java is a new "temporary" data type.) Here are the types:

boolean-Can be true or false
byte
-8-bit signed quantity
short-16-bit signed quantity
int-32-bit signed quantity
float-32-bit floating-point value
double-64-bit floating-point value
long-64-bit signed quantity
char-16-bit Unicode character

Listed next are the Visual Basic basic data types. Next to each VB data type is the equivalent (if any) Java data type:

Integer-16-bit signed quantity; equivalent to short.
Long-32-bit signed quantity; equivalent to int.
Single-32-bit floating-point value; equivalent to float.
Double-64-bit floating-point value; equivalent to double.
Currency-64-bit floating-point value limited to four decimal places; there is no Java equivalent, although a Currency class could be defined (and undoubtedly will be with a full set of properties and methods).
String-8-bit character; although the Java char type appears to be equivalent, caution should be used here. Note that the Java char type is actually a Unicode character, whereas the Visual Basic String makes use of the ASCII characters. There are Java functions that can be used to convert Unicode characters to their ASCII values, and vice versa.
Byte-8-bit unsigned quantity; no Java equivalent.
Boolean-16-bit value used to store True or False; equivalent to boolean.
Date-64-bit value; Visual Basic automatically converts this number to represent a date between January 1, 100 and December 31, 9999. There is no Java basic type equivalent, although as with Currency, it would be relatively easy to build a date class.
Object-32-bit Object reference value; no Java equivalent, unless the class keyword is considered.
Variant-16 bytes (8 bits/byte) plus 1 byte for each character; no Java equivalent.

Declaring Variables

Variables are declared in Visual Basic using the dim keyword. To declare an Integer variable within a function, the following syntax is used:

dim x As Integer

Java has no keyword that designates a variable being defined. Instead, the following syntax is used:

<data type> <variable_name>;

To repeat this example, an integer variable would be declared in Java as follows (keep in mind that Java is case sensitive!):

int x;

What is completely different about Java, however, is the fact that there are no global variables. Every variable and method in Java must be declared inside some class. This forces everything to be stored and referenced as an object, thus enforcing the object-oriented paradigm.

Any object in Java can be stored as an array of that object. This can be done in three steps:

  1. Declaring the array of objects using the syntax <data type> <variable_name>[];
  2. Example: int group[];
  3. Creating a new array object. Although the preceding statement declared a new array *object, it must actually be initialized in memory using the new operator:
  4. Int[] group = new int[50];
  5. Filling the array with values. This can be done using standard array notation:
    Group[15] = 304;

Programming Constructs

All modern programming languages contain programming constructs such as for and while loops and if…then branches. Visual Basic and Java are no exception. This section provides a comparison of the primary differences between the control structures of the two languages.

Visual Basic supports the following decision structures:

If...Then
If...Then...Else
Select Case

The If…Then Structure

The syntax for producing a Visual Basic If…Then structure is the following:

For a single-line statement:

If condition Then statement

For multiple statements:

If condition Then
  
statements
End If

To add an additional Else block to the preceding structure, the syntax looks like this:

If condition1 Then
  
[statementblock1]
[ElseIf condition2 Then
  [statementblock2]]...
[Else
  
[statementblock3]]
End If

Java greatly simplifies this construct with the following syntax:

if condition1 {
  [statementblock1]
}
else if condition2 {
  [statementblock2]
}
else {
  [statementblock3]
}

The Select Case (or switch) Structure

To provide an alternative to many multiple If…Then structures, most languages provide a mechanism of selectively executing blocks of code depending on the value of some variable.

In Visual Basic, you can do this by creating a Select Case structure. Here's the syntax:

Select Case testexpression
  [Case expressionlist1
    [statementblock1]
  [Case expressionlist2
    [statementblock2]
  .
  .
  .
  [Case Else
    
[statementblockn]
End Select

In Java, this construct is known as a switch statement (similar to C/C++). The testexpression must be a byte, char, short, or int. Its syntax is just like C's:

switch (testexpression) {
  [case expressionlist1:]
    [statementblock1]
   break;
  [case expressionlist2:]
    [statementblock2]
   break;
  .
  .
  .
  default:
    
[statementblockn]
  break;
}

The for Loop

For loops are used to execute a group of statements a set number of times. Both Visual Basic and Java provide a for loop, but there are differences between the two. In Visual Basic, the for loop has the following properties:

For counter = start To end [Step increment]
  statements
Next [counter]

Visual Basic allows the programmer to set the start and ending value of the variable counter as well as set the Step increment. Here is the Java for loop:

for (counter = start; booleanexpression; expression) {
  statements
}

There are several subtle differences between the Java for loop and that of Visual Basic. The Java for loop allows the programmer to provide an expression as opposed to the Visual Basic increment. This expression could be a call to a method or, as in VB, the programmer could simply increment or decrement a value. In addition to that, Java allows a variable to be declared in the for loop. (See Listing 6.5 for an example.)


Listing 6.5. Example of variable initialization in a Java for loop.
for (int counter = 1; counter < 99; counter ++) {
     /* statements */
}

The variable declared in the for loop cannot be used outside of that loop, however. (This is yet another example of a potential error-causing language feature that the Java designers have removed!)

The while and do…while Loops

Visual Basic and Java provide nearly identical while and do…while loops. The do loop is used to execute a group of statements an unknown amount of times (until the condition returns true). The do…while loop executes the group of statements at least once before testing the condition. The syntactical differences will be shown here.

In Visual Basic:

Do While condition
  statements
Loop
Do
  statements
Loop While condition
In Java:
while (condition) {
  statements
}
do {
  statements
} while (condition);

Language Features Missing from Visual Basic

There is some similarity between Visual Basic and Java (particularly in the area of GUI programming), but there are some language features in Java that just are not available using Visual Basic. All of these topics will be discussed in greater detail later in this book; however, they will be touched on now so that the Visual Basic programmer is aware of the differences.

Threads

32-bit Windows developers are perhaps familiar with the concept of multithreaded programming. A thread is a single self-contained set of states of execution of a program. A multithreaded environment (or language) allows multiple threads to run simultaneously (in parallel). In other words, threads allow applications to execute simultaneous operations at the same time. This is most often seen in applications where the display is being updated with some type of graphics while the application is performing some type of computation in the background. (See the JDK's Animator example.) Java applets and applications that take advantage of threading can be identified easily because they implement the Runnable interface. Implementing the Runnable interface can be thought of as opening a window into Java's threading capabilities.

It should be noted that on single-processor machines, both threads are not actually executing concurrently. The execution of the threads will switch between the two at regular intervals. Using a machine with multiple processors, it is possible to split the threads off and run them at the same time. This type of operation is operating-system dependent.

Networking

The java.net package (see Chapters 26, "Network-Aware Programming," and 33, "Package java.net") provides the Java programmer with a full complement of networking capabilities using both HTTP (the World Wide Web protocol) and sockets. Sockets were originally implemented for UNIX. They allow the programmer to open a pipe to another machine (or to their own machine, if so desired) for passing data back and forth. Entire books have been written on socket programming, so we won't go into much detail here. Suffice it to say, however, that the Java networking classes are platform-independent and will continue to support open, standards-based protocols. These classes also allow Java applets to do things like call Web pages up in a browser and stream data to and from the client computer over the Internet.

Exception Handling

The ability to handle application exceptions is a powerful feature that is common to many languages including C++, Ada, and Object Pascal. An exception is any type of condition that prevents a program from continuing in its current state. Without exception handling, the program would either crash or exit at that point. Java allows this exception to be "caught" and handled appropriately. More information on exception handling can be found in Chapter 22, "Exception Handling."

Summary

Obviously, the overall programming paradigm for Java is entirely new. A vision of a highly networked, message-handling programming language is (even for software!) a relatively new idea. Therefore, the idea of applets and networking built into the core language is something new for developers of all languages, not just Visual Basic. Visual Basic developers should not look at Java as some new technology that is leaving them behind. Because the language is so new (and its potential unrealized), Visual Basic developers will undoubtedly soon find tools that allow these two languages to interact. James Gosling, creator of Java and a Sun Microsystems vice-president, has even mentioned the possibility of a Java Virtual Machine that understands the Visual Basic language. Basically, it is important that all software developers understand what Java is and how it could affect their current day-to-day work.