 | Level: Introductory Mark Weber (weberm@us.ibm.com), Senior Software Engineer, IBM David Carew (carew@us.ibm.com), Senior e-Business Architect, IBM
27 Feb 2004 This article is the second installment in Getting on the open road, a three-part series of roadmaps designed to assist developers of .NET, Windows client/server, and ASP applications make the jump to the Java platform. In Getting on the open road, the authors help you leverage your existing development knowledge to ease the way onto the path of open-standards-based programming. Senior software engineer Mark Weber and Senior e-Business architect David Carew provide this roadmap for Windows developers using Visual Basic 6 or C++ who are new to the Java language and J2EE technology, are interested in Web enabling Windows client-server applications as Java-based or J2EE-based Web applications, and want help finding the most useful tools, technologies, and online information from IBM and elsewhere. Share your thoughts on these articles with the authors and other readers in the accompanying discussion forum. (You can also click Discuss at the top or bottom of the article to access the forum.)
Do you need to provide Web access to existing Windows client-server applications or application components? Have you considered deploying them as Web applications based on Java technology or J2EE? If so, this roadmap will get you started. It focuses on migrating existing Windows client-server applications and application components to the Java and J2EE platforms, and on the tools, technologies, and architectural approaches appropriate to this task. After we provide a primer on Java technology, we'll point you to more resources for learning the Java language and J2EE technologies, integrating Windows applications and application components into Java and J2EE applications, and enabling these applications for Web access. We'll also introduce you to some deployment environments for your integrated applications, including the IBM WebSphere family.
Why use Java technology for Web-enablement?
The Java platform is both an application programming language and an execution environment. It's syntactically similar to C++ with a SmallTalk-like execution environment. Sun Microsystems first released the Java language in 1994, and the use of Internet browsers made it popular. Industry acceptance of the Java language has become universal. Computer and software vendors, as well as hundreds of commercial companies, have endorsed Java technology.
The Java language is an easy-to-use, object-oriented language that's based on the best characteristics of previous-generation object-oriented languages (SmallTalk and C++). It's architecture-neutral, portable, secure, distributed, interpreted, robust, dynamic, and high-performing for targeted applications. And it includes a complete application-execution environment. These characteristics add up to three major advantages:
- The Java language is platform-independent at both the source and binary levels; you can write your Java code once and run it anywhere.
- The Java language's object-oriented basis fosters reuse and lets you create modular applications and components.
- The Java language's set of standard APIs lets you deploy applications in execution environments from several different vendors.
J2EE's benefits
J2EE is the platform for distributed, enterprise-level Java applications. Its standard environment lets you distribute and reuse application components. Its component-based modular application architecture encourages code reuse, simplifies development and maintenance of applications and components, provides deployment flexibility, enables high performance with load-balancing and distribution of components, and supports higher scalability of applications.
 |
Migrate to the Java platform
If you develop .NET, Windows client/server, and ASP applications, and are contemplating making the leap to the J2EE platform, our series Getting on the open road will guide you through the process, leveraging your existing development knowledge to ease the way onto the path of open-standards-based programming.
|
|
Because J2EE is based on Java technology and is itself a standard, it's highly portable. Many J2EE servers, providers, and components conform to J2EE open standards, which gives you a choice of development and deployment environments. Java and J2EE applications are both network-oriented and distributed, which lets you write Web-based, thin-client applications. This architecture provides many benefits over native Windows applications or Windows client-server applications, including:
- Universal access to applications from Web browsers, from pervasive mobile-computing devices, and from other applications
- Access to the same applications and components from full Java client applications to provide richer user interactivity and appearance
- Easy updates to new versions of the application, because end users don't need to update or install any code
- Ability to integrate external applications with a Java-language or J2EE application's modular components, thereby increasing reuse, application design, and design flexibility
Java programming fundamentals
Before we delve into Web-enabling your applications, we'll give you a deeper look into the Java programming language. You can use the Java language to write server-side applications as well as desktop applications with GUIs. This article assumes you want to use the Java language on the server side to complement a Web-based interface, so we'll skip the GUI programming environment and focus instead on the platform's nonvisual aspects. We'll start with an introduction to the Java Software Development Kit (SDK) and then show you how to write the time-honored "Hello World" application in Java code. Then, we'll explore the differences between Visual Basic 6 and the Java language.
Introducing the Java SDK
The Java SDK is a group of command-line tools and packages you need in order to write and run Java programs. Java programs are compiled into platform-independent bytecode by a Just-in-time (JIT) Compiler, and then the bytecode is compiled into native code at runtime. The most important tools are the Java compiler (javac.exe) and the Java interpreter (java.exe), which you use to run Java programs. The SDK also includes the base classes (called the Java platform), which provide you with the basic functionality and APIs you need to start writing applications.
Sun Microsystems has released an SDK for each of its five major releases of the Java platform. We recommended you get the latest SDK version (Java 1.4.2) for this article. The Java SDK is freely available. If you don't have it already, download it now (see Resources).
You can reference the Java 2 Standard Edition (J2SE) API documentation online (see Resources). It's a collection of HTML documents that you can navigate in a standard Web browser. The API documentation is an essential reference, and you'll probably use it frequently.
 |
