CPSC 124 Introduction to Programming Spring 2005

Lab 1: Introduction to Linux and Java

Introduction

An operating system is the basic software that runs the computer - it controls the hardware of the computer (such as disks and memory) and runs application software (like word processing programs and web browsers). It is the first thing loaded when the computer starts up.

Most of you are familiar with one or more of the Microsoft Windows operating systems (Windows 2000 and Windows XP are the most recent versions). You may also have used a Macintosh, which uses the MacOS operating system (the current version is Mac OS X). The Math/CS Department at HWS uses an operating system called Linux on its computers. Linux is a version of Unix, an operating system often used for servers and in academic environments.

task to do This lab will introduce you to the Linux environment at HWS. You'll also see how to enter and run a Java program, and how to print your results. It contains a lot of useful information, and has some specific tasks to accomplish mixed in. These tasks are marked with a checkmark icon (shown on the right) to help you find them. However, you'll get a lot more out of the lab if you read through it in order instead of just skipping to the checkmarks.

Much of this lab was originally written by Professors Eck and Orr.

Starting Linux

The Math/CS Department has a computer lab in Lansing 310 with 12 computers running only Linux. You can use these computers to work on assignments outside of lab.

task to do Gulick 208 has 31 computers configured to run both Windows XP and Linux. Only one operating system can control the computer at a time, so these computers are configured as dual-boot machines. When you sit down at one of these computers, it will probably be running Windows. To start Linux, reboot the computer by pressing ctrl-alt-delete to get the Windows login screen, then click the "Shutdown" button on the screen. Make sure that "Restart" is selected in the dialog box that appears, and click "OK". A message indicating that "Windows is shutting down" will appear, and the machine will reboot. Wait a little while, and eventually you will see a screen with the green Gateway logo for a second time, immediately followed by a menu which allows you to choose "Windows XP Professional" or "Linux". Use the down arrow key to select "Linux" (quickly - you only have 30 seconds to do it) and press the "Enter" key. Wait some more, and eventually you will get the Linux login screen.

You can also use your own computer to work on assignments outside of lab. If you have a Windows computer, you'll need to install a free program called VNC which will allow you to connect to a computer in the Lansing lab. See the "VNC" section of Professor Eck's Using Linux at HWS document for information on how to obtain and use the software. If you have a Macintosh, see me for some suggestions.

Regardless of how you start Linux - by sitting down in front of a computer in Lansing 310, by rebooting a computer in Gulick 208, or by using VNC to connect - you should now have a login screen (likely titled something like "SuSE Linux 9.0") where you can enter your username and password.

Logging In and the KDE Desktop

task to do Go ahead and log in - enter your username and password, leaving the "session type" set to KDE. Your username is the same as it is for Windows login (but be sure to type it entirely in lowercase letters). Your password should have been provided to you at lab - it will be different from your Windows password! (You'll have a chance to change your password to something easier to remember a bit later.) Press "Return" or click the "Go" button, and wait while KDE starts up. This can take a while, especially the first time you log in.

Eventually, the KDE Desktop will appear. If this is your first time logging in, there will probably be a "Welcome to SuSE Linux" window open. Close it for now. You might also see something called "Kandalf's Tips" about using KDE; go ahead and close this as well.

The KDE Desktop is similar in function to the desktop in Microsoft Windows, and you'll notice a number of common features. For now, move on to the rest of the lab (you'll have a chance to explore KDE more in a bit).

Logging Out and Shutting Down

suse menu logo When you are done working for the day or are going to be away from the computer for a while, you need to be sure to log out - if you don't, anyone who comes along will have access to your account and all your files! To log out, click on the gecko head/start menu in the lower left corner of the screen (the icon you are looking for is shown on the right) and look for "Logout 'username'" option at the very bottom of the menu that pops up. If you are in Lansing or using VNC, just choose "logout" in the window that pops up. If you are in Gulick, you also need to reboot the computer - choose the "Restart Computer" option in the dialog box that pops up and click "OK". The computer will automatically reboot to Windows, so you don't need to wait around for it to finish.


