CHAPTER 1

image

Java Basics

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:

  • Basic Java keywords and syntax
  • Classes, methods, and variables
  • Constructors and comments
  • Perspectives and views

Using WebSphere, you will be able to:

  • Create projects, packages, and classes
  • Use and customize perspectives and views
  • Write a basic Java application
  • Run a Java application

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.

Table 1-1.

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.

Java Statements

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.

Objects and Instantiation

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.

Constructors

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:

  1. Assuming that WebSphere has already been installed, from the Windows desktop, click the Start button (in the lower left of the screen), then All Programs.
  2. Within the program list find and click on the entry for IBM Software Delivery Platform, IBM Rational Application Developer, then Rational Application Developer (see Figure 1-1).

    image Note   If Rational Application Developer is running for the first time, this may take a little while.

  3. You may be prompted for a location on the PC where WebSphere should store the work (see Figure 1-2). If so, specify a location (e.g., a flash drive) and click the OK button.
  4. Rational Application Developer (RAD) will be started and if this is the first time RAD has been run, the Welcome pane will be displayed (see Figure 1-3). Close the Welcome pane by clicking the X in the pane tab (indicated by the arrow in Figure 1-3).

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.

Tutorial: Perspectives

Let’s examine perspectives:

  1. Close the perspective by right-clicking the JEE icon and choosing “Close” from the shortcut menu. The result will be Figure 1-5.
  2. Click the “Open a Perspective” icon (indicated by the arrow in Figure 1-5). A shortcut menu will be displayed with an option for “”Other.”” A list of available perspectives can be viewed by choosing the “Other” option.
  3. Click on the “”Other”” option. The “”Open Perspective”” window will be displayed (see Figure 1-6).
  4. For now, simply select “Java” from the “Open Perspective” window and click the OK button. The Java perspective will be displayed (see Figure 1-7)

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.)

  1. To create a project, click File (on the Menu bar), New, then Java Project (see Figure 1-8).
  2. The “New Java Project” window will be displayed (see Figure 1-9). At the “New Java Project” window, specify MyFirstProject and click the Finish button.

    image Note   MyFirstProject now appears in the Package Explorer view.

  3. Selecting an item in the project navigation tree results in the item name being enclosed in a rectangle with a pale blue background. Because MyFirstProject was just created, it is automatically selected by RAD. (An item can also be selected by clicking its name or icon.) Any subsequent actions you specify will be performed against the selected item. On the Menu bar, click Edit, then Delete.
  4. At the “Delete Resources” window, click the “Delete project contents on disk” checkbox, and then the Yes button. The Java Perspective is redisplayed. Notice that MyFirstProject has been removed from the Package Explorer view. The delete was performed against MyFirstProject because MyFirst-Project was the selected item.
  5. Perform steps 1 and 2 again to recreate MyFirstProject. The “Package Explorer” pane should look like Figure 1-10.

Tutorial: Creating a Package

Now let’s create a package:

  • 1.  On the Menu bar, click File, New, then Package to display the “New Java Package” window.

image 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.

  • 2.  At the “New Java Package” window, specify MyFirstPackage in the Name field. Notice the message at the top of the window. Package names usually begin with a lowercase letter to make it easier to distinguish them from project names. RAD tries to warn programmers about errors and suggest good programming practices throughout the development process. This is one of the many advantages provided by a development tool such as RAD.
  • 3.  Change the name to myFirstPackage. Notice the message goes away (see Figure 1-11).
  • 4.  Click the Finish button. Notice that myFirstPackage is selected in the “Navigation Tree” within the “Package Explorer” view and appears as a branch or subitem within src (see Figure 1-12).

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 image. 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 (image) or are not displayed (image). 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.

  • 5.  Click on the MyFirstProject expansion icon. The contents are hidden and the expansion icon is changed.
  • 6.  Click on the MyFirstProject expansion icon again. The contents are displayed and the expansion icon is changed back.
  • 7.  Double-click the project icon for MyFirstProject to hide the contents and then double-click the project name (MyFirstProject) to redisplay the contents.

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:

  • 1.  If myFirstPackage is not selected, select it by clicking its name.
  • 2.  On the menu bar, click File, New, and then Class to display the “New Java Class” window (see Figure 1-13).

