Lab 1: Introduction to Java

Lab Objectives

  • Understand the structure of a simple Java program
  • Understand the distinction between compiling and interpreting Java programs
  • Create and execute simple Java programs using Eclipse
  • Learn how to find and correct syntax errors in your code.

Getting Started

In a typical lab, you will be typing shell commands into an xterm (terminal) window, using Firefox to access files that have been put on the Web for you to use in lab, and typing in programs using Eclipse. Ocassionally, you will also need to use the text editor to prepare some responses to questions. So, to get started

Your first CS120 program

Most programs start out as text files that contain a series of instructions written in a computer language like Java or C++. The following instructions lead you through the process of writing and modifying a very simple Java program.

Traditionally the first program a computer scientist writes in a new language is a simple one that prints out a "Hello, World" message.

  1. First you need to open the text editor using the icon that you created on your toolbar last week.

  2. Type in the following program exactly as you see it.
    
    package lab1;
    
    /**
     * Prints a "Hello World" message.
     * 
     * @author john doe
     */
    public class Hello
    {
       /**
        * Prints the greeting
        * 
        * @param args   command line arguments
        */
       public static void main(String[] args)
       {
          System.out.println ("Hello, World!");
       }
    }
    
    

  3. Double check to make sure that your program looks identical to the one on this sheet.
    (The one exception is that you should replace "john doe" with your name)

  4. Save your program in a file called "Hello.java" in your lab1 subdirectory (remember, capital 'H').

  5. You should note that your program is now color coded. The colors correspond to some of the major structural components of this program that we discussed in class. Specifically you should be able to identify:

  6. You will probably notice a few differences from the way that your textbook presents Java source code and what we have written here. Notably:

  7. You are now ready to compile the program. Activate your xterm window then move the to the "Labs" directory. Type the command

    javac lab1/Hello.java


    If all went well (no error messages) a file named Hello.class was created by the compiler. This file contains the bytecode version of the program. If you recieved an error make sure that your present working directory is "Labs" (use the pwd command). If you had an error, go back to text editor window, find and correct the error. Save the program again and repeat the command to compile (in the xterm window).

    *** Shell HINT: To repeat a shell command you have already used press the up arrow key until the command you want to repeat appears, then press ENTER to execute the command.

  8. Use the appropriate command(s) to see a list of the files in your lab1 directory (there are a couple of different ways you can do this). You should have at least two files -- Hello.java and Hello.class. Hello.java is your source code; Hello.class is the file containing Java bytecode created by the compiler.

  9. Now run (execute) the program by typing (in the xterm window) the command

    java lab1/Hello

    This sends the Java bytecode through the Java Interpreter. You should see the hello message followed by the command line prompt on the next line.

Setting up Eclipse

You have just written your first Java program using a Text Editor. It got the job done, but this process can be made much easier using an Integrated Development Environment or IDE. IDEs facilitate the programming process by helping programmers adhere to good programming practices, quickly identify mistakes, and helping to organize large projects. Many times the IDE even helps to generate generic code frameworks and allow programmers to simply fill in the details.

For this class we are going to use the Eclipse IDE to help us create our Java programs. You can start Eclipse by clicking on the icon that you added to the Gnome panel last week. Since this is the first time using Eclipse, there are a couple of things we need to do to get started.

  1. The first thing that you will see is a dialog asking you to select a workspace. This is the general location where Eclipse will store all of your programs. You want to use your cs120 directory, so you should enter

    /home/students/jdoe/cs120

    substituting your username for jdoe. For this class we will always use this directory as our workspace, so you can also check the option to make this the default directory.

  2. You will probably see an Eclipse welcome screen. There are several useful icons on this screen, including a tutorial for how to use Eclipse. Right now, we are interested in the Workbench - the icon to the far right side of your screen . Click the icon to enter the workbench (also called workspace).

  3. We also would like to set some preferences to make Eclipse function consistently for everyone in the class. These preferences are stored in the file that you copied to your home directory last week (RCEclipsePrefs.epf) To load them into Eclipse:

    1. Use File menu and select the Import option. A new "Import" dialog box will appear.

    2. Open the General option, highlight Preferences and then press Next

    3. Browse for the file RCEClipsePrefs.epf (Remember, it was stored in your home directory) and then click Finish.

    Later in the semester, you may wish to set up Eclipse to run on your personal computer. You will use this same preferences file to ensure that the same standards and conventions are used as the lab computers.
Projects, Packages & Classes

One of the advantages of Eclipse is that it helps us to organize the code that we produce. Specifically, Eclipse lets us create projects - large groups of code that contain packages - smaller groups of code, usually centered around a particular theme, which in turn hold classes - actual code for specific instructions or programs. This kind of stucture may sound familiar; in fact, projects correspond directly to directories, packages are subdirectories and classes are files.

  1. In this semester, you will have two major projects: Labs and Assignments. Remember that you already created these directories in your account earlier, our next step is to designate these directories as Eclipse projects. To accomplish this:

    1. Under the File menu, expand the new option and select project

    2. When the New Project Wizard dialog appears, press Next (if Next isn't an active option first click Java Project).

    3. Enter "Labs" in the Project Name field. Note: you should see a message at the bottom of the window indicating that the "external location exists". This is simply reminding you that you already have this directory in your account. If you do not see this message, please contact your instructor or lab assistant.

    4. Press Finish. You should see Labs added to the left-most panel of the Eclipse window. This panel is known as your "Workspace".

    Repeat this process to create an Assignments project as well. Your workspace should now contain two projects: Labs and Assignments. This mirrors the directory structure in your cs120 directory.

  2. Projects group together packages. Double click on the Labs project to see its packages; it should already contain two. Your workspace should look something like this:

    If you don't see these packages, you can Refresh the workspace by pressing the F5 key. (You may also see JRE System Library listed.) If they still don't appear, call over your instructor or lab assistant.

    Where did these packages come from?

  3. Each week you will designate a new package to hold your work for the week's lab activities. Packages group together classes. Double click on the lab1 package to see its classes.

    You should find that lab1 contains the "Hello" Java file that you typed in previously. Double click on the Java file containing the Hello class. You should see the source code load into the center panel of the Eclipse window. There are some notable points about the code:

    Eclipse is aware that you are trying to write Java Code. Automatically formatting and color coding your work are some of the ways that Eclipse tries to make life easier for you as a Java programmer.

  4. Now we are ready to try executing your program. To do this:
    1. Under the Run menu, expand the Run As option and select Java Application.

    2. You may see a Save and Launch dialog asking you to to save your program before it is run. Since you almost always want to save your files, it is reasonable to check the Always save resources... box if you wish. Press Ok to continue.

    3. If the bottom of the Eclipse window does not contain a console tab, select Window>Show View>Console from the menu bar. In the Console, you will see the phrase, "Hello World!".

Creating a Java Program in Eclipse

In the previous activity, you were working with a program that already existed. Now we would like to create a new program from scratch within Eclipse. This program will be very similar to "Hello"; the only difference is that it will display a different message.

  1. With the lab1 package highlighted in the Workspace, open the File menu, expand the new option and select class.

  2. In the dialog that appears, verify that the Source Folder is "Labs" and that the Package is "lab1".

  3. In the Name field, enter "Cool".


  4. Under the option Which method stubs..., you will need to add a check next to "public static void main (String[] args)"

  5. Click on Finish

In the center panel you should see the following text appear

package lab1;

/**
 *
 * @author jdoe
 */
public class Cool
{
   /**
    * @param args
    */
   public static void main(String[] args)
   {
      // TODO Auto-generated method stub
   }
}

You will see this same structure over and over again in this class. While Eclipse was kind enough to generate it for us, it can only create parts of the code that are generic. This program still does not do anything; notice that there are no commands in the main method. Let's fill in the details for this framework by adding instructions to accomplish our task.

  1. In the begining of the first comment block, add some text describing the overall purpose this program (This program prints a "Cool" Message). You will notice that when you add text to a comment block in Eclipse, each line is automatically preceded by an "*".

  2. Add text to beginning of the comment block preceding the main method; indicating what it will do. In this example, like Hello, your comments will probably be redundant. Since there is only one method in the class, the class and the method will do the same thing - print a cool message. However, it won't be long before your class contains multiple methods. It is a good habit (and makes professors happy) to provide details of every class and method definition via comments.

  3. In the main method, replace the "TODO" comment with the following line of code:
     System.out.println("Java is Cool!");

  4. Execute (run) this program, and verify that your code functions as intended.

Syntax Errors

You may have experienced what happens if your code is incorrect. Mistyping a command, forgetting a ';' or capitalization mismatches are all examples of Compile-time Errors. If you are using the javac command in an xterm, the compiler will generate a collection of error messages and does not create the bytecode file. In Eclipse, source code is automatically compiled so these kind of errors can be detected immediately. Syntax errors are flagged with a red 'x' in the margins of the code. Moving the mouse over the 'x' give a more elaborate description of cause of the problem. These descriptions can be quite useful once you learn to interpret them. In the following you will be introduced to a few typical errors into the Cool program and examine the error messages.

  1. Class name is not the same as the file name In Java, when you define a new class, it must be saved in a file that shares the name of the class. Delete the l (el) from the name of the class (so the first non-comment line is public class Coo). What was the error message (put your mouse over the red x)?

     

     

  2. Correct the mistake above, then delete the l (el) from the Cool in the comment block (inside the quotation marks). Does this generate an error message? why not? Run the program to see what happens.

     

     

  3. Leaving off a quotation mark in a string literal Correct the mistake above, then delete the ending quotation mark enclosing the string Java is Cool!

     

     

  4. Put the ending quotation mark back, then take out the beginning one. Examine the error message -- notice that it indicates there are "multiple markers". The compiler is trying to make sense of what you have typed, but it is rather confused. After we study variables, you will have a better understanding of what the compiler thinks. If you scan the list of errors, you will notice a message about double quotes. When you get lots of errors, it is often useful to concentrate on the ones that appear first and work your way down the list. Fix the last error (put the quotation mark back).

     

     

  5. Lastly, try deleting the "n" from the end of println. Make a note of the error message. The compiler is effectively telling you that it does not understand the command that has been issue; printl is not a recognized command.

     

     

  6. Correct the last error before proceeding (otherwise you will get an "errors exist in project" message when you try to run the next programs you add to the package).

Modifying programs

At any time you can go back to previously written code to make changes. To start this section, re-activate the "Hello" program. You can accomplish this either by selecting the appropriate tab from the center panel or by selecting the Hello class from the Workspace browser.

  1. Add appropriate statements to the Hello program so it will print the following:
        *******************
           Hello, World!
        *******************
    
    Run your new version (make sure it prints the correct pattern).

  2. println versus print. Section 2.1 of the text (beginning on page 34) discusses the difference between println and print. See this difference by changing all println's to print in the program. Run the revised program.

     

     

  3. Printing a blank line. A blank line is printed by invoking the println method with no arguments -- that is, with the statement
           System.out.println();
    
    Change each print back to println then insert statements to print 4 blank lines: one before the first row of stars, one between the first row of stars and the message, one between the message and the second row of stars, and finally one after the last row of stars. Run your program. Does the last blank line make any difference in the way the output looks?

     

  4. Making a new program from the old. Often when programming you want to take a program you already have as a basis for a revised one or you want to try changes to the program without losing the old one. To do that you need to make a copy of the original program to work with so you have both the old and new. Your job now is to make a new program by customizing the Hello program.

    1. With the Hello.java active in the center panel, Use the File -> Save As option to save a new copy of the original Hello.java. Name this new file MyHello.java.
    2. You should notice that MyHello.java will be automatically added to your lab1 project in the Workspace navigator. You should also notice that this file contains syntax errors. But how can that be? Hello.java didn't have any syntax errors! The source code for MyHello.java should be open in the center editing window (if not open it). Find out what the error is and fix it.
    3. Make the appropriate changes so that the program prints the following (put your name instead of Bozo -- make the border align nicely):
          *****************************
      
             Bozo says Hello, World!
      
          *****************************
      
    4. Escape sequences The "Hello, World!" part of the message above should really be enclosed in quotation marks but we can't just put quotation marks inside the println statement because the Java compiler would interpret them to mean the end (or beginning) of a string. To print special characters such as these in Java you use an escape sequence (discussed on pages 39 - 40). The backslash character indicates the beginning of an escape sequence. The table on page 40 shows the meaning of the different Java escape sequences. Add the \" escape sequence to your program so the message Hello, World! is enclosed in quotes when printed out.

    5. After your program is correct print out a copy of it (you will turn this in at the end of lab) using the following command:
         enscript -2rG MyHello.java
      

Names and Places Program

Our next goal is to develop a program that will print out a list of student names together with other information for each. The tab character (see escape sequences) is helpful in getting the list to line up nicely. A program with only two names is in the file Names.java.

  1. Do the following to copy this program to your lab1 directory:
  2. Open the file in Eclipse (you will probably need to refresh your workspace using F5) and study it for a few minutes particularly noting the use of the escape sequences for the tab character.

  3. Run the Names program to see what it prints.

  4. Now add code to the program so that your name and hometown and the name and hometown of at least two classmates sitting near you in lab also are printed. (So, the program should print at least 5 names.) Also add your name in the documentation at the top of the program. Run the program. Make sure the columns line up.

  5. Modify the program to add a third column with the intended major of each person (assume Sally's major is Computer Science and Alexander's major is Math). Be sure to add a label at the top of the third column and be sure everything is lined up (use tab characters!).

  6. Print a copy of your final Names program. (Remember the up arrow - use it to retrieve the last time you printed and just change the file name in that command.)

 

Two Meanings of +

When using a string literal (a sequence of characters enclosed in double quotation marks) in Java the complete string must fit on one line. The following is NOT legal (it would result in a compile-time error).

    System.out.println ("It is NOT okay to go to the next line
                           in a LONG string!!!");
The solution is to break the long string up into two shorter strings that are joined using the concatenation operator (which is the + symbol). This is discussed in Section 2.1 (pages 36 - 39) in the book. So the following would be legal
    System.out.println ("It is OKAY to break a long string into " +
                           "parts and join them with a + symbol.");
So, when working with strings the + symbol means to concatenate the strings (join them). BUT, when working with numbers the + means what it has always meant -- add! To see the behavior of + in different settings do the following:
  1. The file PlusTest.java contains the following program:
    
    package lab1;
    
    /**
     * Purpose: Demonstrate the different behaviors of the + operator
     * 
     * @author ingram
     */
    public class PlusTest
    {
       /**
        * prints some expressions using the + operator
        * 
        * @param args   command line arguments
        */
       public static void main(String[] args)
       {
          System.out.println("This is a long string that is the "
             + "concatenation of two shorter strings.");
    
          System.out.println (7 + 8);
    
          System.out.println ("7" + "8");
    
          System.out.println ("7" + 8);
    
          System.out.println("8 plus 5 is " + 8 + 5);
    
          System.out.println("8 plus 5 is " + (8 + 5));
    
          System.out.println(8 + 5 + " equals 8 plus 5.");
    
          System.out.println("The first computer was invented about" 
             + 60 + "years ago.");
             
       }
    
    }
    
    
    
  2. Study the above program a minute, then in Firefox open it (click on the link above) and save it to your lab1 directory.

  3. In Eclipse refresh your workspace (f5) and double click the PlustTest.java file in left panel. Run the program, study the, output and observe the following:

Your last task for today!!

Write a complete Java program that prints out the following sentence.

   Ten apples plus 13 bananas is 23 pieces of fruit.

Your program must use only one statement that invokes the println method. It must use the + operator both to do arithmetic (add 10 and 13) and string concatenation. Make sure that your program includes comments that document the heading information (Author and Purpose) and the key steps of the program. Print out a copy of your completed (and working!) program.

TURN IN the following: