FHTW Berlin

FHTW Berlin
Fachbereich 4
Internationale Medieninformatik
PROG1: Programmierung I
Wintersemester 02/03


Laboratory 0:

The Manual of Dexterous Compilation


Prologue


A learned software consultant was once approached by a bedraggled pilgrim who had not showered in many days.

"O wise one, I am troubled. I must continually master new languages, operating systems, and applications in order to remain competitive, and I must remember so many commands and keystrokes and directories where everything is supposed to be kept, that I cannot write a line of code without devoting months of effort and frustration. Yet you have mastered all these with ease, and even find spare time to go to the beach and see movies. How may I discover this programmer-nature, that I as well may become sought after in business and academia and still have a social life?"


The consultant responded by lifting his index finger.


The pilgrim went away, perplexed.

A week later, the pilgrim returned with bloodshot eyes, wearing black wrist guards.

"O wise one, woe is me! For I have reflected much upon your answer, and concluded that the only answer was to become a touch typist so that I could write code faster. I mastered the Dvorak keyboard and can now type at 80 words per minute, but now I have Repetitive Strain Injury and must wear these wrist guards and the pain is most bothersome! Clearly you must be mistaken when you lift your finger."


The consultant responded by depressing his index finger.


The pilgrim went away, more confused than ever.

The consultant was not surprised to find the pilgrim returning a full two weeks after that, this time pale and near death.

"O wise one, I believe that you do not know the answer. For your depressed finger suggests a bowed head, so I have persued the ascetic life by fasting, meditating, and practising yoga. I am much more spiritually complete, but I still find it overwhelming to sit down and write a line of code. Clarity of thought and purity of the soul is not the answer; you have misled me. I believe I know what this programmer-nature is: it is merely the ability to speed-read computer manuals together with a photographic memory. It is the only explanation for your success."

The consultant was silent for a moment, and then responded by lifting, and then depressing, his index finger.

At this the pilgrim was enlightened.

A note from your teacher: Help was only a mouse-click away. The Integrated Development Environment (IDE), though still not a cure-all, can alleviate many of the pilgrim's complaints and make programming a more enjoyable experience. This laboratory is designed to familiarize you with Borland's JBuilder, the IDE we will be using in this course.


Logging In

We will be starting on the old Linux machines in VG 212.

If the machines are turned off, turn them on. They should not be turned off, but some people do not listen to their teachers. You should see a screen with lots of names, and two field to enter in your username and password. You did fill out the form yesterday for the FB4 username and password, didn't you? If not, take care of that now!

Later in this document and in other handouts, we will use the following convention to describe the process of wading through menus: Menu Name > First Menu Selection > ... > Last Menu Selection. Sound reasonable? Then let's proceed...

Finding Your Homedir

Now that you have your username, you also have a home directory. This is where all your files can be placed. The environment we will be using is the KDE. There are goodies hidden around such as a file manager, that you can use to create directories for grouping your files, or for moving files about. You can also open up a so-called "shell" by clicking on the seashell in the bottom line of icons. If you enter cd and hit return then you are automatically in your home directory. This command is called "change directory" and is a magic spell for moving around directory levels.

All the software that we will be using is located in the LOCAL menu. Click on the lower left hand icon, and you will see a number of menus. Pick LOCAL, and have a look around. You can find the browsers here, and JBuilder.

Now store some files you will need for the exercise in your home directory. Create a directory such as prog1. Save the files JavaEyes.java and JavaEyes.jar in the directory. You do this by klicking the right mouse button on the links on the file names, and saving them with the same name in your new directory.

Logging Out

When it comes time to log out, be very careful. Unix is very fussy about this. Think of it as a friend who will be insulted if you do not properly say goodbye. The proper way is to click on the lower left hand icon and select "Benutzer abmelden". You will be asked if you want KDE to remember what you were doing, you can choose to do this, or not. Try out both sometimes. This is also a choice "herunterfahren". Selecting this is the one and only way to safely prepare the machine for powering down. Never power down the machine without doing this first.

So What is an IDE, Really?

An IDE is just a tool which makes programming easier. To understand the benefits of an IDE, you must first understand how programming is done without an IDE.

So, how would we write a computer program without an IDE? First, we would type the program into a text editor (like emacs or xedit, both available on our machine). Next, we would need to use a translation program (called a compiler), to translate the program into a language the computer can understand. If our program contained errors (as is likely for non-trivial programs), we would use a third program (called a debugger) to help us remove as many "bugs" from our program as possible.

This is fine for simple programs, but what if we wanted to create a large graphical application? This would be a daunting task, as a text editor is not a very good interface for creating graphics programs. Also, a large application might span many files, being simultaneously edited by many software developers. How might we manage these files in a way that is consistent and easy to understand?

