Lab 1 In-Class: 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 Emacs
  • Learn how to find and correct syntax errors in your code.
  • Understand string concatenation and escape sequences.

Getting Started

Generally in lab you will be typing shell commands into an xterm (terminal) window, typing your programs into emacs, and using Firefox to access files that have been put on the Web for you to use in lab. So, to get started

The following instructions lead you through writing and modifying several Java programs.

  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. Programs start out as text files created in a text editor (emacs for us). So, first you need to open a new file, named, in emacs: To do this, activate your emacs window then

      • Use the keystrokes C-x C-f (hold down the Control ctrl then hit the x-key followed by the f-key) OR choose Visit New File under the File menu.
      • If you used key strokes, in the Find File: location at the bottom of the window fill out the full pathname of the file (which should be ~/cs120/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!) HELPFUL HINT - TAB COMPLETION!!! When typing in the filename, you can type just a few characters then press TAB. If there is only one file (or directory) that matches the characters you have typed the system will complete the file name. If you used the menu you can either type the path into the Name box (TAB also works here) or you can browse to find it.
      • Press Enter after typing in the file name and you should be taken up to the blank buffer. You'll type your program into this buffer.

    2. First read the following emacs hints then type in the program below.
      • 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).
      • Emacs automatically indents properly - when on a new line just start typing without spacing over (note - the Tab key won't space over). Emacs will properly indent after you press enter (when it doesn't you probably have a syntax error such as a missing quotation mark or semicolon).
      • If you add a line to the program and it doesn't properly indent, press the TAB key while anywhere on the line. This should indent it properly if your syntax is correct.
      • When you type a closing brace or parenthesis your cursor jumps to the corresponding opening one. PAY Attention - this can help you be sure you have your braces matching correctly.
      • Finally note that the program is color-coded with different programming features in different colors.

      // ********************************************
      // 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 at the prompt 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 (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.

    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 version of your program 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 (use the up arrow key to retrieve your javac command!). (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!);
                                                  ^ reached end of file while parsing
      3 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 three. 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 semicolon and can't find it (it already read past it) so that is the second error. Finally, it keeps reading and comes to the end of the file (past the last brace) but it has not found a complete syntactically correct program so that is the third 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. Once again several errors are reported when there is really only one error. Unfortunately none of the messages tells you exactly what is wrong (the compiler can't know where you meant to start the string since Hello could be a variable, something we study next week) but there is enough information for you to get an idea.

    5. Fix the last error (put the quotation mark back), then change the spelling on println to primtln. Recompile and you should see the following message. cannot find symbol
      symbol  : method primtln(java.lang.String)
      location: class
              System.out.primtln ("Hello, World!");
      This tells you the compiler can't find a symbol then it says the symbol is a method named primtln that takes a String as an argument. It is looking in the PrintStream class since System.out is a PrintStream object. When the message is "cannot find symbol" most likely the problem is misspelling (or mis-typing) the symbol it says it can't find.

    6. Fix the last error and make sure the program compiles.

  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 34) 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. Your 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 in emacs (just do File Open or C-x C-f again - you can have several files open in emacs at one time) 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 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.

    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:
          enscript -2rG

  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 Firefox, you should have open the online version of this handout. Go down to the link to the file and click on it. You should see a window that gives you a choice of opening the file or saving it to disk. Choose the save option. The next window will have a box for the name of the file and one for the folder to save the file in. The name should be The folder will be the default for Firefox, which is probably the Desktop the first time you do this (later it will be the last place you saved something). You should save this in your lab1 directory so choose the "Browse for other folders" option. In the next window, you can get to your lab1 directory by double clicking on Home on the left, then browse the list of files and directories on the right until you get to lab1 (double click directories to open them). Click Save when you have lab1 as the directory. (NOTE: If you prefer, instead of browsing, you can put the full pathname of the file in the box for the name of the file.)

    2. Open the file in emacs and study it for a few minutes particularly noting the use of the escape sequences for the tab character.

    3. Compile and 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. Save, compile and 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.)



  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.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 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 (7 + 8);
              System.out.println ("7" + "8");
              System.out.println ("7" + 8);
              System.out.println ("7" + 8 + 9);
              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. Compile and run the program, study the output and observe the following:
      • The first print statement probably did what you expect - it concatenated the two strings and printed the whole string on one line.
      • For the next three statements the following rules for evaluation are used:
        • If both operands are numbers the + operation 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.

        So, the output for the second print statement was just the number 15 - the two operands for the + operator are numbers so they were added and the result printed. In the third line the two operands for the + are strings (be sure you understand why) so the two strings are concatenated and the result 78 is printed. Finally in the fourth line "7" is a string and 8 is a number so the 8 is converted to a string and the two strings are concatentated resulting in the string "78".

      • For the next four statements the expression to be printed contains two + operators. When there is more than one operation to be performed the following additional rules are used:
        • If an expression contains more than one operation expressions inside parentheses are evaluated first.
        • If there are multiple + operations with no parentheses to specify grouping the expression is evaluated left to right.

        So for the first of the four statements there are no parentheses so the leftmost + is evaluated first. The first operand is a string so + denotes string concatenation and the result is the string "78". The second + then concatenates the string "78" with the 9 to give "789".

    4. For each of the following three output statements (the ones dealing with 8 plus 5) do the following. You can write your answers on the code above or on one of the other printouts. Be sure your answers are based on the rules Java uses for evaluating expressions.
      • specify which of the two + operators is evaluated first and why
      • give the result of just that evaluation (not the whole answer) and indicate whether the result a string or a number.

    5. Notice that the statement about when the computer was invented is too scrunched up. Modify the code to fix this problem. Your modification should be to the existing strings - the basic format should still be a string concatenated with the number 60 which is then concatenated with another string.

  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 (add 10 and 13) and string concatenation. Make sure that your program includes comments that document the heading information (Filename, Author, and Purpose) and the key steps of the program.

TURN IN the following: