Wednesday, December 10, 2008

Command-Line

Using Java's Command-Line Tools

Java comes with several command-line tools you can run directly from a command prompt. The two most important are javac, the Java compiler used to compile a program, and java, the runtime command used to run a Java program. These tools work essentially the same no matter what operating system you're using. (The examples in this section are all for Windows XP and Windows Vista.)

Compiling a program

You can compile a program from a command prompt by using the javac command. Before you can do that, however, you need a program to compile. Using any text editor, type the following text into a file and save it as HelloApp.java:

public class HelloApp
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}

Save the file in any directory you wish. Pay special attention to capitalization. For example, if you type Public instead of public, the program won't work. (If you don't want to bother with the typing, you can download the sample programs from this book's Web site.)

Open a command prompt and use a cd command to change to the directory you saved the program file in. Then enter the command javac HelloApp. java. This command compiles the program (javac) and creates a class file named HelloApp.class.

Assuming you typed the program exactly right, the javac command doesn't display any messages at all. If the program contains any errors, one or more error messages appear on-screen. For example, if you type Public instead of public, the compiler displays the following error message:

C:\java\samples>javac HelloApp.java
HelloApp.java:1: 'class' or 'interface' expected
Public class HelloApp
^
1 error

C:\java\samples>

The compiler error message indicates that an error is in line 1 of the HelloApp.java file. If the compiler reports an error message like this one, that means your program contains a coding mistake. You need to find the mistake, correct it, and then compile the program again.

Compiling more than one file

Normally the javac command compiles only the file that you specify on the command line. However, you can coax javac into compiling more than one file at a time by using any of the techniques I describe in the following paragraphs:

  • If the Java file you specify on the command line contains a reference to another Java class that's defined by a java file in the same folder, the Java compiler automatically compiles that class too.

    For example, suppose you have a java program named TestProgram, and that program refers to a class called TestClass, and the TestClass.java file is located in the same folder as the TestProgram.java file. Then, when you use the javac command to compile the TestProgram.java file, the compiler automatically compiles the TestClass.java file, too.

  • You can list more than one filename on the javac command. For example, the following command compiles three files:

         javac TestProgram1.java TestProgram2.java
    TestProgram3.java
  • You can use a wildcard to compile all the files in a folder, like this:

         javac *.java

  • If you need to compile a lot of files at once, but don't want to use a wild-card (perhaps you want to compile a large number of files, but not all the files in a folder), you can create an argument file that lists the files to compile. In the argument file, you can type as many filenames as you want. You can use spaces or line breaks to separate the files. For example, here's an argument file named TestPrograms that lists three files to compile:

         TestProgram1.java
    TestProgram2.java
    TestProgram3.java

    Then you can compile all the programs in this file by using an @ character followed by the name of the argument file on the javac command line, like this:

         javac @TestPrograms

Using Java compiler options

The javac command has a gaggle of options you can use to influence the way it compiles your programs. For your reference, I list these options in Table 2-3. To use one or more of these options, type the option either before or after the source filename. For example, either of the following commands compiles the HelloApp.java file with the -verbose and -deprecation options enabled:

     javac HelloWorld.java -verbose -deprecation
javac -verbose -deprecation HelloWorld.java
Table 2-3: Java Compiler Options
Open table as spreadsheet

Folder

Description

-g

Generate all debugging info

-g:none

Generate no debugging info

-g:{lines, vars, source}

Generate only some debugging info

-nowarn

Generate no warnings

-verbose

Output messages about what the compiler is doing

-deprecation

Output source locations where deprecated APIs are used

-classpath

Specify where to find user class files

-cp

Specify where to find user class files

-sourcepath

Specify where to find input source files

-bootclasspath

Override location of bootstrap class files

-extdirs

Override location of installed extensions

-endorseddirs

Override location of endorsed standards path

-d

Specify where to place generated class files

-encoding

Specify character encoding used by source files

-source

Provide source compatibility with specified release

-target

Generate class files for specific VM version

-version

Version information

-help

Print a synopsis of standard options

-X

Print a synopsis of nonstandard options

-J

Pass directly to the runtime system

Don't get all discombobulated if you don't understand what all these options do. Most of them are useful only in unusual situations. The options you'll use the most are

  • -classpath or -cp: Use this option if your program makes use of class files that you've stored in a separate folder.

  • -deprecation: Use this option if you want the compiler to warn you whenever you use API methods that have been deprecated. (Deprecated methods are older methods that were once a part of the Java standard API but are now on the road to obsolescence. They still work, but may not in future versions of Java.)

  • -source: Use this option to limit the compiler to previous versions of Java. Note, however, that this option only applies to features of the Java language itself, not to the API class libraries. For example, if you specify -source 1.4, the compiler won't allow you to use new Java language features that were introduced with Java 1.5, such as generics or enhanced for loops. However, you can still use the new API features that were added with version 1.5, such as the Scanner class.

  • -help: Use this option to list the options that are available for the javac command.

Running a Java program

When you successfully compile a Java program, you can then run the program by typing the java command followed by the name of the class that contains the program's main method. The Java Runtime Environment loads, along with the class you specify, and then runs the main method in that class. For example, to run the HelloApp program, type this command:

