Introduction to Java

To get started, start up DrJava (there's an icon on your desktop).

A first Java program

Look at the program Hello.java. In DrJava, type in this program exactly. You might find it easiest to put the two windows side-by-side on your computer screen, or perhaps you might wish to print out Hello.java first and work from the printout. Don't copy and paste the code. You'll learn more if you go through the experience of typing it in and fixing any errors. Save your file under the name Hello.java, in the directory C:\STI. Whatever you do, don't save it in "My Documents", or it will get erased when you log off the machine. Feel free to use a USB drive instead if you have one.

Before we can run your program, we need to compile it (translate it to a language the computer can understand). Click the "Compile" button in DrJava's button bar. Hopefully, the program should compile without returning any error messages. If you do get errors, holler for help.

Once you've compiled the program successfully, click the "Run" button.

EXERCISE 1: Modify the program so that it prints out "Welcome to AP Computer Science, [your name]."

Java input

This time, look at Input.java. This time, copy and paste the code into DrJava (or type it in if you like), and save the file. Compile the program and run it a couple of times. (Again, get help if you have any error messages.)

EXERCISE 2: You may notice that we sometimes use System.out.print() and sometimes System.out.println(). What's the difference between the two? Play around with both of these in your program (try modifiying it in various ways and rerunning) to see if you can figure it out.

EXERCISE 3: What happens if you enter a number when prompted for your name and a name when prompted for a number? If you get a message, what did the message say? What do you think it means?

EXERCISE 4: Modify the program so that it asks for the current year, and the year you were born. Your program should then print out the difference between the two, which is (approximately) your age. Make sure to put parentheses around your subtraction, like in the example shown.


Authored by Dave Musicant and Amy Csizmar Dalal.