Lab 1 In-Class: Introduction to Java

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 (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 simple 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. First you need to open a new file in emacs: To do this, 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 ~/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!)
      • 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. 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). PAY ATTENTION AS YOU TYPE: You should notice that emacs automatically indents properly after you press enter (when it doesn't you probably have a syntax error such as a missing quotation mark or semicolon). Also when you type a closing brace or parenthesis your cursor jumps to the corresponding opening one.

      // ********************************************
      // 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 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 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:
      
      Hello.java:15: unclosed string literal
              System.out.println ("Hello, World!);
                                  ^
      Hello.java:15: ')' 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 62) 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 66 - 68). The backslash character indicates the beginning of an escape sequence. The table on page 67 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 MyHello.java
      

  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. 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 64 - 66) 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 ("The first computer was invented about" + 60 +
      			    "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 Firefox 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. Your explanation should be based on the following rules Java uses for evaluating expressions involving more than one + operator: [*** Write your explanations on one of the programs you already have printed out.]
      • 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.
      • 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.

    4. The statement about when the computer was invented is too scrunched up. How should that be fixed? [Write your answer on the same printout as the other answers.]

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

TURN IN the following: