After a very short history of Java, we will jump right into Java programming. We will create and use a bare bones program to demonstrate the Java basics and the capabilities of Rational Application Developer.
After finishing this chapter, you should understand:
Using WebSphere, you will be able to:
The Java Language
Java shares many of the same characteristics as spoken and written languages such as English, Spanish, and so on. For instance, both Java and spoken languages consist of a unique set of words. In Java, these words are called keywords. Java also uses symbols (; , {}, (), etc.), just as written languages use punctuation marks. All of the symbols and keywords that comprise the Java language are referred to as tokens. (Another definition of a token is the smallest unit of the Java language.) We mention this right at the beginning of the text because error messages often cite an “incorrect token” or “token expected” as problems—not that we are expecting you to make any errors!
Programming languages also have rules of grammar that must be followed. These grammar rules are called the programming language’s syntax. Just as a written language’s grammar dictates how to combine words and punctuation into sentences and paragraphs, the Java syntax dictates how tokens are combined to create Java statements, methods, and classes.
Who makes the rules? Oracle. Sun Microsystems (acquired by Oracle in 2009) originally developed Java in the early 1990s and modeled it after the very popular C++ programming language. Java shares many of the same syntax rules and keywords as C++ but the major difference with Java is its network orientation. The Java language was designed so that graphical, two-way interactions between computing devices can be easily created.
In the early 1990s, the Internet was primarily text-based. Sun, working with Netscape, enabled the Netscape browser to download Java appletsfrom another computer (called a server). The applet ran on the user’s PC (known as the client), and the applet results were displayed in the browser window.
Java programs can also be stored and run on a client. These types of Java programs are called client-based applications. Finally, Java programs can be stored and run on a server and the results sent to the PC’s browser for display. There are many different types of Java programs that can run on the server. As a group they are called a server-side (or server-based) application. However, each different type of Java program (Servlet, JSP, Bean, etc.) has advantages and disadvantages and a specific purpose in the application. We will explore this in later chapters.
Oracle/Sun has continued to work with many companies (Microsoft, IBM) and international organizations to insure that Java is compatible with all hardware and operating systems. Of course, there is also competition. Microsoft offers a number of programming languages, specifically J# (pronounced “jay sharp”), that compete with Java and an Integrated Development Environment (IDE) called .Net (pronounced “dot net”) that competes with IBM’s WebSphere.
Classes
Java statements are grouped into a class. A class is comparable to what other programming languages call a program. A class begins with a header. The class header identifies the Java code as a class and defines class attributes. For instance, a class header can include an access modifier (e.g., public, private), the keyword class, and the class name with at least one space between each. For instance, the following class header defines a class called Employee (note we still need to add a body to this class definition):
public class Employee
The words public and class are examples of keywords (also called reserved words). A keyword has a specific purpose in Java and can only be used in the manner dictated by the Java syntax. For example, class identifies the code as a class, and public means that any other class can access Employee. The access modifier public must come before the class keyword, and the keywords public or class cannot be used as the name of the class. There are many other keywords (such as if, else, do, while, return) that also cannot be used as a class name, and there are a couple other rules that must be followed. For instance, class names can consist of letters, numbers, and some special characters, however, it is strongly recommended that class names begin with an uppercase letter. Table 1-1 shows a brief list of the rules and examples.
Class name rule | Good | Bad |
---|---|---|
Begin with a letter | Sale1 Sale$ | 1Sales |
No spaces | Tax_Calc TaxCalc | Tax Calc |
No keywords | MyFirstClass Class | class do |
Notice that the third row in Table 1-1 lists “Class” as a valid name but “class” as invalid. This highlights another feature: Java is case sensitive. This means that classes named Employee, EMployee, and EmployeE are all considered different classes. In addition, if you referred to employee or EMPLOYEE, the system would not find a class with that name. Be aware and careful of your capitalization! It is customary (but not required) to begin class names with a capital letter and capitalize the first letter of each “word” within the class name (e.g., MyFirstClass). This mix of upper- and lowercase letters is called “camel case.”
All of the Java code following the class header is called the body of the class and is enclosed in braces, { }. Therefore, a valid class definition would be:
public class Employee {}
However, as there are no Java statements between the braces, this class does not do anything.
The class body is comprised of what we will refer to as class variable definitions and methods. Variables are categorized by their scope. This text will define class variables as those variables that can be accessed by any statement within the class. The official Java definition of class variables is much more specific and has many other variable classifications (such as instance variables). However, the distinctions between the various variable scopes are beyond this introductory discussion of Java.
Class variable definitions traditionally follow the class header. Simply stated, the purpose of a variable is to hold stuff, but we will discuss this in more depth later. Variables are also be classified by the type of “stuff” they hold. For example, the following Java statement declares (defines) a String variable called empName. String variables hold String objects:
String empName = new String();
Let’s explain the various pieces of this statement. The definition begins with the variable type (String), at least one space, and the name of the variable (empName). This creates a String variable called empName. Think of this as telling the computer to reserve some space in memory and calling this space empName. Next, the equal sign assigns a value (or in Java-speak, an object) to this variable. Please note that the Java equal sign is not like a mathematical equal sign. The Java equal sign associates an object or value on its right to a variable on its left. So in this case, new String() creates an empty String object (meaning no text has been assigned), and the equal sign assigns the String object to the variable empName.
Another way to look at the statement is that everything to the right of the equal sign creates the String object and everything to the left creates the String variable empName.
Finally, there is a semicolon (;). Java statements end with a semicolon. This is a requirement. In fact, forgetting the semicolon will be your most common coding mistake. (Try not to get too frustrated the first thousand times you do it.) If you do not specify a semicolon at the end of a line, Java assumes that the statement is not finished and will look to the next line for more of the statement. For example, the empName definition above can also be written as follows:
String
empName
=
new
String();
Although perfectly valid, this is one ugly looking statement.
As mentioned, strings can be assigned text. When a String object is created, a text value can be assigned at the same time as follows:
String empName = new String("Joe Employee");
The value of a String variable can be changed very easily (which is unique for Java variables. In other words, since most other variable can’t be changed as easily, don’t get used to this!) The following would assign empName to a String object with text of Mary Worker:
empName = "Mary Worker";
Methods are subsections of a class that contain executable statements. An executable statement performs an action (e.g., adding two variables, printing, etc.). Methods can receive and return variables. Methods, like classes, require a header. A method header has an access modifier and the method name. In addition, the header defines what data the method expects (is receiving) and what data the method will return. For instance, the following header defines a method called salaryCalc:
public double salaryCalc( int hoursWorked, double payRate)
The access modifier (public) comes first, is followed by a space, and then the type of variable (double) that the method will return. In this case, salaryCalc will return a variable of type double (more on this type of variable later). There is another space and then the name of the method is next. It is customary to begin method names with a lowercase letter. The method name is followed by parameters for the values that the method is expecting. The parameters must be enclosed in parentheses and separated by a comma. Parameters define method variables that will hold the passed values. Method variables are different from class variables because they have a more limited scope. In other words, class variables are considered global in scope because any method (within the class) can use a class variable. Method variables are local in scope because they can only be used in statements within the method that defines them.
Classes can contain specialized methods. For now, the two specialized methods we will discuss are the main method and a type of method called a constructor.
The main Method
When you run a class as an application, Java looks for and runs the class’s main method. The following is a valid main method:
public static void main(String[] args) { }
There must be at least one space between each keyword (public, static , void) and the method name (main). Also, the tokens must be in the order shown. You are already familiar with the purpose of the access modifier public. The keyword void means that the main method does not return anything. String[] args defines the expected data as an array of String variables called args. One nice feature of Java is that if the person running the class does not specify an array of strings, Java automatically supplies one at runtime. Finally, the method is defined as static. A static method does not need any class variables or other methods to work properly. In other words, a static method can be executed as a “stand alone method.” Usually only one class within an application is coded with a main method. This single main method creates the objects that comprise the application. In other words, the main method “kicks off” the application.
Most classes are not run as applications; rather, most classes are instantiated. Instantiated is a very intimidating word. Essentially, when a class is instantiated, a copy (also called an instance) of the class is placed in the computer’s main memory. A class instance is also called an object. You can actually have many instances of a class or, to say it another way, many objects of the class type.
For instance, we could instantiate two Employee objects. One object could have a pay rate of ten dollars per hour and an employee name of “Joe Smith.” The other Employee object’s pay rate could be twelve dollars an hour and have an employee name of “Mary Jones.”
You actually have already instantiated a class (i.e., you have already created an object). A String object was created when new String(""Joe Employee"") within the following statement was executed:
String empName = new String("Joe Employee");
If you executed the following statements, you would have two more String objects:
String empAddr = new String("1 Main St");
String empCSZ = new String("Albany, NY 11508");
Therefore, in the example, there are three unique String objects. Since an object is an instance of a class, this means that there is a String class. The String class was created by the Java developers and “comes with Java.”
If you’re a little confused, don’t worry. We will cover instantiation and explain “what comes with Java” in greater detail in later chapters. For now, just remember that there are a number of very useful classes that come with Java and that these classes are used to build sophisticated Java applications quickly.
When an object is created, Java runs the instantiated class’s (i.e., the object’s) constructor. A constructor is a method with the same name as the class that does not return any value. For example, the constructor method for the Employee class would be called Employee and could be defined as follows:
public Employee() { }
Notice that a return variable type is not specified. This is a rule for constructors: they cannot return any data. The example is also considered a null (or default) constructor because it does not accept data (i.e., no parameters are specified). However, a constructor can accept information. The following defines a constructor that accepts a String object, creates a String variable called name and assigns the String object to name:
public Employee(String name) { }
As mentioned, when the Employee class is instantiated, the constructor method is automatically run. In the above example, however, the constructor does nothing. Constructors are often used to initialize variables needed by the class methods. For instance, the following constructor assigns the passed String object to the class variable empName:
public Employee(String name) {
empName = name;
}
This is similar to the algebraic statements: A=1, B=A. In the Java example: name = String object, empName = name. Therefore, name and empName contain the same value.
WebSphere
WebSphere is a group of IBM software products that includes all of the “development tools” that a programmer would need to write, debug, and install Java applications. “Development tools” is a category of software that usually includes a code editor, syntax checker, debugger, and many other useful programming utilities. In addition, WebSphere includes software that can be installed on any computer to make that computer a Java application server.
There are many “versions” of WebSphere products (Express, Standard, Enterprise, etc.). These different versions simply have different sets of tools. As of this writing, the Enterprise Editions have the most complete and powerful set of Java development tools.
We will use the development tools provided by the Rational Application Developer (RAD). We will begin with a tour of the RAD “client environment” and then demonstrate several of the “tools” used to create and run Java applications. Later in the text, we will cover the WebSphere Application Server (WAS) software.
Tutorial: Starting Rational Application Developer
Let’s get started:
Note If Rational Application Developer is running for the first time, this may take a little while.
The Rational Application Developer (RAD) will be started and the default “perspective” will be displayed (see Figure 1-4). RAD provides several different “views” of Java applications. These different views are called perspectives. Each perspective provides a unique set of panes, functions, command options, tool bar buttons, and so on. Initially, the Java EE (Java Enterprise Edition) perspective is displayed. You can tell which perspectives are open by the icons on the upper right of the window. In this case, the arrow in Figure 1-4 is pointing to the Java EE icon.
Let’s examine perspectives:
The initial Java perspective is comprised of four panes. All the panes can be resized by clicking and dragging on their borders and some panes can contain different views. Each view has a tab at the top of the pane that displays the views name and, at least, a close button. You can switch between views by clicking on the tabs. Initially, the Package Explorer view, the editing area, and Outline view display nothing. However, as Java classes are created the views contents will change. Most of the time, these views will display (respectively) a project navigation tree, source code, and a Java class navigation tree. One of the views provided in the task pane (at the bottom of the perspective) keeps track of work (e.g., problems) that needs to be completed.
Tutorial: Creating and Deleting a Project
RAD stores everything in projects. Projects are comprised of packages and packages contain Java classes. This means that a project and package must exist before creating a Java class. (Think of projects and packages as specialized folders. In fact, a project and its packages are implemented as folders when a project is exported from RAD to a Windows environment.)
Note MyFirstProject now appears in the Package Explorer view.
Now let’s create a package:
Note MyFirstProject/src already appears in the Source folder field. This is because MyFirstProject was selected in the “Package Explorer” view and RAD requires that all source code packages be in project subfolder called src (source). (RAD does a lot for the programmer but it also sometimes imposes its own unique standards.) The Browse button to the right of the Source folder field can be used to find and select a different project.
The project navigation tree allows the programmer to easily navigate and manipulate the Java projects, packages, and their contents. Notice to the left of each item name is an icon that indicates the item type. To the left of some of the item type icons are the symbols . These are expansion icons. Expansion icons appear next to items that contain other items. These icons indicate if the tree item’s contents are displayed () or are not displayed (). In this case, the contents of MyFirstProject and src are displayed, but the JRE (Java Run time Environment) System Library package’s contents (created by RAD when the project was created) are not. myFirstPackage does not have an expansion icon because it was just created and is empty. You can display and close a sub-tree by clicking the item’s expansion icon or double-clicking the item name or item type icon.
Tutorial: Creating a Java Class
Do you remember all the syntax rules for defining a class header? Probably not. Fortunately, RAD will walk you through the process. In other words, just as you created a project and a package, RAD will supply a series of windows to help you easily define a class:
Note The source folder and package names are already specified. Because myFirstPackage was selected in step 1, RAD assumed that was where the class should be created. A different project and package can be specified by simply entering their names in the appropriate fields or clicking the Browse buttons next to each field.
Notice that the EmployeeApp class was stored in a file called EmployeeApp.java within myFirstPackage and that if myFirstPackage is selected it has an expansion icon. Java source code must be stored in a file that has the same name as the class and the file name extension must be java. RAD generates the correctly named file automatically so there is less chance of error.
Please note the following about the RAD generated Java code.
RAD has included comments in the source code. Comments are nonexecutable statements. This means that comments do not perform any computing function. Characters that appear within /* and */ or /** and */ are treated as comments. These comments can span multiple lines. For a single line of comments use //. Any characters that appear after // on a line are considered comments.
Comments are used to document the Java code. Generally, programmers will include their name, the date the class was created, as well as, brief descriptions about what the class does and how the various methods work. Notice that RAD generated two comment sections: a Methods comment section (in blue, right before the method header) and a Method body comment section (in green, after the method header). Each comment section has default text that will be inserted into every class and method that RAD generates. To change the comment default text, click Window, then Preferences.... At the Preferences window, expand the Java item then the Code Style item and select Code Templates. Two expandable items are displayed: Comments and Code. The Methods comment is within Comments and the Method body comment is within Code. Expand the appropriate item and then select either of comment items to display the default text. To change the text, click the Edit… button, modify the text, and then click the OK button. One would think that the default text has been changed—one would be wrong! You must click the Apply button and then the OK button to make the change permanent.
Changing comments that have already been inserted in a class is much easier. Simply select the comment text and type over it.
When a class is defined within a package, a package statement must be included. The package statement must come before the class header and follows the simple syntax of the package keyword followed by at least one space, the package name, and a semicolon (e.g., package myFirstPackage;). The package name actually becomes part of the file identifier. For example, if the file name is Employee and the package is myFirstPackage, the file is identified as myFirstPackage.Employee.
We’ll prove that the package statement is required by “commenting it out.”
Note A light bulb icon and a red circle with a white X appears to the left of the very first line. This is an example of RAD’s syntax checking. When RAD detects an error, the line RAD believes has an error will be flagged with a red circle. If RAD has suggestions on how to fix the error, the light bulb icon will also appear.
Note If you double-click a solution, RAD will make the changes to the code. In this case, the package statement is there but has been commented out so we don’t want RAD to insert the statement. We will simply uncomment the statement using a RAD shortcut.
Notice that the two forward slashes are removed. The package statement is now executable and the error icon on the first line is gone. Statements can also be commented out quickly by selecting the line(s) and pressing Ctrl and forward slash (Ctrl-/). Essentially Ctrl-/ acts as a toggle switch to comment and uncomment statements.
Tutorial: Entering and Editing Java Statements
Now let’s do some editing:
System.out.println("Howdy");
This statement will display the text “Howdy.” Why and how this statement works is beyond your understanding right now. Accept the fact that there is a class called System that contains a wonderful object called out. The out object has a nice method called println that will display anything passed to it. This statement passes the simple text “Howdy” to the println method, and println displays the text.
The code should look like Figure 1-15.
Notice the asterisk, to the left of the text EmployeeApp.java in the tab at the top of the content pane. This means that there are unsaved changes in the code.
Tutorial: Running an Application in RAD
This application simply prints out the text “”Howdy””. Within RAD, the Console view displays text and system messages. The Java perspective does not offer the Console view in any of its panes; however, perspectives can be customized by adding or deleting views.
RAD will display a “run configuration” for EmployeeApp in the “Run Configurations” window. In the future, you can simply select this run configuration to execute EmployeeApp.
The first time a Java application is executed it may take a while because RAD must perform one-time configuration and setup tasks. Remember, the Console view is the default area for printed text to be displayed and, in this case, the text “Howdy” appears. This proves that the main method is executed when a Java class is run as an application.
The last application executed is considered the default application. To rerun EmployeeApp, simply click the Run button () on the Tool bar. (RAD runs the default application when the Run button is clicked.)
String sample = new String("Howdy from EmployeeApp");
This statement will create a String variable called sample and associate the text “Howdy from EmployeeApp” to it. We will now change the println statement to print the text associated with the variable sample.
After an application has been run (besides becoming the default application to run), the application is also added to a list of “applications to run.” Instead of re-specifying an application to run, it can be selected from this list.
EmployeeApp should be displayed at the top of the drop down menu. The application at the top is the default application to run. However, any application can be selected and run from the list by simply clicking it.
Many engineering disciplines use destructive testing to understand how a product or design will function. For instance, automobile manufacturers crash cars in walls to improve design and safety features. Programmers can do the same with Java code. Removing pieces of code will help you understand what function the code performs. In addition, producing errors highlights common programming mistakes and their associated error messages. Hopefully, by producing the errors now, you will recognize them sooner and fix them faster when you make them later.
Exception in thread "main" java.lang.NoSuchMethodError: myFirstPackage/
EmployeeApp.main([Ljava/lang/String;)V
The key portions of this message are the text “NoSuchMethodError” and then the identification of the main method—“myFirstPackage/EmployeeApp.main.” Notice that the error message doesn’t tell you exactly what the problem is (i.e., the Main method doesn’t begin with a lowercase m), only that there is no main method. Really, what the message means is that there is no main method coded exactly as it is needs to be. The main method header has to be coded exactly as specified earlier. Any deviation will result in the above error. When you get this error, you will have to figure out which picky Java syntax requirement was violated in the main method and correct it.
Now, let’s break something else!
Notice that there is now a red squiggly line under the class and main ’method’s closing braces. Like a word processor, this is another way RAD indicates that there is an error. Again, we’ll ignore ’RAD’s warnings and run the application.
RAD tries to warn us about errors by displaying the Errors in Workspace window. (Please also notice that RAD calls “running an application” a “launch.” Launches will come up later in the book.)
The following error message will be displayed in the Console:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error, insert "}" to complete ClassBody
at myFirstPackage.EmployeeApp.main(EmployeeApp.java:16)
The first line of the error message simply means there was a fundamental Java language syntax error (i.e., compilation problem). The second line tries to pinpoint the error and offer a solution (i.e., there is a syntax error because the class body was never ended with a closing brace.) The red squiggly line under the first closing brace indicates that RAD thinks that token is incorrect. If you move the cursor over that error icon or the red squiggly line, RAD will display a message saying that the token } should be deleted. However, the real problem is that the main method is outside of the class body. Obviously, RAD is not too good at identifying this particular error. The third line of text explains where the error was found. Notice it contains the package name, class name, and method name where the error was found, as well as, a hyperlink to the suspected line with the error.
The Java statement/line that RAD believes caused the error is highlighted. Every line in the source code is assigned a sequential number, but initially the line numbers are not displayed. However, you can change this (and other appearance aspects of any view).
The Text Editors pane is displayed on the right of the window. The checkboxes and text fields provide control over various options. Notice that the “Show line numbers” checkbox is not selected.
The line numbers are now displayed to the left of each line (see Figure 1-19).
RAD placed a gray box around the matching brace on line 13. When you click to the right of a paired token (e.g., a bracket, brace or parenthesis), RAD will identify the matching token by enclosing it in a gray rectangle. Being able to match paired tokens is extremely useful as an application’s source code grows in size. The “Highlight matching brackets” option in the Java/Editor category within Preferences controls this feature.
RAD will display a “hover” message saying a semicolon is missing. If you click on or in the space before the red squiggly line, the error message will be displayed in the RAD window bottom border on the left.
Notice that RAD does a good job of identifying the missing semicolon problem.
A red squiggly line is placed under the text sample in line 9 and if you display the error message, you will see that RAD suggests entering a semicolon. RAD does not do as good a job identifying this error. While technically it is true that placing a semicolon after sample would make a valid statement, this is not the real source of the problem. Rather, this shows that RAD often identifies/highlights the token before or after the real problem and error messages will often suggest incorrect solutions.
Be careful. Because of the widespread use of word processing software, most people assume that whatever text is “red squiggled” is the problem. For instance, a novice programmer might think that the text sample is the problem and try changing it or delete it entirely (since it appears to be the problem).
Avoid compounding a mistake by thoroughly reading the error message and looking for the problem in the statement(s) or token(s) preceding or following the “red squiggled” text.
Notice that line 10 is flagged as an error. There are two lessons to be learned. First, Java is case sensitive. Line 10 refers to sample but there is no variable sample, however, there is a variable Sample. For beginner programmers, incorrect capitalization is a source of countless errors. Second, sometimes RAD’s first solution is correct. Click on the light bulb icon to display solutions. Notice that RAD suggests changing the variable name to Sample. This is a viable solution to remove the error indicators.
RAD flags the statements on both lines 10 and 12 as errors. If you display the solutions, RAD will once again suggest changing the variables from sample to Sample. In this case, this is not the best solution. Instead, you should change the variable definition on line 9 not the two statements on lines 10 and 12.
Notice that RAD removes both errors icons. This is an example of a cascading error. A cascading erroris a single error that results in many error messages being generated. This is why you shouldn’t panic if many lines of source code are flagged as incorrect. Often solving one error will clean up many error messages. This is also why you should solve errors within the source code from top to bottom.
Here’s what we now have:
Review Questions
String coolStuff
public displayCoolStuff() {}
String veryCoolStuff("ice");
string veryCoolStuff;
String extremelyCoolStuff = new String(liquid nitrogen);
Review Exercise
Overview
In the exercises, you will create a Java-based application for a company called TNT Salvage. TNT receives unwanted consumables (food, kitchen and laundry products, toiletries, etc.) from large retail organizations, repackages them, and sells them to smaller retail outlets at a significant discount. Throughout the chapter exercises, you will create an application that accepts information about shipments from the large retailers.
Detail
In this first exercise, you will create a Java class called ShipmentApp that creates and uses five variables to store shipment information and displays that information.
At this point, the code should consist of:
And assign the following text:
Check that the Exercise Was Done Correctly
Finally, let’s check that everything was done correctly:
3.144.119.170