Enter the IDE. A good IDE combines a text editor, compiler, and debugger into one package. Because all three tools are generally made by the same company, the degree of interoperability between them is very high. Additionally, an IDE often provides specialized editors for editing user interfaces, icons, and other graphical components. It usually provides sophisticated project management utilities to help you organize your files. It is also common for an IDE to come with a profiler (a tool which aids in discovering inefficiencies in your program), and an interface to 3rd party version-control software.

If you still don't understand the advantages of an IDE, that's OK. You'll appreciate them more after you gain in programming experience. For now, just accept that IDEs are useful, and enjoy the rest of the lab!

Problem set 1

Exploring JBuilder

The best way to learn an IDE is by using it, so let's try building a small project in JBuilder. The course author has implemented xeyes in Java, and we will attempt to edit, compile, and run it from within JBuilder. Xeyes is a simple application that comes with many X-windows distrubtions. It draws a pair of eyes which follow your mouse pointer as it moves around the screen.

Let's get started. To get JBuilder running, click on the lower left icon on the screen) and select LOCAL. Look for the JBuilder entry and click on it. Then wait. We are training you in patience this semester.

Setting Up a Project

The first thing we're going to do is create a new project:

Now we need to add the files which contain the implementation of JavaEyes:

That's it!! You've now set up and configured your first Java project with JBuilder. Let's see what this project can do.

Compiling and Running a Project

First we must compile the project:

You shouldn't see any error messages. If you do, make sure that you did in fact complete all of the above steps in the correct order. If you still can't find the error, please ask the teacher for help.

When you run the program, a window with eyes should appear. Move your mouse around in the window and watch the eyes follow it. When you're done playing with JavaEyes, hit the "Quit" button to close the application.

Editing a Project

We'd also like to be able to use our IDE to modify Java programs. Let's trying making some changes to JavaEyes and see what happens.

Important! Even though juicy bits of code are displayed in your code editing window, it is not the focus of this exercise.  Do not feel compelled to read or understand it at this point. It is meant to be an example which can help familiarize you with the tools that we will be using in lab.

Notice how different bits of code are colored differently. This is meant to aid the programmer in visualizing the syntax of Java statements. You'll experiment with Java expressions and statements in next week's problem set.

If you've used other windows-based editors or word processors, a lot of the editing options available to you will be familiar. For instance, copying, cutting, and pasting are all available from the Edit menu. Search and replace options are availble from the Search menu. You can also go to a certain line number by selecting Search > Go To Line... and entering a number. (The current line number is displayed on the bar at the bottom of the window.)

Now we'd like you to make some modifications to the code. The purpose of this part of the project is just to get you comfortable using the tools, not to experiment with Java expressions and statements. That is what the next problem set is for.

Problem set 2

The first modification we'll make is to change the color of the JavaEyes application. In the Code Editing window, look for the line that says

private static final Color DEFAULT_BG_COLOR 
= Color.white;

(You should be using the Search > Find... command as a shortcut.) This line sets the background color of the JavaEyes application. Change that line so that the background color will be blue:

private static 
final Color DEFAULT_BG_COLOR = Color.blue;

Save the file by using the File > Save JavaEyes.java command (or, use <CTRL-s> as a shortcut). Now compile and run it as before. The background should now be blue. Cool, huh?

What if we tried to run the program without compiling it first? Well, JBuilder would be smart enough to compile it anyway, but if we managed to fool it into running without compiling, then none of the changes we made would take effect. This is because computers do not understand the Java language -- they need Java to be translated into machine language before they can process it. In other words, the changes we make at the Java level are completely ignored by the computer until we translate them into a language it can understand.

If you wish, also try changing the color of the eyes. The eyes are in the foreground, so their color is determined by the foreground color. This can be controlled by modifying the line:

private static final Color DEFAULT_FG_COLOR 
= Color.black;

Some of you may notice that not all of the colors that you're familiar with will work. Some will produce errors when you try to compile. (For instance, try setting the background color to "sepia". The program should not compile). To see why this is so, we need to examine the interface for the Color class. This can be found at http://java.sun.com/products/jdk/1.3/docs/api/java.awt.Color.html. Scroll down to the Field Summary section of the document. This enumerates the list of available fields in the Color class. You are only allowed to use the colors specified here -- Java simply doesn't know about any other ones. Of course, you can create brand new colors if you wish, but these ones are the only ones that are predefined for you. If you haven't successfully changed the foreground color yet, try using one of the colors specified in the interface.

Our next modification will be to customize the "quit" button. Find the line that says:

quitButton = new Button("Quit");

and replace Quit with a string of your own choosing. Save, compile and run the program to see what happens.

Problem set 3: Fixing Errors

Lastly, you're going to comment out a portion of the code, in order to see what kinds of compiling errors you can get. Commenting means to mark off an area in your code file that will be deliberately ignored by the compiler. In Java, you use the following scheme to comment your code:

 /* This is a comment. */ 
// This is also a comment. /* This * is * also * a comment. */ // This is not 
a comment (and will produce an error) 

