Is Java for Visual Basic Programmers?

From EDM2
Jump to: navigation, search

by James W. Cooper

I believe more PC programs are written in Visual Basic (VB) than in all other languages combined. Is now the time for VB programmers to move to new ground? Let's look a little at Java and see how it compares.

Unless you've been locked in a vault working on top secret programs for the last year, you couldn't have missed the buzz that Java created when Sun, Microsoft and IBM stated their positions on this new programming language. It's easy to let the hoopla and fanfare obscure the real technical issues. If all the fuzz-phrases have left you as weary as a dust ball under the divan, let's sweep up the fuzz and look at Java again as User Interface (UI) programmers do.

If you're a Visual Basic programmer, you are used to working in a powerful, interactive environment with a good GUI builder, reasonable debugging tools and a rapid application development (RAD) environment. Using VB (and VisualAge Basic), you can move a few controls around on the screen, click on a couple of places, add two or three lines of code, press Run, and have a full-fledged application in just a few minutes. I call this the seductive appeal of VB: there is just no other way to build a professional looking application so quickly.

And while lots of programmers came to VB; figuring it as a prototyping tool, they stayed in the fold, because they soon found out that they could build complete, sophisticated applications there in a very short period of time.

Before we take a look a Java, let's experience that seductive appeal for ourselves, by building a simple program to convert Fahrenheit temperatures to Celsius and vice-versa. We start up Visual Basic and use the GUI builder to lay out the following simple program:

Vb-java1.gif

Figure 1. A simple Visual Basic program for converting temperature

Now, let's write the code:

   Private Sub Compute_Click()
   Dim temp As Single, newtemp As Singl 
   temp = Val(TempEntry.Text)          'get the text field
   If Fahr.Value Then
      newtemp = temp * 9 / 5 + 32      'convert to Fahrenheit
   Else
      newtemp = 5 * (temp - 32) / 9    'convert to Celsius
   End If 
   result.Caption = Str$(newtemp)      'put result in label
   End Sub 
   Private Sub Quit_Click()
   End'exit when Quit is clicked
   End Sub

And that's the whole program.

Great, but that was VB and this is supposed to be a Java article. What about the disadvantages of VB? Well, here goes:

  • VB only works on Windows platforms
  • VB is not particularly object oriented
  • VB does not provide any way to connect to networks or the Internet
  • VB is not multithreaded or multitasking

By contrast, we'll see that:

  • Java works on virtually any operating system
  • Java is 100 percent object oriented
  • Java has built-in classes for connection to web servers and to TCP/IP sockets
  • Java implements multithreading very effectively

In addition, you can derive or subclass new Java visual controls from existing ones in a completely general way. If that widget doesn't have the function you want, you can derive a new widget from it that does.

Building a Java Temperature Program

Java allows you to do the same kind of things and build the same sort of interfaces. In fact, there are now a plethora of GUI building programs available that help you write elegant visual applications, which will then run on any platform. Once you have constructed the GUI, shown in Figure 2, you write pretty much the same code.

Vb-java2.gif

Figure 2. The Java version of our temperature conversion program

   public void clickedCompute()
     {
       float temp, newtemp;//declare variables 
       temp = new Float(TempEntry.getText()).floatValue();
        if (Fahr.getState())
           newtemp = 9 * temp / 5 + 32; //convert to Fahrenheit
        else
           newtemp = 5 * (temp - 32) / 9; //or to Celsius 
       //put the computed result in the &result8 label
       result.setText(new String().valueOf(newtemp));
     }

This is really pretty nice. The same kind and style of code when a "click" event occurs. Almost as seductive as VB, but how did we produce that GUI?

We built the GUI using a commercial GUI builder and added the code above. The difference is that we could have used any of 5 or 6 different GUI builders from different vendors to accomplish this job.

Some of the most popular of these GUI builders are Symantec's Visual Cafe, Sun's Java Workshop, Penumbra's Mojo, and Microsoft's Visual J++, with Borland's forthcoming Open JBuilder and IBM's forthcoming VisualAge for Java also is likely to be in the running. You will note that I just listed six competing vendors who are all giving strong support to Java tools. This means the industry is moving rapidly, with vendors falling over each other in the race to provide better tools. Such competition can only be good for all programmers, and for all of the companies as well. Java is not a single vendor's closed platform: it's everyone's platform for new development.

Cross Your Platforms Before You Come to Them

Let's reemphasize here that programs like this simple TempCalc application can be developed on any platform or operating system and compiled there. There is no recompilation needed in Java: the same binary code runs identically on all platforms. I doubt you can make that statement about (or in) any other language. This works in Java by each platform running a program called the Java Virtual Machine (JVM), which executes the binary code for that platform.

But this is interpreted code. Shouldn't it be slow? Well guess what, VB is interpreted code, too, and its performance has not been questioned in years, primarily because in both cases, user interfaces spend most of their time waiting for the user. There were a few cases where Java was slow in early editions, but new virtual machine code, called "just-in-time" (JIT) compilers, has pretty much overcome this limitation.

But, Do You Object Yet?

Java is a completely object-oriented language. Learning Java gives you the opportunity to begin the transition to object-oriented thinking and programming in the most painless possible way. Variables in Java can be any of the common primitive types such as integer, float, and Boolean, but the most important variables are actually objects. You can use a number of predefined objects like the String object (or class) and you can easily create objects yourself.

Perhaps you have had some experience in object-oriented (OO) programming before in C++ or Smalltalk, but have never taken it up as a major part of your work. If so, Java is much easier to learn than any other OO language, because it is much simpler. Java has a syntax like C++ and C, but several confusing parts of these languages are missing. Most important, Java has no pointers. Not only do C programmers struggle to understand how to use pointers properly, even experienced programmers misuse them frequently, leading to catastrophic program crashes as well as subtle, annoying bugs.

