HelloWorld is usually the first Java program a novice writes. It is a
trivial program that just displays the string "Hello World". This is
not very impressive, but getting it to work proves you have your classpath,
compiler and runtime all correctly installed and that you understand the basics
of compling and running. This is a surprisingly difficult task. So break out
the champagne when your little HelloWorld works.
public class HelloWorld
{
public static void main ( String [] args )
{
System.out.println( "Hello World" );
}
}
From the directory where HelloWorld.java lives, to compile it, type:
javac.exe -classpath . HelloWorld.java
and later run it with:
java.exe -classpath . HelloWorld
If this does not work, here are some likely problem areas:
-
The name of the source file must be HelloWorld.java, precisely,
and the name of the public class in your source must be HelloWorld,
precisely, including case. If you use notepad, you may have inadvertently
named your file hellowworld.txt or helloworld.java.txt.
-
You specify the .java extension to compile, but leave the .class extension off
to execute. How logical!
-
You may not specify the fully qualified drive and path: e.g.
java.exe -classpath . C:\TEMP\HelloWorld
is not permitted.
-
As a corollary, make sure the current directory is where the HelloWorld.class
file is.
-
You have to get the case exactly correct. e.g.
java.exe -classpath . Helloworld
is not permitted.
-
If your HelloWorld is an Applet rather than an application, you need some HTML
commands to invoke it. You don't just load it in your browser as if it were a
web page.
Applet for more details on composing that HTML
-
Did you remember to make your class public?
-
Did you remember to make your main method public and static? It must have a
signature exactly like this:
public static void main ( String [] args )
-
If you used the abbreviation javac instead of the
fully qualified name such as javac.exe, check
that the javac.exe you wanted is on the
classpath and is the only javac.* on the
classpath.
If you have a more complex program, using a package, the name of the class you
put on the java command line would be com.mindprod.mypackage.MyClass.
MyClass.class needs to live in a directory called C:\com\mindprod\mypackage.
The current directory needs to be C:\ for Java to be
able to find the class. The full truth is a little more complex, e.g. you can
have zip and JAR files too.