image 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.

  • 3.  Specify EmployeeApp in the Name field. Notice that the access modifier public has already been selected. Other modifiers can be chosen by clicking the other modifier option’s radio button or check boxes.
  • 4.  Make sure the main method option is the only method stub option selected. Since EmployeeApp will be run as an application, it needs a main method. By checking the “main method” option, RAD will automatically generate an empty main method (e.g., a stub) relieving you from having to code it.
  • 5.  Click the Finish button to create the class and redisplay the Java perspective (see Figure 1-14).

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.”

  • 6.  Move the cursor before the package keyword and insert two forward slashes (//). Notice that the text changes to green. Green text indicates that Java considers the text a comment and this text will not perform any function.

image 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.

  • 7.  Move the mouse cursor over the red circle to display the error message text. The text “The declared package” does not match the expected package “myFirstPackage” will be displayed.
  • 8.  Click the light bulb icon to display the possible solutions. A box with a list of solutions will be displayed. The first solution option will be selected and a yellow box with more details regarding the selected solution will be displayed. In this case, the Add package declaration ‘myFirstPackage;’ solution should be selected and the exact statement that will be inserted and where within the code it will be placed should appear to the right.

image 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.

  • 9.  Click anywhere on the commented out package statement line to select it.
  • 10.  Press and hold the Ctrl key, then press the forward slash (/) key. (We will use Ctrl-/ to indicate this action).

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.

  • 11.  Select all the lines of the class.
  • 12.  Press Ctrl-/ to change them all to comments.
  • 13.  Press Ctrl-/ to uncomment all the statements.
  • 14.  On the menu bar, click File and then Save.

Tutorial: Entering and Editing Java Statements

Now let’s do some editing:

  • 1.  Click to the right of the opening brace ({) in the main method header. The insertion cursor (a blinking vertical line) should appear at the far right of the line.
  • 2.  Press the Enter key to insert a blank line.
  • 3.  Enter the following statement on the blank line:
    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.

  • 4.  Save the code by clicking File and then Save. (You can also click the floppy-disk icon on the tool bar.) Notice that the asterisk is no longer there.

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.

  • 1.  Add the Console view by clicking Window, Show View, and then Console. The Console view will replace the Problem view in the Task pane at the bottom of the Java perspective window. Did you notice all the views that were listed when you clicked Show View? We will explore other views in later chapters and demonstrate many of RAD’s very useful tools offered in these views.
  • 2.  On the Menu bar, click Run, and then Run Configurations.... The Run Configurations window will be displayed.
  • 3.  Select Java Application and then click the New button (see Figure 1-16).

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.

  • 4.  On the “Run Configurations” window, click the Run button.

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 (image) on the Tool bar. (RAD runs the default application when the Run button is clicked.)

  • 5.  In the main method, add the following statement before the println statement:
    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.

  • 6.  In the println statement, replace “Howdy” with sample. (Make sure the double quotes around the text Howdy are removed also.) The source code should look like Figure 1-17.
  • 7.  Save EmployeeApp by clicking on the floppy-disk icon.
  • 8.  Click the Run button. The text “Howdy from EmployeeApp” will be displayed in the Console view.

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.

  • 9.  Click the black arrowhead to the right of the Run button to display the “applications to run” 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.

Tutorial: Breaking the Code

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.

  • 1.  In EmployeeApp, change the name of the main method to Main (capital M).
  • 2.  Click the Run drop down button and select the EmployeeApp configuration. Notice that RAD prompts you to save the EmployeeApp source code.
  • 3.  On the “Save and Launch” window, click the OK button. RAD will display a Java Virtual Machine Launcher window with a Fatal exception message and in the Console view one of the most common Java application error messages will be displayed:
    Exception in thread "main" java.lang.NoSuchMethodError: myFirstPackage/
    EmployeeApp.main([Ljava/lang/String;)V

The key portions of this message are the text “NoSuchMethodErrorand 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.

  • 4.  Close the Java Virtual Machine Launcher window by clicking the OK button.
  • 5.  Put the lower case m back in the header by clicking Edit then Undo in the menu bar. Notice that RAD will undo the change even though the source code was saved.
  • 6.  Save the source code, and run the program to verify that code was fixed correctly.

Now, let’s break something else!

  • 7.  Select the entire main method.
  • 8.  Cut and paste the method after the EmployeeApp class’ ending brace.

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.

  • 9.  Run the application by selecting the EmployeeApp run configuration.
  • 10.  On the Save and Launch window, click the OK button (to save the changes).

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.)

  • 11.  Click the Proceed button on the Errors in Workspace window to run the application.

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.

  • 12.  Move the mouse pointer over the third line of the message and click the hyperlink.

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).

  • 13.  Cut and paste the main method back within the EmployeeApp class body. Notice that the error icons to the left of the source code are removed but there is still an error icon in the tab at the top of the Editor pane.
  • 14.  Save the source code. The error icon in the tab is removed.
  • 15.  Click Window, then Preferences to display the Preferences window.
  • 16.  In the list on the left, expand the General item, the Editors item and then select Text Editors (see Figure 1-18)

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.

  • 17.  Click the “Show line numbers” checkbox to select it.
  • 18.  Click the Apply button and then the OK button.

    The line numbers are now displayed to the left of each line (see Figure 1-19).

  • 19.  Click to the right of the open brace on line 8.

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.

  • 20.  On line 10 in EmployeeApp, delete the semicolon at the end of the statement. RAD puts a red squiggly line under the closing parenthesis. Remember, a red squiggly line means RAD thinks there is a problem.
  • 21.  Move your mouse pointer over the red squiggly line.

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.

  • 22.  Save the source code. RAD places an error icon to the left of the line.
  • 23.  Type the semicolon at the end of line 10. The error icon to the left of the line becomes inactive but is still visible. RAD is reminding you that the fix to the code is not saved.
  • 24.  Save the code to remove all error messages and error icons.
  • 25.  Go to line 9 and remove the equal sign.

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.

  • 26.  Replace the deleted equal sign on line 9 and run the application to verify it is correct.
  • 27.  On line 9, change the “s” in sample to a capital “S.” This changes the variable name to “Sample.”

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.

  • 28.  Copy the println statement from line 10 and paste it on line 12.

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.

  • 29.  On line 9, change Sample to sample.

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.

  • 30.  Delete the println statement from line 12 and save the source code for EmployeeApp. The code should look like Figure 1-19.

Results of the Tutorial

Here’s what we now have:

  1. A new project called MyFirstProject.
  2. In MyFirstProject/src, a new package called myFirstPackage.
  3. In myFirstPackage, one file called EmployeeApp.java.
  4. The source code in EmployeeApp should look like Figure 1-19.

Review Questions

  1. What is the minimum Java source code needed to define a class?
  2. What is the syntax to define a String variable?
  3. Where must the package statement appear in the class?
  4. In a method header, where is the keyword void specified?
  5. How can you tell if there are unsaved changes in a source code file?
  6. When an object is instantiated, which is done first: the constructor is executed or class variables are created?
  7. Determine which of the following statements are valid and which are invalid:
    String coolStuff
    public displayCoolStuff() {}
    String veryCoolStuff("ice");
    string veryCoolStuff;
    String extremelyCoolStuff = new String(liquid nitrogen);
  8. What is a token?

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.

  • 1.  Start RAD and create a new Java project called ReviewEx.
  • 2.  In ReviewEx, create a package called c1.
  • 3.  In c1, create a public class called ShipmentApp with a main method.

At this point, the code should consist of:

  • a package statement
  • a class header
  • the opening and closing braces for the class body
  • a main method header
  • the opening and closing braces for the main method body
  • 4.  Save the ShipmentApp source code and verify that there are no errors.
  • 5.  Define five String variables in the main method called:
  • shipmentNum
  • supplierName
  • rcvDate
  • rcvTime
  • employeeNum

And assign the following text:

  • 99
  • Costco
  • 12/15/2011
  • 10:25 AM
  • 33
  • 6.  Save the ShipmentApp source code and verify that there are no errors.
  • 7.  Insert five println statements to display each of the String variables.
  • 8.  Save the ShipmentApp source code and verify that there are no errors.

Check that the Exercise Was Done Correctly

Finally, let’s check that everything was done correctly:

  • 1.  Verify that ShipmentApp.java is in c1.
  • 2.  Run ShipmentApp and verify that the Console displays the following:
  • 99
  • Costco
  • 12/15/2011
  • 10:25 AM
  • 33
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.119.170