OK, so Java is C-like without pointers, but what about these objects? Just what is an object? Objects are rather like the structs we use in C and the TYPEs we define in Visual Basic, in that they contain data. They also are like modules, since they contain functions as well. Some of these functions are meant to be used publicly and some are meant only for internal use within the object. Java allows you to distinguish these by making some functions public and others private. Java and most other OO languages refer to the functions inside an object as methods. Don't let that throw you off, these are still functions.

The data that an object operates on should nearly always be private. When you create an object, you may feed it some data, but how it stores that data and how it performs operations on that data is completely hidden inside the object. This is called information hiding and is one of the most important parts of OO programming.

In Java, objects are called classes. These classes are rather like data types in VB and C, in that you have to create variables of those types.

So let's create a temperature class. We don't have to know what kind of internal representation it uses or how it converts. All we know is that this class will hold a temperature and return it in any form requested. We declare the class as follows:

   class Temperature
     {
     private float tempval;//temperature is stored here

<(code> Then we declare methods for storing strings representing Fahrenheit and Celsius data: <code>

   public void setFahr(String fahr)
     {
     float t = makeFloat(fahr);//convert to float
     tempval = 5 * (t - 32) / 9;//and thence to Celsius
     }
   //----------------------------------------------------------
    public void setCels(String cels)
     {
     tempval = makeFloat(cels);//convert to float and store
     }

Both of these use a private method for converting the string data to floating point numbers:

   private float makeFloat(String s)
   {
   //this private method converts strings to floats
   //in the real world it would also do error handling
    s.trim();  //remove leading spaces
    return new Float(s).floatValue();
   }

It is here that we would usually add error handling, for users who type in "qwerty" instead of numbers. Then we declare two methods for fetching data out of the class:

    public float getFahr()
    {
    return 9 * (tempval / 5) + 32;   //return temp as Fahrenheit
     }
   //------------------------------------------------------------
     public float getCels()
     {
     return tempval;                 //return temp as Celsius
     }
   }                                 //end class Temperature

This may look like more work at first, but we have encapsulated all of the temperature behavior inside a simple class, where the data value is stored. We can then fetch that temperature in any convenient form using the getFahr and getCels methods.

Now we can rewrite the code that we execute when that Compute button is clicked to use that class in the following simple way:

   private temp = new Temperature();//create a variable 
   public void clickedCompute()
       {
           float newtemp; String tx;
           tx = TempEntry.getText();            //get the text
            if (Fahr.getState())
               {
               temp.setCels(tx);                //store as Celsius
               newtemp = temp.getFahr();        //get back as Fahrenheit
               }
            else
               {
               temp.setFahr(tx);               //store as Fahreheit
               newtemp = temp.getCels();       //get back as Celsius
               }
               result.setText(new String().valueOf(newtemp));
       }

Applet-Sauce?

Java programs can be written in two forms: stand-alone programs or applications, and programs to be embedded in World Wide Web pages or applets. Stand-alone Java programs are just as flexible and powerful as stand-alone programs in any other languages, but Java applets are restricted by the Java security model so that they can be safely downloaded with a web page and cannot do any harm to your computer or local network.

This ability to write programs that can be embedded in web pages is one of Java's major attractions. You can write applets like the one in Figure 3, which represents part of our current research on using Java applets to assist users in searching for concepts in collections of documents.

Vb-java3.gif

Figure 3. A Java-based client for concept searching

But stand-alone Java programs are now becoming even more significant because you can run the exact same program on your Windows system, your OS/2 system, your UNIX system (any flavor), or your Macintosh. Any number of companies have announced plans to provide Java-based office suites, including Lotus, Corel-Wordperfect, Applix, and Microsoft. Java represents the end of programs that run well on one system, but only "pretty well" or poorly on others. The programs will be the same on all platforms. This is persuasive to vendors seeking to cut development costs and to Information System (IS) managers who have to support multiple platforms in a single organization.

Full of Beans?

Visual Basic has long been noted for the availability of a wide variety of third-party visual controls: buttons, grids, database connectors and zillions more. IBM, working with JavaSoft and other vendors, has developed a specification called JavaBeans that allows these same sort of third-party controls to work in both development and execution modes. In execution mode, these components provide a smaller code size than in-development mode and all the flexibility of any other kind of visual controls. Look to see lots of Beans being picked in the next few months.

How're We Doing So Far?

I hope you're convinced by now that Java really is the wave of the future. And Java is moving very fast because of all the major vendors that have embraced it and are writing tools for it. In an article on VB and Java that I wrote a few months ago, I noted Java's deficiencies. Let's see how this has improved in the interim:

  • Java applications are too slow. With the current round of JIT compilers, Java applications load and run faster than VB code does. Java applets embedded in web pages still load slowly because web browser vendors have not yet optimized the security checking of download byte codes as much as they need to.
  • Java development tools are still primitive. Big changes here. The latest versions are really better than the current VB implementations. This is what competition has done in this fast moving market.
  • Java access to databases is too young. In Java 1.1, now in beta testing, this is no longer true.
  • Java can't print anything. This is true of Java 1.0, but printing is included in Java 1.1.
  • Java can't access local hardware and interface cards. Still true. You need to access these by linking your Java to native methods for that platform. I don't see a rapid change here.

So is Java for Visual Basic programmers? I'm more sold on Java than ever. I still write a lot of VB code as a hobby, but will be changing even that in the next few months. It's probably time you considered changing too.

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