Journal Articles

CVu Journal Vol 13, #3 - Jun 2001 + Programming Topics
Browse in : All > Journals > CVu > 133 (12)
All > Topics > Programming (877)
Any of these categories - All of these categories

Note: when you create a new publication type, the articles module will automatically use the templates user-display-[publicationtype].xt and user-summary-[publicationtype].xt. If those templates do not exist when you try to preview or display a new article, you'll get this warning :-) Please place your own templates in themes/yourtheme/modules/articles . The templates will get the extension .xt there.

Title: Some Thoughts on Java

Author: Administrator

Date: 03 June 2001 13:15:46 +01:00 or Sun, 03 June 2001 13:15:46 +01:00

Summary: 

Body: 

Learning Java

It was disappointing to see no articles on Java in either C Vu or Overload but also acknowledging that readers' contributions are valuable, valued and required in generating content here are some thoughts on the start of a journey into Java, which others may find interesting and/or helpful. Currently there is no overall plan to this activity, consequently it may stop abruptly, or it may continue...

Having followed Java for a number of years, but not having used it in anger, the time seemed right to start to learn about Java in the only way that is really possible - writing code. Writing code implies at a minimum:

  • At least a rudimentary understanding of the language and facilities (libraries...) it offers

  • At least a rudimentary understanding of the language development environment

  • At least a limited knowledge of how to create an executable (Hello World) using the language

Thereafter more complex tasks can be undertaken.

Resources for Java

Sun Microsystems has provided a great deal of free material to help the aspiring Java developer. The best place to start is with Sun Microsystems themselves at http://java.sun.com. There are a number of good books that describe the Java language, not least of which are those provided by Sun Microsystems. Of course, the ACCU contains a number of book reviews on Java and that would be a good starting point before purchasing any books. In addition there is Bruce Eckel's book Thinking in Java Second Edition, which is available for free in electronic format from www.bruceeckel.com.

The minimum requirement to produce programs in Java is to use the JDK with your own choice of editor, even Notepad for those who prefer a handicap. Before long the value of having access to documentation will become apparent and Sun provide plenty of documentation. Many, myself included, prefer the use of a suitable development environment. These can be downloaded from the Web or obtained from magazine CD/DVDs. PC Magazines often make available Java related material, for example PC Plus have previously carried Borland's JBuilder Java development environment on the CD/DVD. The latest version of JBuilder that is available for free is their version 4.0 Foundation product, using JDK 1.3.0, available from http://www.borland.com. IBM also have a free product called the VisualAge Entry Enterprise Edition 3.5, using JDK 1.2.1, and a supporting community called the VisualAge Developer Domain (VADD). These resources make useful entry points to Java and learning more about it. Of course much more Java material is also available from other sources and searching on the web will find many other resources.

Choosing a Java Development Environment

The development environment (IDE) used is a highly personal choice, or perhaps a corporate choice. In any event my starting premise was to choose an IDE based on first impressions. Whilst acknowledging that this approach is the antithesis of a structured evaluation, with well-defined objectives, requirements, comparative criteria and feature assessments, it does allow a choice to be made quickly. Two simple criteria were chosen:

  1. Which IDE appeared to offer the most functionality out-of-the-box

  2. Which IDE was easiest to use

The functionality available was assessed based on moving around the IDE and looking at the menu options, particularly around wizards to do new things (projects, forms, classes...). Assessing ease-of-use was performed by creating a test program, compiling it, stepping through it using the debugger and watching variables and finally customising the IDE editor. To make it a little harder the test program required the use of an external library (Java Archive - JAR), so was another step beyond a simple Hello World program. The JAR file itself was from a vendor supplied library from Documentum (Enterpise Document Management Systems).

The same actions were performed using three IDE contenders: Borland JBuilder 4.0 Foundation, Sun Forte 2.0 Community Edition and VisualAge for Java 3.5 Entry Enterprise Edition. Given that this evaluation was based on first impressions and was completed within the space of hours rather than days, weeks or months I will not try to summarise the products themselves, simply my impression. The Borland product was neat and aesthetically the most pleasing but also the most limited, the VisualAge product was the most complex and initially daunting and the Sun Forte product provided the best all round performance based on first impressions. The rest of this article (and possibly others to follow) will focus on Forte 2.0 Community Edition as the IDE of choice although, of course, others may prefer and use a different IDE.

Installing the JDK, Documentation and IDE

Having now chosen an IDE let us backtrack to installing Forte 2.0 Community Edition onto Windows, to see what is involved. There are three key download files:

  • Java Developers Kit (JDK) - Java development tools to create an executable:

    Windows download - j2sdk1_3_0-win.exe (~30Mb)

  • JDK documentation - documentation describing the tools and differences between versions

    Windows download - j2sdk-1_3_0-update1-doc.zip (~21Mb)

  • Forte 2.0 Community Edition - integrated development environment (IDE) using JDK 1.3.0

    Windows download - forte_ce_2_win.exe (~9Mb)

Installing Forte 2.0 Community Edition is very easy:

  1. Run the executable to install the JDK 1.3.0

  2. Extract the JDK 1.3.0 documentation from the ZIP file to the same location

  3. Install Forte 2.0 Community Edition (CE), which will detect the JDK 1.3.0

This basic installation procedure has worked successfully and without any issues on both an NT4 desktop client PC and also a Windows Millennium Edition PC. It is my understanding that using the equivalent files for other platforms would effectively be the same process.

Test the installation

To verify that the JDK installation has been performed correctly open an MS-DOS Prompt box and type java -version at the prompt. This should result in something similar to this:

If this does not happen then check the installation procedure once again.

To verify that the documentation has been installed, typically to a docs directory, use a browser to check. For example, using Internet Explorer, use the File Open menu command and then browse to the location that the documentation was installed into and open the index.html file. On my PC the JDK was installed to c:\rnl\jdk13, documentation to c:\rnl\jdk13\docs, so opening c:\rnl\jdk13\docs\index.html results in:

If this does not happen check the installation procedure and where the documentation was actually extracted. It may be located in another directory, search for index.html.

To verify the Forte 2.0 CE installation, run the program: from the menu or desktop icon. Alternatively dependent on where it is installed use the Start:Run command and run runidew.exe (i.e. C:\rnl\forte4j\bin\runidew.exe). This will open a number of windows and in particular the main window (this screenshot has been resized, the swing components are to the right of the first two toolbars by default):

If this does not happen then check the installation procedure, documented in Java_CEinstallation.pdf, which is available from Sun as a separate file. (That particular document emphasises that the directory location should not include spaces in the name.)

JDK Hello World program

An interesting question is: why use the JDK directly at the command line, possibly only occasionally, when a Java IDE is available? There are a number of possible reasons:

  • To understand what the IDE is doing behind the scenes

  • To potentially switch between JDKs by using a second JDK environment

  • An IDE may not be available on the target platform but is available on a different (developer) platform

  • The IDE may have undocumented features that produce unexpected results, for that - read bugs ?

  • ...

The first program is traditionally a simple "Hello World", using an editor of your choice create this Java program, for example create a file named Test.java in a suitable location (c:\rnl\JavaApp\Test.java) and add this Java code:

public class Test {
  public static void main(String[] arg) {
    System.out.println("Hello Java World");
  }
}

Note the following items:

  • The class name Test is capitalised

  • The filename uses the same name as the class, and the same capitalisation, with a java extension

  • The presence of a semicolon after the Hello Java World

To compile this program use the MS DOS prompt and in the same location as the source file (c:\rnl\JavaApp) type: javac Test.java. The javac command is actually invoking the Java compiler to perform its work, compiling the program, from its location i.e. c:\rnl\jdk13\bin. At this point you will get an error: Bad command or file name. This is because the Java compiler is not in your path and Windows is unable to find the file in either the current directory location or in the directories specified in the PATH environment variable. This can be resolved in the following ways:

  • Provide the full path to the Java compiler as part of the command i.e. c:\rnl\jdk13\bin\javac Test.java

  • Set the environment variable (PATH) to include the location of the Java binaries - c:\rnl\jdk13\bin

The simplest option is to set the PATH environment variable. This can be found in the autoexec.bat in Windows ME, which requires a restart of ME, or in System Properties in NT4, which can be applied without requiring a restart.