Java SDK basics
- Write your Java source code in plain ASCII format with a text editor that supports long filenames.
- Save the file with a .java extension.
All Java keywords are lowercase. You can use any case for variable and method names, but you must use it consistently throughout a class.
- Compile your program from a command-line prompt, using the javac compiler that comes with the SDK. Always specify the .java extension.
- Run your program from a command-line prompt, using the Java interpreter that comes with the SDK. Do not specify the .class extension.
- Debug your code if necessary. Errors can occur when a Java program compiles or runs.
|
|
Installing the SDK
After you download the SDK, you need to install it on your machine. The installation is straightforward. If the setup gives you a choice between a typical or a custom install, choose the typical install. (You should choose the custom install only if you know exactly what you do and don't want to load on your machine.) The installation usually gives you the option of installing the source code for the standard Java platform classes. If you have sufficient disk space on your machine, we recommend that you take this option. These files will give you a chance to look at the implementation of the classes that make up the Java language and standard APIs. They're particularly well designed and implemented, and you can learn a lot from them.
After you install the SDK, you might need to configure it to work on your system. How you configure the SDK depends on your operating system and the SDK version you're using. The SDK includes complete installation and configuration instructions.
Your first Java program
Now you can write your first Java program -- the ubiquitous Hello World. Open your text editor and enter the source code exactly as you see it in Listing 1.
Listing 1. Hello World program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
|
The Java language is case-sensitive, and language keywords such as class and public are always lowercase. You can use any case for your variable and method names, as long as you are consistent in the usage throughout a given class. When you're done typing, save the code in a file called HelloWorld.java. You have no choice when it comes to this filename. Java source files use a .java extension, and every Java source code file must have the same name as the class you define inside it. We can't state it enough: Case is significant, so file names like HELLOWORLD.JAVA and Helloworld.java will result in a compile error. You can save HelloWorld.java in any appropriate directory on your machine. You need to go to this directory to use the command-line tools, so make sure it's convenient.
Compiling the program
Now you're ready to compile the HelloWorld program. The Java language compiler that comes with the SDK is a command-line application called javac.exe. To compile a Java source code file, you simply pass the name of the .java file to the javac.exe program. To compile your HelloWorld program, open a command-line prompt and change your directory to the location where you saved the HelloWorld.java file. Then execute this command:
Like a Visual Basic compiler, the Java compiler can generate any number of errors. Naturally, you need to correct any errors before the Java compiler will compile the HelloWorld program successfully. A successful compile generates a class file called HelloWorld.class. This file represents the executable you run in the Java interpreter.
Running the program
The Java interpreter that comes with the SDK is a command-line application called java.exe. To run a Java bytecode executable, you simply pass the name of the Java program to the Java interpreter. Don't specify the .class extension when you use the Java interpreter. The interpreter expects only class files, so adding the .class extension will produce an error. To run your HelloWorld program, open a command-line prompt and change your directory to the location where you compiled the HelloWorld.java file. Your bytecode executable file, HelloWorld.class, should be there. Then execute this command:
The Java interpreter tries to execute the HelloWorld program's main() method. Java methods that list void as the return type are equivalent to a Sub in Visual Basic. Methods with other return types are equivalent to a Function in Visual Basic.
The Java interpreter might report a runtime error, which usually terminates program execution. As in Visual Basic, Java runtime errors are more difficult to debug than compile-time errors but occur less frequently. When runtime errors do occur, you can handle them gracefully because Java programs execute in a managed environment, which reduces the likelihood of "runaway code" bringing an entire machine to a screeching halt.
Thanks to Scott Stricker for his contributions to this and the next main sections, adapted from his tutorial, "Java programming for C/C++ developers" (see Resources).
Java 101 from a Visual Basic perspective
Now that you have a basic idea of what Java code looks like and how to compile and run it on your test machine, you're ready to go deeper into the Java language's structure and syntax, including the Java programming environment and Java primitive data types. Because you're familiar with programming in Visual Basic, you'll learn by comparison. We'll discuss the Java platform's fundamental components in terms of their relation to or differences from similar components underlying the Visual Basic programming framework. If you're a C/C++ programmer, you can skip this section and take advantage of the free developerWorks tutorial Java programming for C/C++ developers instead (see Resources).
Visual Basic execution environment
Visual Basic is a high-level programming language; its purpose is to make it easier for human beings to develop computer programs. Computers can't understand high-level languages; they can only understand low-level machine languages -- a sequence of binary instructions that can execute directly on a computer's processor. For this reason, programs written in high-level languages must be translated into machine-language programs -- executables -- before they can be run on a computer. Different computers use different machine languages. An executable that runs on one machine won't run on another machine that uses a different machine language.
Two methods are available for translating a high-level programming language into machine-language executables: compilation and interpretation. Compilation involves translating an entire high-level program into a whole machine-language program, which can then be executed in its entirety. Interpretation involves translating a high-level program into machine instructions line-by-line; one line is translated and executed before the next line is reached. Compilation and interpretation are logically equivalent, but compiled programs tend to execute faster than interpreted programs. Visual Basic programs are compiled into machine-language executables by a program called a compiler.
The Java execution environment
Like Visual Basic programs, Java programs are compiled. Unlike Visual Basic programs, Java programs aren't compiled to a platform-specific machine language. Instead, they're compiled to a platform-independent language called bytecode. Bytecode is similar to machine language, but bytecode isn't designed to run on any real, physical computer. Instead, it's designed to be run by a program, called a Java virtual machine (JVM), which simulates a real machine.
Simply put, the JVM is an interpreter that translates Java bytecode into real machine-language instructions that execute on the underlying, physical machine. More specifically, the term Java virtual machine is used generically to refer to any program that executes Java class files. The Java interpreter program, java.exe, is a specific JVM implementation.
The Java platform uses the virtual-machine layer to ensure that programs written in the Java language are platform independent. Once a Java program is compiled to bytecode, it can run on any system that has a JVM. This includes UNIX, Linux, Windows, and many others. Programs in other languages must be recompiled for each platform on which they are to be executed, but a Java program needs to be compiled only once.
Data types
The Java language has two different types of data: the classes programmers define (or made available to them as part of the SDK or third-party class libraries), and "primitive" types (boolean, char, byte, short, int, long, float, and double) that the Java runtime understands directly. Most of the Java primitives have an equivalent in Visual Basic, and user-defined classes are like classes in Visual Basic, for the most part. Table 1 lists the primitive data types in the Java language and the equivalent type in Visual Basic.
Table 1. Java language primitive types and their Visual Basic equivalents
| Java primitive | Range | Visual Basic type | Notes | boolean | true, false | Boolean | The only valid values for booleans are true and false. | char | 0 - 65535 | String (of length 1) | The Java language uses Unicode to encode characters. | byte | 8-bit integer (signed) | Byte | | short | 16-bit integer (signed) | Integer | | int | 32-bit integer (signed) | Long | | long | 64-bit integer (signed) | N/A | | float | 32-bit floating point number | Single | | double | 64-bit floating point number | Double | | | N/A | | Variant | The Java language doesn't have a Variant type. | | N/A | | Date | The Java language doesn't have a primitive date type. You can use the Date class instead. | | N/A | | Currency | The Java language doesn't have a primitive currency type. You can use the BigDecimal class instead. |
Listing 2 shows some examples of declaring primitives in the two languages.
Listing 2. Declaring primitive types
Visual Basic Java
Option Explicit // Note that all Java
Dim LetterJ As String, I As Integer, x As Byte // variables must be declared
Dim Point1 As Single, Point2 As Double // before they can be used
Dim IsEmpty As Boolean char letterJ = 'j';
LetterJ = "j" int i = 0;
I = 0 byte x = 12
X = 12 boolean isEmpty = false;
IsEmpty = False float point1 = 1.1F;
Point1 = 1.1 double point2 = 0.0025;
Point2 = 0.0025 |
Operators
Operators in Visual Basic and the Java language share many similarities and have some key differences. The Java language uses the same set of operators that C and C++ use. Table 2 lists the most common operators used in both languages.
Table 2. Operators in Visual Basic and the Java language
| Java operators | Description | Usage | Visual basic operators | Notes | ++ | Increment | ++num num++ | N/A | This unary operator allows incrementing a non floating point number. | -- | Decrement | --num num-- | N/A | This unary operator allows decrementing a non floating point number. | * / | Multiplication Division | num * num
num / num | * / | |
/ | Integer division | num/num | \ | The Java language uses the same operator for integer division and arithmetic division. If the operands are integers, then integer division is performed. | % | Modular division | num % num | Mod | | +
- | Addition Subtraction | num + num num - num | + - | | + | String concatenation | str + str | & | | < <= | Less than Less than or equal | expr < expr expr <= expr | < <= | | > >= | Greater than Greater than or equal | expr > expr expr >= expr | > >= | | != | Inequality | expr != expr | <> | | == | Equality (primitives) | expr == expr | = | | == | Equality (objects) | obj == obj | Is | | ! | Logical negation | !boolean | Not | Visual Basic uses the same operator for bitwise negation on integers and logical negation on Boolean expressions. The Java language doesn't. | ~ | Bitwise negation | ~int | Not | | & | Bitwise AND Boolean AND | int & int
expr & expr | And | | | | Bitwise OR Boolean OR | int | int expr | expr | Or | | ^ | Bitwise XOR Boolean XOR | int ^ int expr ^ expr | Xor | | && | Conditional AND | if (expr &&expr)... | And | The Java language uses a different operator for a conditional AND and a logical Boolean AND. | || | Conditional OR | if (expr || expr) ... | Or | The Java language uses a different operator for a conditional OR and a logical Boolean OR. | | N/A | Pattern matching | str Like pattern | Like | You can use the Java String object's methods to duplicate this Visual Basic operator's functionality. |
Visual Basic functions and sub procedures vs. Java methods
Visual Basic lets you define functions and sub procedures. The main difference between them is that a sub procedure doesn't return a value, and a function does. In Java terminology, functions are called methods. The Java language has no equivalent to sub procedures in Visual Basic. However, in the Java language you can define a method that has no return value by using the keyword void, which is roughly equivalent to a sub procedure. You can declare Java methods only as members of a class; you can't define a method outside of a Java class. Listing 3 shows an example of one Java method that returns a value and another that doesn't.
Listing 3. Return types of Java methods
public class MyClass {
// This method doesn't return a value
public void myMethod1(String arg) {
...
}
// This method returns an integer
public int myMethod2(String arg) {
int i;
...
return i ;
}
|
Arrays
In the Java language, arrays are objects with attributes, the most important of which is the length attribute, which you can use to determine the array's size. Java arrays are always indexed from 0, and the array's declared size includes the 0th element. So a size of 100 means that the valid indexes are 0 through 99. Also, you bind the bracket characters ([ ]) you use to indicate arrays to the array type, not the array name. The Java language allows for array literals that let you initialize arrays to a predetermined set of values. Listing 4 shows some examples.
Listing 4. Arrays
Visual Basic Java
'An array with 100 integers // An array of 100 integers
Dim a(99) As Integer int[] a = new int[100];
'An array of Strings initialized // An array of Strings initialized
b = Array("Tom","Dick", "Harry") String[] b = {"Tom","Dick", "Harry"};
'Iterating through an array // Iterating through an array of length 100
' of length 100 int [] c = new int [100];
Dim c(99) As Integer for (int i = 0; i <.length; i++) {
For i=0 To UBound(c) c[i] = i;
c(i) = i }
Next
|
Strings
Visual Basic has a String data type to represent strings. You represent Java strings by objects of the String class. Both Visual Basic and Java string literals are represented as a sequence of characters enclosed within quotation marks. In the Java language, you have two ways to create a String object: You can use a string literal, or you can use a constructor. String objects are immutable, which means that once you give a String an initial value, you can't change it. In other words, if you want to change the value of a String reference, you need to assign the reference a new String object. Because Java strings are objects, you interact with them through the interface defined by the String class. (You'll learn more about constructors and interfaces in An introduction to object-oriented programming, later in this article.) The String class has a rich interface with quite a few useful methods.
Listing 5 demonstrates some of the most commonly used methods. Try compiling and running this example. Remember to name the source file StringTest.java, and don't forget that the filename's case is significant.
Listing 5. Strings in the Java language
/*
* The StringTest class simply demonstrates
* how Java Strings are created and how
* String methods can be used to create
* new String objects. Notice that when you
* call a String method like toUpperCase()
* the original String is not modified. To
* actually change the value of the original
* String, you have to assign the new
* String back to the original reference.
*/
public class StringTest {
public static void main(String[] args) {
String str1 = "Hi there";
String str2 = new String("Hi there");
// Display true if str1 and str2 have the value
System.out.println(str1.equals(str2));
// A new uppercase version of str1
System.out.println(str1.toUpperCase());
// A new lowercase version of str2
System.out.println(str1.toLowerCase());
System.out.println(str1.substring(1,4));
// A new version of str1 w/o any trailing whitespace chars
System.out.println(str1.trim());
// Display true if str1 start with "Hi"
System.out.println(str1.startsWith("Hi"));
// Display true if str1 ends with "there"
System.out.println(str1.endsWith("there"));
// Replace all i's with o's
System.out.println(str1.replace('i', 'o'));
}
}
|
The main() method
Java classes that are to be run from the command line as an application must define a main() method in order to run. In Java code, the main() method follows a strict naming convention. You declare main() methods this way:
public static void main(String[] args)
|
Note: You can reverse the public and static modifiers, and you can name the String array anything you like. However, remember that the above format is conventional. Not all classes need a main() method -- only those to be run from the command line. A typical Java application has one class with a main() method and several other supporting classes without a main() method.
Packages
Object-oriented languages like the Java language facilitate reuse of classes. Because most programmers use simple descriptive name for their classes (such as Invoice or User) the likelihood of a name collision is high when you reuse classes from various sources. The Java language addresses this issue by letting each class belong to a package. You can simultaneously use classes that have the same name but are in different packages. To associate a class with a package, you must make the package statement the first line of code in the class' source code. Here's an example:
package com.ibm.training;
|
By convention, you prefix package names by the reverse Internet domain name (for example, com.yourco.somepackage). To use a class that is in a different package, you have two choices. One option is to use the class's fully qualified name, including the package. Listing 6 shows an example.
Listing 6. Using fully qualified class names
public class PackDemo1 {
public static void main(String[] args) {
Java.util.Date today = new java.util.Date();
System.out.println("The date is " + today);
}
|
The alternative is to use an import statement in your source file for the class that's in another package. The fully qualified name isn't necessary anymore, as Listing 7 shows.
Listing 7. Using an import statement
import java.util.Date;
public class PackDemo1 {
public static void main(String[] args) {
Date today = new Date();
System.out.println("The date is " + today);
}
|
You can use a wildcard to import all the classes in a package. This is useful if you need to use several classes in the same package, as in Listing 8.
Listing 8. Using an import statement with wildcards
import java.util.*;
public class PackDemo1 {
public static void main(String[] args) {
Date now = new Date();
System.out.println("The date is " + today);
}
|
Packaging for reuse
In Visual Basic, you can write code and build it as a dynamic link library (DLL) that's represented on the file system as a file with a .dll extension. Other programs can refer to DLLs in order to use the code they contain. The Java language also allows you to package sets of classes, in file called a Java Archive (JAR), for reuse. You can combine sets of classes into a file with a .jar extension and reference the JAR file from other classes. Files with a .jar extension are standard zip files that can be manipulated with WinZip or other zip utilities. However, for convenience, the Java SDK contains a utility called jar.exe (on the Windows platform) that you can use to combine sets of classes into a single file with a .jar extension.
Before we walk you through an example of using the jar.exe utility, it's important that you understand the relationship between package names and the directory structure the Java platform uses to build classes and load them at runtime. Consider a class called Test whose source is in a file called Test.java. If you define Test.java to be part of the package com.mycompany.test, then the compiler creates a directory tree for the resulting .class module. The directory tree is based on the package name. In this case the tree is com\mycompany\test, with the periods in the package name converted to directory boundaries.
Now, open a command prompt and create a directory (for example, c:\javapack). Change to that directory (cd javapack). Use your favorite text editor to add the code in Listing 9 to a new file called Test.java.
Listing 9. An example of using packages
package com.mycompany.test;
public class Test
{
public static void main(String[] args) {
System.out.println("In test");
}
}
|
Now, compile Test.java with the following command. (The -d option should point to the directory that you created for this example):
java -d c:\javapack Test.java
|
You should now have a subdirectory called com in your c:\javapack directory. In fact, you can see that the fully qualified name of the comTest.class file that resulted from the compilation is Test.class. Note how the package name (com.mycompany.test) was translated to a corresponding directory structure (com\mycompany\test) rooted at the directory you specified with the -d option.
Now we'll show you how you can package Test.class for easy reuse by other classes. Run this command from the c:\javapack directory:
The command creates a file, called Test.jar, that contains all the classes under the com subdirectory.
Run this command to use the class in the Test.jar file:
java -classpath Test.jar com.mycompany.test.Test
|
Note that you have to use the fully qualified class name to run the command from the command line, and note the way you use the -classpath option to point to the Test.jar file. Alternatively, you could add the Test.jar file to the CLASSPATH environment variable, which is a semicolon-separated list of JAR files and directories the Java compiler and the JVM use to look for classes that need to be loaded.
Other differences
We've gone over the major syntactic differences between the Java language and Visual Basic. Some other differences are:
- Global variables: Unlike Visual Basic, the Java language offers no way to declare global variables (or methods).
GoTo: Although the Java language reserves goto as a keyword, it has no Goto statement like the one Visual Basic uses.
- Freely placed variables: You can declare Java variables anywhere, as they're needed. You don't need to group variables at the top of a block, as you must in Visual Basic.
- Inheritance: Visual Basic doesn't let you define classes that extend the capabilities of other classes. The Java language lets you define a class that inherits all but the private members of a class. These new classes can extend the behavior of the class they inherit from as well as override the behavior of the inherited members. (You'll learn more about inheritance in the next section.)
An introduction to object-oriented programming
The Java programming language is object-oriented. Visual Basic has many object features but isn't strictly an object-oriented language. In this section we'll show you how you build a class in Visual Basic and then the equivalent class in the Java language.
Working with classes
You can think of a class as a data type that you define. Variable instances of a class are called objects. Like other variables, objects have a type, a set of attributes, and a set of operations. An object's type is represented by the class from which the object was instantiated. The object's attributes represent its value or state. An object's operations are the set of possible functions you can invoke on the object in order to change its state.
Consider Visual Basic's Integer fundamental data type, which represents an integer. You use this type name to create variables that are instances of an integer. Every Integer variable has one attribute, which represents the integer number that the variable holds. Every Integer variable also has the same set of operations, which you can use to change the variable's state (or value). Some of the operations you can perform on an Integer variable include addition (+), subtraction (-), multiplication (*), division(\), and modulo (Mod).
Defining a Visual Basic class
Now, let's examine a situation in which you might want to develop your own type -- one that represents a complex object that the Visual Basic language doesn't support as a fundamental type. Suppose you're part of a team developing software for a financial institution, and your job is to develop code to represent a typical bank account. A bank has several accounts, but each account has the same basic set of attributes and operations. In particular, an account has a balance and an ID number. The Visual Basic code in Listing 10 defines an account class. It defines three operations: Deposit, Withdrawal, and InitAccount (used to initialize the balance and account number). Note how you keep track of the actual balance by using a private variable and that you define a property called Balance to let this class's user obtain the balance.
Listing 10. Defining a Visual Basic class
Private theBalance As Currency
Private theAccountNumber As Integer
Public Sub InitAccount (number As Integer, initBal As Currency)
theAccountNumber = number
theBalance = initBal
End Sub
Public Sub Deposit (amount As Currency)
theBalance = theBalance + amount
End Sub
Public Sub Withdrawal (amount As Currency)
theBalance = theBalance - amount
End Sub
Public Property Get Balance() As Currency
Balance = theBalance
End Property
Public Property Get AccountNumber() As Integer
AccountNumber = theAccountNumber
End Property
|
Defining a Java class
Listing 11 implements the Account class in the Java language.
Listing 11. The Java language Account class
public class Account {
private double balance;
private int number;
public Account(int number, double balance) {
number = argNumber;
balance = argBalance;
}
public void deposit(double amnt) {
balance += amnt;
}
public void withdrawal (double amnt) {
balance -= amnt;
}
public double getBalance() {
return balance;
}
public int getNumber() {
return number;
}
}
|
As you can see, defining a Java class is different from defining a Visual Basic class. The two languages' respective account classes reflect the major differences:
- You don't need a separate method to initialize an instance of
Account in your Java code. You use a constructor. As the name implies, you use it to construct instances of a class. A constructor must have the same name as the class for which it's defined, and it can take parameters. You can create as many constructors as you like for a class. If you don't provide a constructor, then a default constructor that takes no parameters is made available to you automatically. You could use the constructor in Listing 11 this way:
Account myAccount = new Account(12345, 0.00);
|
- Unlike Visual Basic, the Java language has no special provisions for properties. By convention, Java properties are private fields and you usually provide a set of methods called accessors for access to the fields that contain properties. The methods that return the properties' values are known as getters, those you use to set a property's value are called setters. Here's an example of a setter method:
public void setIntProperty(int argIntProperty) {intProperty = argIntProperty;} |
- The default access modifier for class members isn't
public as it is in Visual Basic (more on access modifiers later).
Benefits of objects
Three of the primary benefits of using classes and objects in an object-oriented language like the Java language are encapsulation, inheritance, and polymorphism:
- Encapsulation (or information hiding) refers to treating an object like a "black box;" that is, you can use an object without knowing (or caring) how it's implemented. Using objects through the interface defined by the methods (operators) defined in the class ensures you can change the class implementation without breaking any code that uses objects of that class.
- Polymorphism refers to the ability to associate different features to the same name, together with the ability to choose the right feature based on context. The most common example of polymorphism is method overloading, whereby you can define several methods that have the same name, as long as they take different parameters.
- Inheritance refers to reusing code by writing new classes that extend an existing class. For example, let's say you want to write a new class to represent a checking account. Because a checking account is a special kind of bank account, you can write the
CheckingAccount class so that it extends (or subclasses) the Account class. Then, the CheckingAccount class automatically gets the state and all the operators (functions) of the Account class. You only need to add the new state and operators specific to the CheckingAccount class. For example, you might add a cashCheck() function to perform the operation of cashing a check written for the checking account. If required, you could also change the subclass's inherited state or behavior. For example, a user might be allowed to overdraw on her checking account, so you would need to override the withdrawal function.
 |
Java classes in depth
Now that you understand the general role of classes and objects in an object-oriented programming framework, you're ready to delve more deeply into these specifics of the Java platform's class structure and implementation:
- Class members: A class member is always either a field or a method. A field represents data, and a method represents operations. Classes can define any number of members.
- Access modifiers: You declare class members with access modifiers, which specify the accessibility of the member outside of the class in which it is defined. For example, members that are declared private cannot be accessed at all, but public members are freely accessible.
- Objects: Classes are really just definitions. What you actually use in code are class instances called objects. You'll learn how to create objects from classes.
- Constructors: A constructor is a special operator you use to create objects. In general, a class isn't of much use if you can't create objects of that class. Constructors are important because they provide the ability to create new class instances.
- The
this keyword: Java objects implicitly reference themselves. It's important that you understand how to use the this keyword for this purpose.
Class members
A Java class is an independent module of code that defines attributes and operations in terms of members. Fields and methods are examples of members.
A field is a variable you declare inside of a class. Java fields come in two varieties: instance variables and class variables. Instance variables are associated with each instance of a class, and each instance has its own copies of instance variables. Class variables, which you declare using the static keyword, are associated with the class as a whole, and the class shares a single class variable with all class instances. For example, the balance field in a BankAccount is an instance field because each BankAccount instance has its own balance, which is independent of every other Account object's balance. On the other hand, you could declare an interest field as a class field because every BankAccount object uses the same interest rate.
A method is a function you declare inside of a class. Java methods come in two varieties: instance methods and class methods. Every class instance gets its own copy of instance methods, but there is only one copy of a class method, which all class instances share. You declare class methods using the static keyword. You use instance methods to operate on instance variables, and class methods to operate on class variables. For example, a deposit() method in the BankAccount class would be an instance method because each BankAccount has its own balance field, which the deposit() method would change. You could declare a setInterest() method as a class method because every BankAccount shares a single interest field, which the setInterest() method would change.
The program BankAccount in Listing 12 has five members. Two members are fields: balance, which is an instance field, and interest, which is a class field. Three members are methods: deposit() and withdraw() are instance methods, and setInterest() is a class method. Notice that you use an object name to access instance members, and the class name to access class members.
Listing 12. The BankAccount class
public class Account {
public class BankAccount {
private float balance; // an instance field
private static float interest; // a class, or static, field
// an instance method
public void deposit(float amount) {
balance += amount;
}
// an instance method
public void withdraw(float amount) {
balance -= amount;
}
// a class, or static, method
public static void setInterest(float interestRate) {
interest = interestRate;
}
public static void main(String[] args) {
// create a new account object
BankAccount account = new BankAccount();
// deposit $250.00 into the account
account.deposit(250.00F);
// set interest rate for all BankAccount objects
BankAccount.setInterest(5.0F);
}
}
|
Access modifiers
Like Visual Basic, the Java language allows you to set a class member's visibility. Java members use the public modifier to indicate that a member is freely accessible both inside the class and outside. Java members use the private modifier to indicate that the member is accessible only inside the class. Outside of the class, private members are inaccessible.
Consider the BankAccount class again. Assume you want other programmers using BankAccount objects to change the balance by using the deposit() and withdraw() methods. You'll declare these methods to be public, so they can be invoked in code outside of the BankAccount class. However, you don't want other programmers to change the balance field directly, so you make the balance field private.
You might be wondering what the default access level is -- that is, the access level for a class member you don't declare with either the public or private modifier? You might guess that the default access level is public, the default access level in Visual Basic. In fact, the default access level in the Java language is called package access, because only classes in the same package have access to these class members. If you want to declare a member with package access, don't use an access modifier keyword.
The Java language defines one further access level, called protected. You use the protected modifier when you want a member to be accessible in subclasses. We'll discuss protected class members a little later in the article.
Creating objects
If you look at the main() method of the BankAccount class in Listing 12, you can see that the code created a new BankAccount object, like this:
BankAccount account = new BankAccount();
|
First, you declare an object (that is, a variable) of type BankAccount. As you can probably guess, the new keyword sets aside enough memory to create a new object. The new object is actually created by this statement: BankAccount(). This statement looks like a method call. However, Listing 12 didn't declare a method with this name, so you might wonder what the statement is doing.
In fact, the statement is a constructor call. You can't create Java objects without a constructor, so if you write a class without a constructor, the compiler creates a default one. That's why you can call BankAccount(), even if you don't explicitly write a constructor in the BankAccount class.
 |
Java classes: A quick review
Class members: Java class members are fields and methods. Fields represent data, and methods represent operations. A class is a declaration of a class of objects, which are defined in terms of the class's members.
Access modifiers: You use access modifiers to limit the visibility of class members and constructors outside of the class in which they're defined. Most often, you'll encapsulate all the data in a class by declaring class fields private, and you'll define the interface of a class by writing public methods.
Constructors: You define constructors as a way to let other programmers create instances of your class. Generally, you'll define constructors that make it easy for another programmer to create an object that's initialized properly.
|
|
Visual Basic supports the concept of a constructor by letting you define a procedure called Class_Initialize for each class, but, unlike the Java language, it doesn't allow you to pass parameters to it.
Java constructors don't have return types; all constructors implicitly return a new object of the class in which it is defined. Every Java constructor must have the exact same name as the class in which it is declared. Otherwise, constructor declarations would be pretty much the same as method declarations. In particular, constructors can take parameters, just like Java methods.
Strictly speaking, a constructor isn't a kind of method, because methods are class members and constructors aren't. Class members, like fields and methods, are inherited in subclasses. Constructors are never inherited.
Explicit references
The Java language uses the this keyword to reference the current object. You can use the this keyword to refer explicitly to fields, methods, and constructors in the current class.
A common use for the this keyword is to resolve variable-scope issues. For example, the BankAccount class has a field called balance. Let's say you want to write a method called setBalance(float balance), which sets the object's balance field. The problem is that inside of the setBalance(float balance) field, when you refer to balance, you're actually referring to the balance parameter, not the balance field. You can refer to the field explicitly by using the this keyword, as in Listing 13.
Listing 13. The "this" keyword
public class Account {
public void setBalance(float balance) {
this.balance = balance;
}
|
Inheritance
Inheritance is one of the most important benefits of object-oriented programming. It's important that you understand inheritance correctly in order to use it to the greatest effect. Inheritance involves these key concepts:
- The
extends keyword: Inheritance is defined when a class is declared. You use the extends keyword to specify the superclass of the class you're writing.
- Constructors: Constructors aren't inherited in subclasses, but you often invoke the constructors of superclasses in your subclass's constructors.
- Overloading/overriding: Overloading refers to writing several methods with the same name but different parameters. Overriding refers to changing the implementation of a method that's inherited in a subclass.
- The
Object class: All Java objects ultimately inherit from the Object class, which defines the basic functionality that every Java object is guaranteed to have.
- Interfaces: An interface is a description of behavior that provides no implementation.
Extending classes
In Visual Basic, a class can't inherit from any other class, but the Java language allows single inheritance. Inheritance is a way to reuse code. When class A inherits from, or extends, class B, class A automatically inherits all of the public and protected members of class B. If class A is in the same package as class B, class A also inherits all of the members with default, or package, access. It's important to note, however, that subclasses never inherit the private members of the classes they extend.
Once you extend a class, you can add new fields and methods that define the attributes and operations that make your new class distinct from the superclass. Also, you can override the operations of the superclass that must behave differently in the subclass.
You can explicitly extend a class when you define it. To extend a class, you simply follow the name of the class with the extends keyword and the name of the class you want to extend. If you don't explicitly extend a class, the Java compiler automatically extends the class Object. In this way, all Java objects are ultimately subclasses of the Object class.
An extension example
Suppose you want to create a new CheckingAccount class. A CheckingAccount is a special kind of BankAccount. In other words, a CheckingAccount has the same attributes and operations as a BankAccount. However, a CheckingAccount also has an added operation -- cashing a check. So you can define your CheckingAccount class so that it extends BankAccount and add a cashCheck() method, as in Listing 14.
Listing 14. Extending classes
public class CheckingAccount extends BankAccount {
public void cashCheck(float amount) {
withdraw(amount);
}
}
|
Subclass constructors
Constructors aren't really members of a class, and constructors aren't inherited. A BankAccount constructor creates BankAccount objects, so you can't use it in the CheckingAccount class to create CheckingAccount objects. You can, however, use constructors from a superclass to initialize the parts of a subclass that are inherited. In other words, you often need to call superclass constructors in subclass constructors to partially initialize your subclass objects. You can do this by using the super keyword, followed by a parameterized list representing the arguments of the super class constructor you want to call. If you're using the super keyword in a constructor to call a superclass constructor, it must appear as the first statement in the constructor body.
For example, you need to write a CheckingAccount constructor to initialize CheckingAccount objects. You want to create CheckingAccount objects with an initial balance, so you pass in a dollar amount. This is just like a constructor in the BankAccount class, so you'll use that constructor to do all the work for you, as in Listing 15.
Listing 15. Subclass constructors
public class CheckingAccount extends BankAccount {
public CheckingAccount(float balance) {
super(balance);
}
public void cashCheck(float amount) {
withdraw(amount);
}
}
|
You can also use the super keyword to explicitly refer to superclass members from a subclass.
Overloading and overriding
The Java language allows you to define several methods with the same name, as long as they take different parameters. For example, Listing 16 defines a second cashCheck() method that takes the amount of the check to be cashed and a fee to be applied for the service. This is called method overloading.
Listing 16. Method overloading
public void cashCheck(float amount) {
withdraw(amount);
}
public void cashCheck(float amount, float fee) {
withdraw(amount+fee);
}
|
Often, when you create a subclass, you want to override the behavior of a method inherited from a superclass. For example, let's say that one difference between a CheckingAccount and a BankAccount is that a fee is applied when you withdraw money from a CheckingAccount. You need to override the withdraw() method in the CheckingAccount class so that a $0.25 fee is applied. You can define the CheckingAccount withdraw() method in terms of the BankingAccount withdraw() method, by using the super keyword, as shown in Listing 17.
Listing 17. Method overriding
public void withdraw(float amount) {
super.withdraw(amount+0.25F);
}
|
The Object class
The Object class is a special class in the Java class hierarchy. All Java classes are ultimately subclasses of class Object. In other words, the Java language supports a centrally rooted class hierarchy, and the Object class is the root class of that hierarchy. A similar concept exists in Visual Basic with Object variables that can be instantiated later to any type of class.
Because all Java objects inherit from the Object class, you can call the methods defined in Object for any Java object and expect similar behavior for each. For example, the Object class defines a toString() method, which returns a String object that represents the object. You can call the toString() method for any Java object and expect to get back a string representation of that object. Most class definitions override the toString() method so that it returns a specialized string representation for that particular class.
Another implication of having Object at the root of the Java class hierarchy is that all objects can be cast down to Object objects. In the Java language, you can define data structures that take objects of the Object class, and these data structures can hold any Java object.
Interfaces
We've already mentioned that a Java class allows only single inheritance, which means that a Java class can extend only one class. The designers of the Java language felt that multiple inheritance was too complicated, so instead they decided to support interfaces. An interface is like a class that can't be instantiated, with methods that are defined but not actually implemented.
You declare an interface just like a class, except you use the interface keyword instead of the class keyword. An interface can extend any number of superinterfaces. Methods inside an interface can't include an implementation. Interface methods are simply method definitions; they don't have bodies. This is the same concept that Visual Basic uses for interfaces; they consist of property and method declarations without code.
An Account interface
The code in Listing 18 shows how you might write a basic Account interface that defines a base set of functionality for bank accounts. Notice that there are no bodies for the methods you declare in an interface.
Listing 18. The Account interface
public interface Account {
public static final float INTEREST = 0.35F;
public void withdraw(float amount);
public void deposit(float amount);
}
|
Implementing interfaces A Java class can extend only one class, but it can implement any number of interfaces. When a class implements an interface, it must implement every method defined in that interface.
Listing 19 defines a SavingsAccount class that implements the Account interface. Because the Account interface defines two methods -- withdraw(float amount) and deposit(float amount) -- the SavingsAccount class must provide an implementation for them. The SavingsAccount class can still extend another class, and it can implement any other interfaces, as long as they don't define the same members as the Account interface.
Listing 19. Implementing interfaces
public class SavingsAccount implements Account {
private float balance;
public SavingsAccount(float balance) {
this.balance = balance;
}
public void cashCheck(float amount, float fee) {
withdraw(amount+fee);
}
public void withdraw(float amount) {
balance += balance;
}
public void deposit(float amount) {
balance -= balance;
}
}
|
Taking stock
At this point, you should have a grasp of the Java language's essential components and comfortable writing simple Java programs. Specifically, you should be able to:
- Write a Java class with a
main() method, compile it, and run it.
- Write a Java interface and compile it.
- Write one or more constructors for your class.
- Write a class that extends another class and implements one or more interfaces.
- Create and use objects using the new keyword and constructor calls.
You should also confident enough to begin examining and playing around with more advanced Java code. A good place to begin is with the Java platform classes themselves. The best way to gain experience using the language is to browse the API documentation (see Resources) and start writing programs that use these classes. Also, see the sidebar Honing your skills for some select resources to supplement this article.
Web application architecture with Java technology and J2EE
Now that you know a lot more about the Java language than you did at the outset of this article, it's time to return to the subject of Web-enabling Windows client-server applications. Structuring your Java or J2EE application as a multitier, modular, component-based architecture provides many advantages in the areas of Web enablement, reuse, maintainability, and flexibility.
A typical J2EE Web application architecture is based on the Model-View-Controller (MVC) architectural design pattern (see Figure 1) and comprises the following key elements:
- Clients based on a thin-client Web browser/Java applet model, which enables universal access to server-based Web applications from browser-based and full Java language based clients, providing on-demand delivery of application components. A properly architected Web application enables multiple interface types for both end users and external applications. J2EE's use of Java servlets and JavaServer Pages (JSP) technologies lets users access applications from thin-client Web browsers and other devices via HTTP. You can use HTML, WML, XHTML, XML, JavaScript, Java applets, and other thin-client technologies to build thin-client interfaces. You can also use the Java language and J2EE to build full-featured "thick client" applications to access your server-based applications within an internal network/firewall.
- A network infrastructure that provides services such as TCP/IP, firewalls, routers, LDAP directory servers, Web servers, and security -- whose capabilities you can access via open-standard interfaces and protocols.
- Business-logic components that enforce a business unit's policies and processes by controlling the execution of transactions and requests users submit through the user interfaces to access and update back-end data sources and applications. Java and J2EE application components that can implement application business logic include servlets, JavaBean components, and Enterprise JavaBean (EJB) components.
- Application-server software that provides a platform for Web-based e-business applications. It typically includes an HTTP server, database and transaction services, session management, mail and groupware services, and messaging services. J2EE application servers such as Apache JBoss and IBM WebSphere can provide these services. You need a J2EE application server to deploy and run the J2EE server side of a Web application.
- Integration middeware and components that provide access to existing data, applications components, data sources and, in some cases, complete applications. Java technology and J2EE provide a number of standard components and technologies for data-source integration, data-source entities through entity EJB components, messaging services, and native platform services and components. Web applications can also access existing platform-specific data and application components through a variety of tools and components.
- Back-end data sources and existing non-Java applications and application components: For the purposes of this roadmap, these assets are typically Windows application components that you can't or won't migrate to Java or J2EE and must integrate with the overall Java technology or J2EE solution. New Java or J2EE application services can also directly or indirectly access vital data sources that these Windows application components connect to. For example, you could replace a Microsoft SQLServer client component with a Java data-access component you implement using the JDBC API.
- A Web application-programming environment and development tools that provide the server-side Java programming and J2EE programming environment for creating, assembling, deploying, and managing dynamic and robust e-business applications.
Figure 1. MVC with J2EE Web applications
Accessing native Windows components
The Java programming environment provides classes and libraries for most commonly used platform-independent system services, including TCP/IP networking and sockets, file system resources, and printing. (We address windowing and user interface functions in User interface considerations, later in this article.) Because you've decided to implement your application for Web enablement with Java technology, you should replace any of these platform/Windows-specific services and functions with their Java-enabled counterparts. For example, replace communications using NetBIOS or Windows networking with TCP/IP and sockets using the java.net package equivalents, and replace Windows file system functions with the java.io package equivalents.
The Java Native Interface (JNI)
JNI provides a mechanism for native C/C++ and Java code to interoperate. It is a documented and supported API of the implementation the JVM itself uses for access to the underlying native platform operating system services. These services include common functions available on most platforms, such as communications, networking, application configuration, process management, and file system. The native platform services can also include services specific to individual platforms, such as Windows-based networking, device management, printing, and COM/DCOM.
If you choose to use JNI to access your native Windows components, you're depriving yourself of one of the major value propositions of using the Java language -- platform independence. However, using JNI might be necessary in some cases. For example:
- You're prototyping a Java implementation of your application and can provide the thin-client interface and Java Web components as front ends in a Web application prototype.
- You're staging the migration of the application components to the Java language or J2EE in phases. As a stop-gap measure, you access the services of some of the remaining non-Java components as their current Windows implementations.
- The application accesses services or data for which the interface is platform-specific (for example, COM/DCOM components).
- The services or data the application accesses are provided through a component or external application that's impractical to include in the migration to the Java language. (For example, the source code isn't available because another company or partner owns it and isn't allowed to modify or redistribute it.)
- You plan to migrate application's components to Java or replace them with externally available Java components at a later time, and you must use the native platform component.
See Resources for some excellent resources on JNI.
Other tools and technologies
In addition to JNI, several other tools and technologies facilitate accessing native Windows components from the Java language. As with JNI, you should limit your use of these technologies to cases in which you can't implement the integrated native code component in the Java language or J2EE, or plan to do so later.
The JNI++ project
The JNI++ project supplies two code-generating utilities and a core C++ library that simplify programming to JNI in C++. Writing simple JNI programs that access fields and use simple accessor and modifier methods in native C/C++ classes that have only relatively simple data structures is fairly straightforward. But using JNI to provide access to C/C++ classes with complex data structures, exception handling, and requiring callbacks from C/C++ to Java code is much more challenging. The JNI++ code-generating utilities are designed to minimize the amount of time it takes to map between the worlds of C/C++ and Java language. JNI++ generates much of the code required to access C++ classes from Java language and vice versa. The core native library provides a simplified interface for the JVM and the JNI environment for each running thread. This library also contains wrapper classes for the raw JNI data types and handles the translation between Java code and C++ exceptions.
Interface Tool for Java
The IBM alphaWorks Interface Tool for Java (formerly named Bridge2Java) lets Java programs communicate with ActiveX objects in order to integrate ActiveX objects into a Java environment easily. Interface Tool for Java uses JNI and COM technology to let you treat an ActiveX object exactly like a Java object. You simply run a proxy-generating tool that creates Java proxies from the ActiveX control's typelib. You can then use these proxies to let a Java program communicate with the ActiveX object. Interface Tool for Java includes samples that show how the Java application code accesses the Java proxies the tool generates in order to interact with a variety of COM objects, including Lotus 1-2-3 spreadsheets, Microsoft Excel, Microsoft Word, Microsoft Outlook, Microsoft Calendar, and Microsoft Internet Explorer.
Codemesh JunC++ion
JunC++ion lets you mix and match Java components and C++ components to solve problems such as Web-enabling C++ applications, integrating C++ clients into an EJB environment, implementing an EJB component in C++, and letting both Java and C++ components use a single set of APIs.
JNIWrapper
JNIWrapper provides a Java interface, through JNI, to platform-specific (Windows and Linux) features and services that the platform-independent Java environment doesn't provide. Some application platform-specific operations, such as operating with Registry items under Windows, aren't supported in the Java language. To use JNI to provide this capability, you need to implement a native library and classes, interface with it, and test and debug in both a Java debugger and a native-side debugger. JNIWrapper provides the Java library for calling native library functions. With JNIWrapper, you can access operations and features of the native system (like tray icons or a custom-shaped splash screen) in your Java application.
Jawin integration project
Jawin (Java/Win32) is a free, open source architecture for interoperation between Java components and components exposed through Windows COM objects or Windows DLLs. Jawin lets your Java applications call any legacy COM- and DLL-based code, without requiring you to write any JNI code. Your code can interact with scriptable applications such as the Microsoft Office suite, call scriptable logic components such as Microsoft's COM-based XML parsers and tools, and access Win32 API features such as the Windows Registry, security APIs, and the event log. Jawin includes a code generator for scriptable COM components. The code generator reads a type library and automatically emits the Java stubs you need to call the component from a Java application.
Stryon i-HUB
Stryon Corp. provides a number of technologies in its iHUB server products that let Java and J2EE applications access existing Windows .NET and COM applications. iHUB also includes a Java-COM+ bridging middleware, which links Microsoft ActiveX, DLLs, and COM+ to Java applications running on a Java-enabled platform. Using the Java2COM bridge, Java applets and applications can support existing native codes.
User-interface considerations
Migrating the user interface is the biggest challenge in moving from a client-server application to a Web-based application. Client-server applications typically have rich user interfaces that can be difficult to duplicate with a Web-based interface. Simply trying to rewrite each screen as a Web page is usually an exercise in futility. A good analogy is translating a book from one language to another using a phrase-by-phrase literal translation, an approach that usually leads to awkward phrases that don't convey the original author's message. Obviously, a better approach is to express the author's message in the new language. The same is true for user interfaces: A client-server application you migrate to a Web-based application is better if you design the Web interface using best practices for Web design, rather than a simple screen-to-Web-page mapping. Let's look at some of the options available to you for the User Interface to your J2EE application.
Web-based interface
Most Web-based applications can utilize a Web browser and browser-based extensions, such as MIME handlers and Java applets, as their user interface. One major advantage of this approach is that on the client side, everything needing to run the application is contained in the browser or is downloaded from the server whenever the application is run, making the application easier to manage. Applications with a Web browser user interface can be written using Java Servlets, JSP technology, HTML and JavaScript.
Java Server Faces (JSF) is a related specification that lets J2EE tool vendors provide drag-and-drop capability for the development of J2EE Web-based UIs. It also lets vendors develop custom components their development tools can use. To see JSF in action, take a look at the WebSphere Studio version 5.1.1 family of tools (see Resources). WebSphere Studio has a fully integrated tool called Page Designer, which you can use to develop HTML pages and JSP pages visually with drag and drop. Page Designer has implemented the JavaServer Faces specification, and allows you to drag and drop components like HTML form elements on to your pages as well as more advanced components that allow you to bind an HTML table to a back-end data source.
Start here to learn the dos and don'ts of designing Web interfaces:
useit.com
Jakob Nielsen, a recognized expert in Web user-interface design, offers a wealth of information -- including best practices -- on this site. You'll also find links to his several books and articles on the subject.
Start here to learn more about JavaServer Faces:
JavaServer Faces home page
Get the official word on JSF from Sun
Magical Web Interface Development
This article shows how JSF offers server-based power and flexibility for building Web-based interfaces that keep components in sync with your business objects.
Developing JSF Applications using WebSphere Studio V5.1.1 -- Part 1
This article offers hands-on exercises with JSF development.
JSF Central
A JavaServer Faces community site that provides access to resources to develop JSF-related technologies.
Applets
Applets are miniature Java applications that users download across a network and execute in a Web browser. Applets are typically considered untrusted because they're sent anonymously across a network and execute within a secure, restricted "sandbox" that isolates them from all parts of the local system outside the current browser session. However, authors can "sign" their applets, and browser users can allow signed applets from trusted providers to have privileges -- such as access to the local file system and other resources -- normally associated with full Java applications.
Applets were first implemented using the original windowing toolkit in the very first releases of the Java SDK. The Java 2 SDK introduced the capability for applets to use Swing components rather than the original windowing components, giving them a more responsive and platform-specific look. See Resources for more about applets.
Browser "helpers"
An alternative to Java applets is browser helpers and MIME type handlers. These can be useful when a browser-based GUI needs to access files and resources, which the Web browser cannot natively render (visual resources) or "play" (media types). Examples are application content in specialized visual formats such as maps, spreadsheets, word processing file types (Adobe Acrobat, Microsoft Word, Lotus WordPro, etc); device class-specific files such as PostScript files; multimedia formats such as video, audio, speech, etc; and application-specific formats that could be of arbitrary format and function such as external application installers, software inventory utilities, virus scanning tools, financial or tax software formats, etc.
Start here to learn more about browser helpers and MIME handlers:
Extending the Browser with Plug-ins
This article covers plug-ins, client side Java programming, client-side scripting, and the DOM and dHTML.
Web services
Web services provide an alternative approach to migrating your client-server Windows applications to J2EE. A Web service is a self-contained, modular application that you build on standard Internet and XML technologies and describe and publish to a network for use by other programs. Web services are the next step in the evolution of distributed systems. They allow businesses to make their assets readily accessible worldwide through the Internet and dynamically connect and execute transactions through open Internet protocols.
By using Web services standards like SOAP, you can keep your current Windows user interface and use Web services to access your J2EE-based business logic. With this approach you'd rewrite your business logic using J2EE standards to take advantage of platform independence, remote access, and scalability for your server based J2EE code, while keeping your Windows client interface the same to minimize the impact on your end users.
Start here to learn about using Web services:
Speed-start Web services
The Speed-start Web services program has DVDs with the latest software-development tools and middleware (trial editions) from IBM, loads of online tutorials and articles, hands-on workshops and technical briefings, and an online forum moderated by IBM Web services experts to help answer your questions.
Java client interfaces
If you need to keep your application's rich-client look and feel but also can run your application on a variety of operating-system platforms (like Linux) then you should consider building a Java client interface for your J2EE application. Your application can then make use of standard APIs like RMI, Web services, and EJB technology to interact with your J2EE server code, as well as system services such as file access, networking, multimedia, and of course, graphical windowing functions.
This approach requires you to distribute the initial version of the application and subsequent updates to the users, through either a manual process or a centrally managed, automated distribution or sharing mechanism. (A "thin-client" browser-based interface using Java applets, Web browser plug-ins, and MIME type "helper" applications is usually easier to manage, because the code downloads from the Web server each time it's activated.)
Start here to learn about writing Java client applications:
" The Java 2 user interface"
This developerWorks article explores various features of JFC/Swing, including the pluggable look and feel capability, drag-and-drop support, support for Java 2D graphics, audio APIs, accessibility, automated events with AWT Robot, and media support (including 3D graphics, advanced imaging, the Java Media Framework, and speech).
Eclipse.org
Eclipse is a Java-based, open, and extensible IDE. Operating under a open source paradigm, with a common public license that provides royalty-free source code and worldwide redistribution rights, the Eclipse platform provides tool developers with flexibility and control.
"Using the Eclipse GUI outside the Eclipse Workbench, Part 1: Using JFace and SWT in stand-alone mode"
With the Standard Widget Toolkit (SWT) and JFace, you can develop a standalone Java application that more closely resembles the look and behavior of a native application. SWT is a windowing toolkit with a platform independent API that is tightly integrated with the native operating system. JFace is a set of utilities built on top of SWT to make it easier to code GUI applications based on SWT. Both SWT and JFace are part of the open source Eclipse project and can be used to integrate Java applications with native platform components, such as ActiveX controls, within a standalone application. The standard Java user interface and windowing system -- Swing -- is a sufficient and proven system for developing user interfaces for client-side applications; however, it lacks the appearance and style of native applications, whereas SWT uses the operating system's native windowing environment directly.
"Integrate ActiveX controls into SWT applications"
With SWT, you can develop a standalone Java application that feels and operates like a native application. This developerWorks article shows you how to leverage and integrate ActiveX controls within a standalone SWT application.
Deployment environments for J2EE applications
J2EE applications don't run directly on a Web server (such as IIS or the Apache Web server). Instead, a separate component called an application server runs them. Application servers coexist peacefully with your Web server of choice on your platform of choice. A variety of both commercially available and open source application server environments are available. You can learn about two of them from these resources:
The Apache Software Foundation
Apache is an open source project that provides several widely used Web-deployment technologies. These include a Web/HTTP server (the Apache Web Server) and a servlet container/JSP processor (Tomcat). The Apache Web Server has been the most popular Web server on the Internet since April of 1996 and is now more widely used than all other Web servers combined. Tomcat is the servlet container used in the official reference implementation for the Java Servlet specification and the JavaServer Pages standard.
WebSphere Application Server V5.1 - Express
IBM offers a cost-effective, out-of-the-box solution for managing simple yet dynamic Web sites with a simplified J2EE based Web application server and a development environment based on WebSphere Studio.
WebSphere for newcomers
This roadmap provides an introduction to the IBM WebSphere family of products plus resources to help get started with developing and deploying J2EE solutions using the WebSphere products.
Conclusion
We hope this roadmap has given you a useful overview of the tasks and technologies involved in migrating client-server Windows applications to Java and J2EE Web applications. Congratulations on taking this first step onto the open road of Java programming.
Resources
|