The remainder of this lab (if you are reading it on paper) is available online at http://math.hws.edu/~bridgeman/courses/124/s05/labs/lab01/. (You can also find this lab, and all of the other labs for the course, on the syllabus page at http://math.hws.edu/~bridgeman/courses/124/s05/syllabus.html.)

konquerer logo You can run KDE's web browser (Konqueror) by clicking on its icon (shown on the right) in the panel at the bottom of the screen or you can click on the gecko menu (the green gecko head in the bottom left corner of the screen) and choose "Internet", then "Web Browser", then either "Konqueror" or one of the other choices.

To save paper, you should try to work with the rest of the lab online rather than printing it out.


Getting Around in KDE

As mentioned above, KDE looks a lot like Windows and you should use what you know about Windows to help you use KDE. The desktop contains a number of icons, including a trash can, icons for printers and drives, and icons for programs. At the bottom of the desktop is the panel, which provides the gecko menu, icons for launching certain common programs, and access to minimized windows (very much like the panel in Windows).

suse menu logo On the far left side of the panel is a green gecko head icon - this is the gecko menu, which is just like the Start menu in Windows. To the right of the gecko are a collection of icons that can be used to quickly launch various programs.

The main part of the panel is an area like the following:

panel

The right section in the image shows a tab for each window that has been opened on the desktop. Clicking a tab will bring a window to the front (and restore it if it has been minimized). To the left is the "pager" which lets you choose between several "virtual desktops". (The picture shows four; you probably only have two.) Clicking on the pager lets you switch between them. Multiple desktops can be useful for organizing your work if you have lots of windows open at once.

task to do Take some time to explore KDE - explore the menus, open some windows, try a few games, try clicking and right-clicking on some things. KDE has tooltips, so if you move the mouse pointer over an icon and leave it for a moment, a little message describing the icon will pop up. This is very useful for exploring a new environment. Note: by default, KDE is a one-click environment, so you only need to click once on a icon to start a program. If you forget and double-click on something, you will get two copies of the same program running at once. You can change this behavior if it annoys you.

Choosing "Control Center" from the gecko menu lets you configure many of KDE's options, such as the single-click behavior. It's worth exploring what the options are, even if you don't want to change anything right away.

The Command-Line Interface

In Linux, most things can be done using either a command-line or GUI interface. ("GUI" stands for "Graphical User Interface" - it refers to interfaces which provide windows, buttons, menus, pictures; in a command-line interface, you type commands in directly.) You are probably more used to a GUI interface, but some tasks require (or are easier with) the command line. The labs will tell you how to use the command-line interface for tasks; feel free to explore and find the GUI equivalents.

konsole In order to use the command-line interface, you must first open a terminal window (also known as a command-line window, shell window, or console window). In KDE, the standard terminal window program is called Konsole. There are two ways to get a Konsole window: either click on the appropriate icon in the panel at the bottom of the screen (shown on the right), or click on the gecko menu and then choose "System", "Terminal", and "Konsole" as you navigate through the menus.

The computer won't execute any commands typed in the Konsole window until you press Enter (or Return, depending on your keyboard) so be sure to do that after each command. If you type a command and decide that you don't want to execute it, press ctrl-C to cancel it. You can also press ctrl-C while a command is running to stop it.

You can close the Konsole window by typing the command

exit

(and press Enter)
or by clicking the "X" icon in the upper right corner of the window (just like in Windows).

Learning More

If you are new to Linux or new to the HWS environment, you should check out Professor Eck's Using Linux at HWS document. Pay particular attention to the "Limits" and "Emergencies" sections.

You can find out more about SuSE Linux by clicking on the gecko head icon labelled "SuSE" on the desktop (not the gecko head menu in the panel at the bottom of the screen).


Changing Your Password

task to do The first thing you do should be to change your password to something only you know, and which is easier to remember than the random one you were assigned. You can use the same password as you use for Windows login if you want.

The password-changing program is a command-line program, so open a new Konsole window if you don't already have one open.

