Lab 1 In-Class: Introduction to Java

Getting Started

Generally in lab you will be typing shell commands into an xterm window, typing your programs into emacs, and using Netscape to access files that have been put on the Web for you to use in lab (the lab instructions such as this handout are also accessible as Web pages with links to files you will use during lab). So, to get started

The following instructions lead you through writing and modifying several Java programs. The goals are for you to learn more about emacs, Linux, and Java programs that do nothing but print.

  1. Hello, World Traditionally the first program a computer scientist writes in a new language is a simple one that prints out a "Hello, World" message so that's what we will do first. Do the following:
    1. First you need to open a new file in emacs: Activate your emacs window then
      • Choose Open File... under the Files menu (OR use the keystrokes C-x C-f -- Hold down the Control ctrl then hit the x-key followed by the f-key)
      • In the Find File: location at the bottom of the window fill out the full pathname of the file (which should be ~/cpsc120/labs/lab1/ if you have set up your directory correctly -- remember the ~ stands for your home directory and is probably already displayed for you by emacs so don't type it again!)
      • Press Enter after typing in the file name and you should be taken up to the blank buffer. You type your program into this buffer.
    2. Type in the following program. You are working in a text editor now rather than a word processor so you need to press ENTER when you are at the end of a line (there is limited automatic wrap of lines).
      // ********************************************
      // FILE:
      // Author: Put your name here!
      // Purpose: Print a Hello, World message.
      // ********************************************
      public class Hello
          // -----------------------------------
          // main method -- prints the greeting
          // -----------------------------------
          public static void main (String[] args)
      	System.out.println ("Hello, World!");
    3. Save your program by typing C-x C-s (Hold down the control ctrl then hit the x-key then the s-key.)
    4. To compile the program activate your xterm window then type the command


      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 had an error, go back to the emacs window, find and correct the error. Save the program again and repeat the command to compile.

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

    5. Use the ls command to see a list of the files in your lab1 directory. You should have at least two files -- and Hello.class. is your source code; Hello.class is the file containing Java bytecode created by the compiler.
    6. Now run (execute) the program by typing (in the xterm window) the command

      java Hello

      You should see the hello message followed by the command line prompt on the next line.

  2. Learning from your mistakes -- Compile-time Errors: When you make syntax errors in your program the compiler gives error messages and does not create the bytecode file. It saves time and frustration to learn what some of these messages are and what they mean. Unfortunately at this stage in the game many of the messages will not be meaningful except to let you know where the first error occurred. Your only choice is to carefully study your program to find the error. In the following you will introduce a few typical errors into the Hello program and examine the error messages.

    1. Error #1: Class name is not the same as the file name Delete one l (el) from the name of the class (so the first non-comment line is public class Helo), save the program, and recompile it. (NOTE: You change the program and save it in emacs then issue the compile command in the xterm window.) What was the error message?



    2. Correct the mistake above, then delete one l from the Hello in the message to be printed (inside the quotation marks). Save the program and recompile it. There is no error message -- why not? What happens when you run the program?

    3. Leaving off a quotation mark in a string literal Correct the mistake above, then delete the ending quotation mark enclosing the string Hello, World!, save the program, and recompile it. You should see the following error message:
    unclosed string literal
              System.out.println ("Hello, World!);
                                  ^ ')' expected
              System.out.println ("Hello, World!);
      2 errors
      Note the error message tells you where the error is (line 15) and what it is (unclosed string literal -- string literals are enclosed in quotation marks so this tells you the closing one is missing). Also note that the compiler doesn't tell you where the mark should go and even though there is only one mistake the compiler says there are two. This is because the compiler is assuming every character it is reading after the first quotation mark (including the ending parenthesis and the semicolon) is part of your string but then it gets to the end of the line without finding the end quotation mark (so that is one error). Now it looks for the parenthesis to enclose the argument to the println method and can't find it (it already read past it) so that is the second error.

      *** emacs HINT -- Line Numbers: In emacs there are two ways to find a specific line when you know its number. Observe that in the status bar (the one near the bottom of the window that contains the buffer name) there is among other things an L followed by a number. That number is the current line number (where the cursor currently is) -- so L23 means the cursor is currently on line 23. In short programs you can just move the cursor up or down until you find the correct line. In longer programs you can use a keystroke command: Hit the Esc key (this is called the META key in emacs), release it, then hit the x-key. In the minibuffer at the bottom of the emacs window you will see M-x with your cursor sitting beside it waiting for you to type a command. The command you need to type is goto-line (type the words) then press ENTER then type in the line number you want and press ENTER.

      *** Try the META-x method getting to a specific line.

    4. Put the ending quotation mark back, then take out the beginning one. Save and recompile. How many errors this time? Lots even though there is really only one error. When you get lots of errors always concentrate on finding the first one listed!! Often fixing that will fix the rest. After we study variables (before next week's lab) the error messages that came up this time will make more sense.
    5. Fix the last error (put the quotation mark back).

  3. Modifying the Hello program
    1. Add appropriate statements to the Hello program so it will print the following:
             Hello, World!
      Save, compile, and run your new version (make sure it prints the correct pattern).

    2. println versus print Section 2.1 of the text (beginning on page 64) discusses the difference between println and print. See this difference by changing all println's to print in the program. Save, compile, and run the revised program. Why does the shell prompt appear where it does?

    3. Printing a blank line A blank line is printed by invoking the println method with no arguments -- that is, with the statement
      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. Save, compile and 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. You job now is to make a new program by customizing the Hello program.

    1. First copy to a new file named using the following shell command:
    2. Now open and 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!
    3. 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 69 - 71). The backslash character indicates the beginning of an escape sequence. The table on page 71 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.

    4. 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:
         nenscript -2rG -p- | lpr -h

  5. 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
    1. Do the following to copy this program to your lab1 directory:
      • In Netscape, you should have open the online version of the this handout. Go down to the link to the file and click on it. You should see the Java program. Study it for a few minutes particularly noting the use of the escape sequences for the tab character.
      • Now choose File, then Save As, from the menu. In the selection box, type in the complete path name for the file so it will be saved in you lab1 subdirectory (part of the path should already be there).

        *** Netscape HINT: When you need to supply the pathname for a file when saving something from the Web or attaching a file it is usually easiest to type the pathname. However occasionally you may want to browse to find the file. In the Save As window you should see two side-by-side windows -- one labeled Directories and the other labeled Files. To browse click on the name of the directory you want to look in then click the Filter button. The Directories and Files windows will now show you the contents of the directory you just selected. Continue this (select a directory then press Filter) until you find what you want. Notice that as you do this the pathname in the Selection box is changed to indicate where you currently are.

    2. Compile and run the Names program to see how it works then open it in emacs. Add code so that your name and hometown and the name and hometown of at least two classmates sitting near you in lab also are printed. Save, compile and run the program. Make sure the columns line up.

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

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

  6. 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.2 (pages 67 - 71) 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 contains the following program:
      // *******************************************************************
      // FILE:
      // Purpose: Demonstrate the different behaviors of the + operator
      // *******************************************************************
      public class PlusTest
          // -------------------------------------------------
          // main prints some expressions using the + operator
          // -------------------------------------------------
          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 ("The first computer was invented about" + 55 +
      			    "years ago.");
      	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.");
    2. Study the above program a minute, then in Netscape open it (click on the link above) and save it to your lab1 directory.
    3. Compile and run the program. For each of the last three output statements (the ones dealing with 8 plus 5) write down what was printed. Now for each explain why the computer printed what it did given that the following rules are used for +: [*** Write your explanations on one of the programs you already have printed out.]
      • If both operands are numbers + is treated as ordinary addition. (NOTE: in the expression a + b the a and b are called the operands.)
      • If at least one operand is a string the other operand is converted to a string and + is the concatenation operator.
      • If an expression contains more than one operation expressions inside parentheses are evaluated first. If there are no parentheses the expression is evaluated left to right.
    4. The statement about when the computer was invented is too scrunched up. How should that be fixed?

  7. 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 and string concatenation. Print out a copy of your completed (and working!) program.

TURN IN the following: