Simple Java Program
A volunteer has recorded a new club member’s age as 6. The program starts, reads that stored value and prints it once so the volunteer can check the entry.
Save the following example as SampleProgram.java.
When a top-level class is public, its name must match the source file name.
class SampleProgram {
public static void main(String[] args) {
// Declare and Initialize an integer variable 'age' with value 6
int age = 6;
// Print the local variable 'age' in the console window
System.out.println(age);
}
}
A source file can contain several top-level classes. This example uses a single class named SampleProgram.
Identifiers name classes, methods, variables, and other program elements. The following identifiers appear in the example.
- SampleProgram - Name of the class
- main names the entry method.
- args - Parameter of a main method
- String names a standard library class.
- age names the local variable.
Java reserves keywords for specific language constructs. The following keywords appear in this program.
- class - Specifies the Class
- public - Specifies the access modifier
- static - Specifies the state of the method
- void - Specifies the return type of a method
- int names the integer type.
The example uses the conventional public static void main(String[] args) entry point. The launcher passes command-line arguments in args.
Several classes can each have a main method. The java command selects the class to launch.
The main function contains a declaration and a call to fmt.Println.
- int age = 6; declares an integer and assigns the value 6.
- System.out.println(age); prints the value of age.
Declarations and expression statements such as method calls end with a semicolon.
Braces group statements into a block and delimit the scope of local declarations.
- The braces delimit the class body.
- The braces delimit the method body.