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 Hello.java, 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/Hello.java 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:  Hello.java                                                            
      // 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

      javac 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 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 -- Hello.java and Hello.class. Hello.java 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:
      Hello.java:15: unclosed string literal
      	System.out.println ("Hello, World!);
                                  ^
      Hello.java:15: ';' expected
              System.out.println ("Hello, World!);
                                                  ^
      Hello.java:17: 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: Hold the Alt key (this is called the META key in emacs), and 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.
      Hello.java:15: cannot find symbol
      symbol  : method primtln(java.lang.String)
      location: class java.io.PrintStream
              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 32) 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
             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. 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 Hello.java to a new file named MyHello.java using the following shell command:
           cp Hello.java MyHello.java
      
    2. Now open MyHello.java 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 37 - 38). The backslash character indicates the beginning of an escape sequence. The table on page 37 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. Compile and run your program to verify that the output is correct (and that the border is still aligned nicely).

  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 Names.java.

    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 Names.java 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 Names.java. 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. 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 34 - 37) 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:
      // *******************************************************************
      // FILE: PlusTest.java
      // 
      // 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 three output statements (the ones dealing with 8 plus 5) determine the following based on the rules Java uses for evaluating expressions.
      • which of the two + operators is evaluated first and why
      • the result of just that evaluation (not the whole answer) and 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.

Submission:

Making an archive file

An easy way to send someone several files at once is to make an archive file using the tar command. (Tar stands for tape archive, a rather archaic name for this function.) To "tar up" all of the java files in your lab1 directory, do the following:

When you're done, do an ls and you should see YourName.tgz in your directory. To submit your code cp the tgz file to the directory:
   /home/staff/bouchard/CPSC120/lab1
You can look back at lab0 if you forget how to do this. Finally, you should log out and copy the tar file of your code for this lab to the labs directory of your partner. You can extract the contents of the tar file with the command:
   tar xzf YourNames.tgz