Once you have the Konsole window open, make sure the window has the mouse focus (the title bar of the window should be blue - click the mouse in the window if it isn't) and type the following command:

 kpasswd

You will be prompted for your current password (the one you were given), and then your new password (whatever you want). Your password won't be shown on the screen, so type carefully. You'll be asked to enter the new password twice as a precaution against typos. You can use any characters except spaces in your password - you should avoid real words (including real words spelled backwards), and use a mix of letters and non-letters. Also, your password is case-sensitive, so make sure the "Caps Lock" key isn't on (unless you mean for it to be). If your password was successfully changed, you should see the message "Success: Password changed".

Navigating Directories

directory tree

Linux Directory Structure

As in any operating system, files in Linux are organized into "directories" or "folders". Each directory can contain files and/or subdirectories, which in turn contain files and/or subdirectories. The directory structure is often represented by a hierarchy; the top directory is known as the "root directory" and is usually written as a slash (/). The picture on the right shows part of a directory organization that might exists on our Linux systems. The root directory is shown at the top and lines indicate what files/subdirectories are contained in what directory. The files in this example of HelloWorld.java (two copies), index.html, and answers.txt - everything else is a directory.


Absolute Pathnames

Every directory and file on the system can be uniquely identified by tracing a path from the root directory. This path is known as the absolute pathname for the file or directory. Each directory name in the path is separated by a slash (/) - note that this is the opposite of Windows. Absolute pathnames always start with /.

For example, the absolute pathname for the index.html file is /afs/.afs.hws.edu/home/bridgeman/www/courses/index.html. Note that the two copies of the HelloWorld.java have different absolute pathnames (so they are actually different files): /afs/.afs.hws.edu/home/alice/cs124/lab01/HelloWorld.java and /classes/s05/cs124/labs/lab01/HelloWorld.java.

Home Directories and pwd

You have a "home directory" which contains your personal files. The absolute pathname for your home directory is /afs/.afs.hws.edu/home/username where username is replaced by your own user name. (Note that the "Using Linux at HWS" document hasn't been updated to reflect this.) When you first open a Konsole window, the current directory is your home directory. The absolute pathname for my home directory is /afs/.afs.hws.edu/home/bridgeman; in the example above, there is also a user alice whose home directory /afs/.afs.hws.edu/home/alice.

You can enter the command

 pwd

(for "print working directory") at any point to see what directory you are in - if you've just opened a Konsole window, it should show /afs/.afs.hws.edu/home/username.

Viewing Directory Contents (ls)

You can see a listing of the files and subdirectories in the current directory with the command

 ls

(for "list"). Color-coding is used to indicate different kinds of things - directory names are blue, for instance. To see a more detailed listing, use

 ls -l

or

 dir

This shows you a bunch of information, including the permissions, user and group which own the file, the size of the file, the date and time it was last modified, and its name. (You can ignore most of this information for now.)

If you want to see the listing for one or more directories other than the current directory, you can specify those names after the ls command name. For example, use

 ls -l /classes/s05/cs124

to see a listing of the /classes/s05/cs124 directory, where you'll find files that you need for labs and projects.

Changing Directories (cd)

To change the current directory, use the cd command (for "change directory"). The name of the directory you want to change to follows the command. For example:

 cd /classes/s05/cs124

changes to the /classes/s05/cs124 directory. If you type pwd now, you should see /classes/s05/cs124.

Relative Pathnames

Always using the absolute pathname for a file or directory can result in a lot of typing. Fortunately, there's a shortcut - you can also refer to a file or directory using a relative pathname, which tells how to find the file or directory from the current directory. ("Relative" refers to the fact that the pathname locates the file relative to where you currently are, rather than from some fixed point like the root directory.)

Consider the directory hierarchy example above. If you are currently in the /classes/s05/cs124 directory, you could type cd /classes/s05/cs124/labs to change to the labs subdirectory. You could also use the relative pathname instead and just type cd labs - since the pathname doesn't start with /, the system appends the pathname you specify to the current directory to figure out the absolute pathname of the directory you want to switch to. Similarly, you could use cd labs/lab01 to change to the cd /classes/s05/cs124/labs/lab01 directory if you are currently in the /classes/s05/cs124 directory.

Note that relative pathnames never start with / - this is what distinguishes them from absolute pathnames. To figure out what an absolute pathname refers to, always start at the root directory. To figure out what a relative pathname refers to, always start at the current directory.

Directory-Name Shortcuts

While you can always specify the absolute or relative pathname for the directory or file you want, there are some shortcuts which are useful.

~ is a shortcut for your home directory, and is an absolute pathname (even though it doesn't start with /). So you could use

 cd ~

to change to your home directory from anywhere, or

 cd ~/cs124

to change to the cs124 subdirectory in your home directory (if you have such a directory).

You can also use ~ without a slash after it:

 cd ~bridgeman/handin

changes to the handin subdirectory of my home directory (username bridgeman) - compare this to

 cd ~/bridgeman/handin

which would change to the handin subdirectory of the bridgeman subdirectory in your home directory (if you had such a directory).

Another useful shortcut is .., a relative pathname meaning the directory above the current directory. For example, if you were in the directory /classes/s05/cs124/labs/lab01, you could use

 cd ..

to change to the /classes/s05/cs124/labs directory or

 cd ../..

to change to the /classes/s05/cs124 directory (going up two levels). You can also combine .. with other things - for example, if you were in your home directory,

 cd ../bridgeman/handin

would be an alternative to cd ~bridgeman/handin. To figure out what this does, remember that your home directory is /afs/.afs.hws.edu/home/username so the .. takes you up one directory (to /afs/.afs.hws.edu/home), then the bridgeman/handin is appended so you get /afs/.afs.hws.edu/home/bridgeman/handin.

A third shortcut is ., a relative pathname meaning the current directory. For example, you could use

 ls .

to get a directory listing of the current directory (though just ls by itself accomplishes the same thing). . may seem silly now, but it is useful for copying files.

Other Basic Commands

Creating Directories

Directories are important for keeping your work organized. You can create new directories with the mkdir command (for "make directory") - the name of the new directory is an absolute or relative pathname specified after the command.

task to do At this point, you should create a new subdirectory called cs124 in your home directory to hold the files for this course. Try to figure out how to do this yourself, but if you get stuck, highlight the following region with the mouse to see the solution:

(Whenever you see the light yellow background, you can highlight the area to see hints for how to accomplish the task - but you should try to work it out for yourself before peeking!)

task to do While you are at it, create a lab01 subdirectory in the cs124 directory you just created. You'll be using this subdirectory shortly.

Deleting Directories

Sometimes you no longer need a directory you've created. You can delete an empty directory using the rmdir command (for "remove directory"):

 rmdir ~/cs124

would delete the cs124 directory that you just created. Don't do this! (though if you do, you can create it again with mkdir)

Note that directories must be empty (i.e. they can't contain any files or subdirectories) before they can be deleted. You'll get an error message if you try to delete a directory which isn't empty. See "Deleting Files" below for how to delete files; use rmdir on each contained subdirectory to remove the subdirectories.

Copying Files, and Wildcards

In many labs, you'll be working with some provided files (as well as creating your own). To copy files, use the cp command (for "copy"):

 cp source destination

where source is replaced by the name of the file you want to copy (including its path) and destination is replaced by where you want to copy the file to (either a filename or directory).

If you want to copy several files to the same destination, you can use a separate cp command for each or you can specify them all at once:

 cp source1 source2 ... sourceN destination

In this case, the destination must be a directory name.

You can also use a wildcard to specify multiple files to copy. The wildcard character (*) matches any number of characters (including zero). For example:

 cp * destination

copies all of the files in the current directory to the destination, and

 cp *.java destination

copies all of the files in the current directory whose names end with .java to the destination.

task to do Copy the HelloWorld.java file from the /classes/s05/cs124/labs/lab01 directory to your cs124/lab01 directory. (You'll be using this file in a bit.)

Copying Entire Directories

You can copy entire directories with a variation of the cp command:

 cp -r source destination

where source is replaced by the name of the directory you want to copy (including its path) and destination is replaced by where you want to copy the directory to. The -r means to copy recursively - it will copy the named source directory, all of the files in that directory, all of the subdirectories in the directory, all of the files and subdirectories in the subdirectories, etc.

Instead of creating a lab01 directory in your cs124 directory and then copying files into it, you could have copied the entire lab01 directory in one step with:

 cp -r /classes/s05/cs124/labs/lab01 ~/cs124

Moving (Renaming) Files

Copying makes a new copy of a file, without changing the original copy. If you want to move a file or rename it (so the original file no longer exists), use the mv command (for "move"):

 mv source destination

where source is replaced by the name of the file you want to move (including its path) and destination is replaced by where you want to move the file to (either a filename or directory). If the destination is a directory, the file retains its original name (and is just moved); if the destination is a filename, the file is renamed.

You can move multiple files and use wildcards to identify the files to be moved just like with cp e.g.:

 mv *.java destination

moves all of the files in the current directory whose names end with .java to the destination. Note that if you are moving multiple files, the destination must be a directory.

Deleting Files

You can delete files with the rm if you no longer need them. Note: if you delete with rm, the files are really gone! There's no undelete feature, so be sure you really want to delete the file before you do it. As with many of the commands we've seen, you name the file or files to delete after the command name e.g.

 rm ~/cs124/lab01/HelloWorld.java

would delete the HelloWorld.java file that you just copied to your directory, and

 rm ~/cs124/lab01/*.java

would delete all of the files ending with .java in your lab01 directory.

Working With Java Programs

Running a Java Program

Running a Java program is a two-step process: first you must compile the source code (the .java file you copied) into bytecode, then you must run the Java interpreter to execute the bytecode.

To compile a Java program, use the javac program. You should run javac from the directory where your files are. The name of the file(s) to compile are specified after the command name.

task to do Compile the HelloWorld.java file you copied to your lab01 directory.

You can also use wildcards to specify the files to compile e.g.

 javac *.java

will compile all of the files ending with .java in the current directory.

task to do When the javac command completes (it should be very fast), use ls to verify that there is now a file called "HelloWorld.class" in your directory. This is the compiled bytecode, and this is what is needed to actually run the program.

task to do To run the program, use the java command:

 java HelloWorld

"java" is the name of the Java bytecode interpreter and "HelloWorld" is the name of the class file where the "main" routine is. Note that you do not include ".class" after "HelloWorld"!

task to do Try running the program a second time - since you already have the class file, you don't need to recompile with javac unless you change the source code file.

Editing a Java Program

In order to create or edit a Java program, you need to use a text editor. There are many text editors to choose from in Linux; emacs is recommended, but you may choose another editor if you wish. Text editors are different from word processors like Microsoft Word, because they are only concerned with editing plain text - they don't do all the formatting with fancy fonts, colors, tables, pictures, and all the things you can do in Word.

To start emacs, type

 emacs &

in a Konsole window. The "&" means to run the editor in the background - really what this means is that you'll get the prompt back in the terminal window once the editor has started up, so you can continue using the terminal window for commands while you are using the editor.

To open a file, choose File -> Open File from the menu in the emacs window. You'll see a Find file: prompt displayed at the very bottom of the emacs window - enter the name of the file you want to open.

If you know that you want to edit a particular file when you start up the editor, you can tell it to immediately load that file. Use

 emacs HelloWorld.java &

to start up an editor and open the "HelloWorld.java" file immediately. Note that if you are not in the directory containing the file, you'll need to include the pathname of the file e.g.

 emacs ~/cs124/lab01/HelloWorld.java &

will open the file no matter what the current directory is.

emacs is a very powerful editor, and has a number of features which are useful for programming:

Printing

There are many ways to print things in Linux, some of which produce more satisfactory output than others.

One important thing to keep in mind is that by default, any printing command will print to the laser printer in Lansing 310. This is not what you want if you are in Gulick, or are logged in remotely from your own computer. However, you can print to another printer if you know its name. The names for the available printers are:

(Linux can only print to printers it has been configured for, so you can't print to your own printer in your dorm room.)

Many GUI programs provide their own printing functions (usually under the "File" menu), but you have much more control over how things are printed and where they end up if you use the command line printing programs. (Some programs only print to your default printer and don't give you a choice about it!) Konqueror (a web browser) is one well-behaved program - the "Print" command is on the "Location" menu, and gives you a drop-down menu to select the printer from. To save paper, you should click on "Properties" near the printer selection and choose to print two pages per sheet. If you choose to print out the lab handouts, you should use this option!

emacs, on the other hand, is not well-behaved when it comes to printing. You should print your Java programs from the command line.

The basic program for printing from the command line is lpr:

 lpr -Pprinter filename

where printer is replaced by the name of the printer you want to print to and filename is replaced with the name of the file you want to print. If the file isn't in the current directory, include the path (relative or absolute) with the filename.

If you are printing text files, it is strongly recommended that you print them in a format that puts two pages side-by-side on one piece of paper. To do this, use

 enscript -2r -Pprinter filename

If you are printing Java programs, there's a third command which produces much nicer output than lpr or enscript:

 a2ps -Pprinter filename

a2ps also prints in a two-page-on-one format which saves paper.

You can see what jobs have been sent to the printer using the command

 lpq -Pprinter

This is handy to see if there's a long line ahead of you.

You can cancel a job with

 lprm -Pprinter jobnum

where jobnum is the number of the job you want to cancel. You can find out a job's number with lpq.

Exercises

task to do Here are the exercises for this week's lab writeup. The writeup is due in lab next Thursday.

  1. Try the procedure outlined under "Handin" below to hand in the file you copied to your lab01 directory. This won't be the final version that you'll hand in, but try it now to be sure that the handin procedure works and that you know what to do. You can handin again when you are done to hand in your final version.

  2. A comment in a program is text in the program file which is ignored by the Java compiler. Comments are used by programmers to document the source code to a program. Documentation may consist of the author's name, copyright information, or just explaining what various parts of the program do. There are two ways to indicate comments in Java. A single-line comment begins with // (a double slash) - everything following the // on the same line is ignored. A multiline comment begins with /* and ends with */ - everything between the /* and the */ is ignored, including line breaks.

    Open the HelloWorld.java program with emacs and add comments to the beginning of the file that include your name, the date, the lab number, and something about what the program does. Your comment may look something like:

    /* Stina Bridgeman               CS124 - Lab 1
     * This program says hi.
     */
    

    Save your program, recompile it, and run it to make sure it is still working properly.

  3. Still using emacs, modify your HelloWorld program so that it prints out "Helloooo...." after the "Hello world!". That is, the output when you run the program should be:

    Hello world!
    Helloooo....
    

    Save your program, recompile it, and run it to make sure it works properly. Check that your output looks exactly like what is shown above - if it doesn't, the program doesn't meet the specifications!

  4. Check out the Using Linux at HWS page, and answer the following questions. Create a new file in your lab01 directory for your answers (in emacs you do this by opening a file with a name that doesn't exist - the file will be created the first time you save).

    1. If you accidentally delete a file, is there anything you can do to get it back? Explain.
    2. If your computer crashes, why shouldn't you just reboot it? Explain, and list two strategies for fixing problems without rebooting.
  5. Write at least two paragraphs about other things you found while exploring and learning about Linux and/or KDE. Put your answers in the same file that you created in the previous exercise. You should show that you've make an effort to explore the environment and the available resources beyond the bare minimum that is mentioned in this lab. For example, what interesting things did you find in the gecko menu? What interesting games did you find and play? Did you find the SuSE help center? What kind of information does it have?

  6. Send me (bridgeman@hws.edu) an email telling me the following:
    1. your name
    2. any computer courses you have taken (e.g. CPSC 120)
    3. your experience with computers (other than programming experience) - this could be using them to write papers, read email, play games, etc
    4. any programming experience you might have had (list languages and what you did) - this includes things like programming calculators
    5. why you are taking this course
    6. are there any particular kinds of programs you'd like to be able to write, or any particular tasks you want to write a program to do? (describe them briefly)

Handin

You will be using electronic handin to submit your work for this course. Make sure that your modified HelloWorld.java program and the file you created for #4 and #5 are in your lab01 directory, and then copy the entire lab01 directory to the handin directory ~bridgeman/handin/124/username where "username" is replaced by your Unix username.

Verify that your handin worked by viewing the contents of the handin directory with ls.

Also don't forget to email your answer to #6.


Valid HTML 4.01!