Anything found within the delimiters /* and */ is considered a comment. This does not mean that you can "nest" comments! In other words, /* /* */ */ would not be a legal comment. The compiler would consider /* /* */ a comment, and it wouldn't know what to do with the final */.

Any text which comes after // on the same line is also considered a comment. Text which comes after // on a subsequent line is no longer considered commented (unless of course, it has been commented somewhere else). If you have further questions about comments, please ask the teacher.

Please go to the place in the code marked for commenting. (You'll see a line that says:

You will comment the subsequent line out during your lab:

You want the line below that one. It's pretty close to the beginning.) Insert two slash characters (//) to comment out the line. (You should not delete the line; you'll need it later.) Save the file again, compile it again, and see what happens.

It should not compile this time. Read the error messages you get. Try to see if they make any sense. Even if you are not sure of the meaning of this message, the compiler can give you some help in debugging it. Double-click on the error message that you got. The compiler takes you to the line on which you made the error (indicated by a little arrow in the left margin). Now take out the backslashes you inserted, and reassure yourself that the propram still compiles.

Note: when the Java compiler can not complete its work, as in this case, JavaEyes.class is the same one as that last time it successfully compiled. What that means is that if you try to run the JavaEyes program again, it'll run the last version (i.e. the one before you commented out that crucial line).

Now find the line that says:

ActionListener 
actionListener = new ActionListener() {

and comment it out. Save, and compile. Your error window should now display 4 errors! Take a look at them and see if you can understand them. Also try double-clicking on them to see where the compiler thinks you have made errors. It seems that these errors don't directly relate to the error we actually committed! This raises an important point: making one error can often "fool" the compiler into thinking that other (correct) parts of your program have errors. The Java compiler is basically stupid, so if it tells you that you committed a bunch of errors that you think you did not commit, chances are that you've made a simple error that has confused it.

Fix the code you just broke, and recompile to make sure everything still works.

Problem set 4: Command-line arguments

One way to provide information to a program is through the use of command-line arguments. Command-line arguments are used when you type in the command to run a program from a command prompt. The command-line arguments are those words which follow the command to run the program. For example, some of you might be familiar with the following command:

> ls -l

ls is the Unix command to list the contents of the current directory. -l is a command line argument to the program ls. It tells ls to use the "long" listing format. The benefit of this approach is that we can change the behavior of a program without recompiling it (while this might not seem like a big deal, we do not want to force users of a program to deal with the inconvenience of modifying source code, and recompiling it on their own).

We can pass arguments to Java programs in the same way. Lets try doing this with the help of JBuilder. JavaEyes knows how to process two command-line arguments, a foreground color and a background color. To add command-line arguments, use the following procedure:

Now compile and run the program.

Setting the color this way has a slightly different behavior than setting it by changing class variables. When using class variables, the compiler would complain if the color was not recognized. Using command-line arguments, if a color is not recognized, JavaEyes will set the color to the default (black). This means that if you set the command-line arguments, but you just get an entirely black screen, you may have input colors that were not recognized by JavaEyes.

It is important to realize this is not due to any intrinsic superiority of either scheme. Rather, it was an purely implementation decision on the part of the JavaEyes programmers.


 

Getting Help

One of the things I hope that you will take away from this class is that you will be a more productive (and happy!) programmer if you learn to work in groups. If you have a question, ask your classmates! I feel this helps both of you: it clears up your question, and reinforces another student's understanding of the material.

If for some unfortunate reason you have to go it alone, there are some computerized resources that may be useful to you. If you have questions about JBuilder, you can find an online manual under Help . If you have general questions about the Java language, the Java Tutorial at http://java.sun.com/docs/books/tutorial/ is a good place to go. The Java 1.3 API Reference at http://java.sun.com/products/jdk/1.3/docs/api/index.html is the official reference for the standard Java 1.3 libraries. You'll probably be getting very familiar with this website.


Epilogue

Many months later, the software consultant was again approached by the pilgrim. This time, however, the pilgrim looked vibrant and healthy, and was dressed in the finest of clothes.
"O wise one, I did as you suggested, and my productivity increased tenfold. I have received promotion after promotion, and am now a very wealthy man. My future as a software developer is at last secure."
The consultant smiled sadly, and for the first time, he spoke:
"Young one, did you remember to make your programs Y2K compliant?"


This course is an adaption for the Fachhochschule für Technik und Wirtschaft , Berlin by Prof. Dr. Debora Weber-Wulff of a part of Prof. Dr. Lynn Andrea Stein's Rethinking CS101 project produced while she was at the MIT AI Lab belonging to the Department of Electrical Engineering and Computer Science (EECS) at the Massachusetts Institute of Technology. The copyright for all materials belongs to Lynn Andrea Stein, this adaptation is used by permission. All rights reserved.
A textbook is in preparation by Morgan Kaufmann Publishers


Questions or comments: <weberwu@fhtw-berlin.de>