C:\java\samples>java HelloApp

The program responds by displaying the message “Hello, World!”.

The class must be contained in a file with the same name as the class, and its filename must have the extension .class. You don't usually have to worry about the name of the class file because it's created automatically when you compile the program with the javac command. Thus, if you compile a program in a file named HelloApp.java, the compiler creates a class named HelloApp and saves it in a file named HelloApp.class.

If Java can't find a filename that corresponds to the class, you get a simple error message that indicates the class can't be found. For example, here's what you get if you type JelloApp instead of HelloApp:

C:\java\samples>java JelloApp
Exception in thread "main" java.lang.NoClassDefFoundError:
JelloApp

This error message simply means that Java couldn't find a class named JelloApp.

However, if you get the class name right but capitalize it incorrectly, you get a slew of error messages. Ponder this example:

C:\java\samples>java helloapp
Exception in thread "main" java.lang. NoClassDefFoundError:
helloapp (wrong name: HelloApp)
at java.lang.ClassLoader.defineClass1(Native Method)
at
java.lang.ClassLoader.defineClass(ClassLoader.java:620)
at java.security.SecureClassLoader.defineClass
(SecureClassLoader.java:124)
at java.net.URLClassLoader.defineClass
(URLClassLoader.java:260)
at java.net.URLClassLoader.access$100
(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run
(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged
(Native Method)
at java.net.URLClassLoader.findClass
(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass
(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass
(Launcher.java:268)
at java.lang.ClassLoader.loadClass
(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal
(ClassLoader.java:319)

Wow, that's a pretty serious-looking set of error messages-considering that the only problem is that I forgot to capitalize HelloApp. Java isn't just case-sensitive, it's case-hypersensitive.

Like the Java compiler, the Java runtime command lets you specify options that can influence its behavior. Table 2-4 lists the most commonly used options.

Table 2-4: Commonly Used Java Command Options
Open table as spreadsheet

Folder

Description

-client

Runs the client VM

-server

Runs the server VM, which is optimized for server systems

-classpath adirectories

A list of directories or JAR or Zip archive and archives files used to search for class files

-cp

Same as -classpath

-D name=value

Sets a system property

-verbose

Enables verbose output

-version

Displays the JRE version number, then stops

-showversion

Displays the JRE version number, then continues

-? or -help

Lists the standard options

-X

Lists nonstandard options

-ea or -enableassertions

Enables the assert command

-ea classes or packages

Enables assertions for the specified classes or packages

-esa or -enablesystemassertions

Enables system assertions

-dsa or -disablesystemassertions

Disables system assertions

Using the javap command

The javap command is called the Java disassembler because it takes apart class files and tells you what's inside them. It's not a command you'll use often, but using it to find out how a particular Java statement works is sometimes fun. You can also use it to find out what methods are available for a class if you don't have the source code that was used to create the class.

For example, here's the information you get when you run the javap HelloApp command:

     C:\java\samples>javap HelloApp
Compiled from "HelloApp.java"
public class HelloApp extends java.lang.Object{
public HelloApp();
public static void main(java.lang.String[]);
}

As you can see, the javap command indicates that the HelloApp class was compiled from the HelloApp.java file and that it consists of a HelloApp public class and a main public method.


TECHNICAL STAUFF

You may want to use two options with the javap command. If you use the -c option, the javap command displays the actual Java bytecodes created by the compiler for the class. And if you use the -verbose option, the bytecodes plus a ton of other fascinating information about the innards of the class are displayed. For example, here's the -c output for the HelloApp class:

C:\java\samples>javap HelloApp -c
Compiled from "HelloApp.java"
public class HelloApp extends java.lang.Object{
public HelloApp();
Code:
0: aload_0
1: invokespecial #1; //Method
java/lang/Object."":()V
4: return

public static void main(java.lang.String[]);
Code:
0: getstatic #2; //Field
java/lang/System.out:Ljava/io/PrintStream;
3: ldc #3; //String Hello, World!
5: invokevirtual #4; //Method
java/io/PrintStream.println:(Ljava/lang/String;)V
8: return

}

If you become a big-time Java guru, you can use this type of information to find out exactly how certain Java features work. Until then, you should probably leave the javap command alone, except for those rare occasions when you want to impress your friends with your in-depth knowledge of Java. (Just hope that when you do, they don't ask you what the aload or invokevirtual instruction does.)

Other Java command-line tools

Java has many other command-line tools that might come in handy from time to time. You can find a complete list of command-line tools at the following Web site:

java.sun.com/javase/6/docs/technotes/tools/index.html#basic

I describe three of these additional tools elsewhere in this book:

  • applet viewer: Runs a Web applet application. For more information, see Book VII, Chapter 1.

  • javadoc: Automatically creates HTML documentation for your Java classes. For more information, see Book III, Chapter 8.

  • jar: Creates Java archive files, which store classes in a compressed file that's similar to a Zip file. I cover this command in Book III, Chapter 8.

No comments:

Post a Comment