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
.
A Closer Look at the Example.java
Here is the code we just created.
/*
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.");
}
}
The first part is a comment.
/*
This is a simple Java program. Call this file "Example.java".
*/
Comment is a remark for a program. The contents of a comment are ignored by the compiler. The next line of code in the program is shown here:
public class Example {
The keyword class
declares that a new class is being defined.
Example
is the name of the class.
The entire class definition is between the opening curly brace ({) and the closing curly brace (}). The next line in the program is the single-line comment, shown here:
// Your program begins with a call to main().
A single-line comment begins with a //
and ends at the end of the line.
The next line of code is shown here:
public static void main(String args[]) {
Java applications begin execution by calling main(String args[])
.
Java is case-sensitive. Thus, Main
is different from main
.
Java Book
Language Basics
- Create your first Java program
- A Short Program with a variable