Using Java from the Terminal in Mac OS X


This document instructs you on how to use Java from the Terminal in Mac OS X. The Terminal is necessary for redirecting standard input, redirecting standard output, and piping—you will use these features in Section 1.5.

These instructions apply to Mac OS X 10.4.11 and higher.


Install the Programming Environment


You will use the Java compiler javac to compile a Java program and the Java interpreter java to execute it.


Command-Line Interface


You will type commands in an application called the Terminal.


Compile the Program


You will use the javac command to convert your Java program into a form more amenable for execution on a computer.


Execute the Program


You will use the java command to execute your program.


Troubleshooting


Here are a few suggestions that might help correct any installation woes you are experiencing. If you need assistance, don't hesitate to contact a staff member.

I deleted the desktop shortcut to Terminal. Where can I find it?

I successfully compiled HelloWorld.java with javac, but, when I execute, I get the error message "Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld". What am I doing wrong? First, verify that the file HelloWorld.class is in the current directory. Be sure to type java HelloWorld without a trailing .class or .java.

When I compile or execute a program from the Terminal that uses StdIn, I get the error .... How can I fix this? First, verify that the installer installed the standard libraries to /Users/username/introcs/stdlib.jar. If so, it is likely an issue with the CLASSPATH environment variable. From the Terminal, type the following command to display it:

machine:~/introcs username$ echo $CLASSPATH
The CLASSPATH environment variable should include /Users/username/introcs/stdlib.jar.

How do I break out of an infinite loop in the Terminal? Type Ctrl-c.

When using standard input, how do I signify that there is no more data? If you are entering input from the keyboard, type Ctrl-d for EOF (end of file).

Can I use csh or tcsh instead of bash? Yes.