Create your first Java program

Let's start by compiling and running the following short sample program.


/* 
 This is a simple Java program. Call this file "Example.java". 
 */

public class Example {
  // Your program begins with a call to main().
  public static void main(String args[]) {
    System.out.println("Java.");
  }
}

In Java, a source file is called a compilation unit. It is a text file that contains one or more class definitions. The Java compiler requires that a source file use the .java filename extension.

In Java, all code must reside inside a class. By convention, the name of the public class should match the its file name. And Java is case-sensitive.

Compiling the Program

To compile the program, execute the compiler, javac, specifying the name of the source file on the command line:


C:\>javac Example.java 

The javac compiler creates a file called Example.class. Example.class contains the bytecode version of the program.

To run the program, use the Java interpreter, called java. Pass the class name Example as a command-line argument, as shown here:


C:\>java Example 

When the program is run, the following output is displayed:


Java. 

When Java source code is compiled, each individual class is put into its own file named classname.class.

java2s.com  |  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.