This 'Hello World' program is syntactically correct and when the Java compiler has run it produces a second file that is called Test.class. This is the output of the Java compiler and is the executable that is actually run by Java, for example, type java Test at the MSDOS prompt and you will get the output of Hello Java World. The first Java program is complete and it works!

JDK Hello World Program Errors

It is useful to review what can go wrong because:

  • It will indicate the type of error message that results for a specific error

  • It gives an indication of the error cascade that can occur for one simple error

  • It will provide helpful clues when similar errors occur in more complex situations (and they will)

  • Finding the issue, or diagnosing the single problem, in this context is very easy

  • ...

Of course, for those who write perfect programs first time through please ignore this section as you will never see these error messages!

Hello World Runtime Errors

Knowing that the program compiles cleanly, what happens when running the program if the command line includes the class extension? (In normal Windows executables the extension doesn't matter):

What about the name of the file used for the source code? If that is named test.java, as opposed to Test.java, and is compiled and run: The message indicates the reason - the difference is found between the file named test and the class named Test. The Java compilation rules clearly require, in this case, that the file and class names are the same, otherwise an exception is thrown in main. The reason for this will be explained later when discussing Java packages and Java compilation.

Hello World Compile Errors

There is plenty of scope to see what error messages result from syntax errors. However, to focus on perhaps the most obvious errors which occur in this example and probably general practice:

  1. Statement is missing a terminating semicolon

  2. Specified property, method or data item, does not exist in specified package

Statement System.out.println("Hello Java World") is missing a terminating semicolon:

Specified property, method or data item, does not exist in the specified package - for example, removing "out" from the code System.println("Hello Java World"); results in:

It is very easy to create a cascade of errors and become totally confused as to what the cause of the error is. If this situation occurs apply this rule of thumb: fix the very first error and recompile to see what errors remain. For example, it would be useful to pass in a command line argument and have the program print that out. A property of Java arrays is that they have a length property that can be interrogated to determine the number of elements within that array. The Java main() method has a parameter of an array of strings (String[] arg), so using this knowledge it is possible to extract the first command line parameter and output that rather than Hello Java World. Changing the code to include these three additional statements:

class Test {
  public static void main(String[] arg) {
    if (arg[].length == 1)
      System.out.println(arg[0]);
    else
      System.out.println("Hello Java World");
  }
}

Results in the following error cascade:

Focusing on the first error indicates that there is a problem obtaining the length of the array so changing that line to if(arg.length == 1) produces the following (expected) result:

Forte 2.0 CE Hello World program

The final task here is to compile and run this program in the IDE. This also completes the installation test for both the JDK and Forte 2.0 CE as the previous test for the IDE merely verified presence, not that it would compile and execute Java programs.

Starting Forte 2.0 CE results in the default startup of displaying the Main Window, as shown before, along with the default windows for the Editing tab i.e. Explorer and Properties. The Explorer window allows the mounting of resources for the Java program, typically file-system locations and JAR files. It is the IDE equivalent of setting the CLASSPATH variable, the JDK variable to locate important Java resources such as class files. The Explorer window will have a default file-system mounted, pointing to the Help system example programs that can be used as an introduction to the IDE:

The starting point for the Hello Java World program is to mount the file-system resource that contains the Java source code. This is achieved by performing the following steps:

  • Select the top level Filesystems item in the Explorer window

  • Right-mouse-click and select Mount Directory...

  • Select the appropriate directory location

Select Mount and the filesystem is added to the list of filesystem resources:

Note that the file (Test.java) is now located within this Explorer view and double-clicking class Test will open the Java code into the source code editor, which you can customise via Tools:Global Options:

To compile and run this code simply press F6, or use the menu option Build:Execute, or right-mouse-click in the Source Editor window and select Execute. This switches the IDE to the Running tab and as part of that view the Output Window is displayed:

The first Java program, via the IDE, is complete and it works! Just to complete this section, earlier command line arguments were passed in and executed this can be achieved by selecting Test, not class Test as we did earlier:

and then examine its execution properties:

Executing the program again will result in Roger being output to the Output Window:

Further Exploration

Now is perhaps a good time to experiment a little and look at the Java tutorials that Sun provides:

Notes: 

More fields may be available via dynamicdata ..