- Back to Home »
- Java Syntax
In this text I will give you an overview of the basic syntax of a Java program, or a Java class (component, module, subpart of a Java program).
All Java code must reside inside a file with the extension
.java
. For instance, HelloWorld.java
or MyApp.java
etc. A Java application can consist of many such .java
files.
The basic syntax of a
.java
files is as follows:- Package declaration
- Import statements
- Type declaration
- Fields
- Static initializers
- Constructors
- Methods
A
.java
file can also contain comments and annotations, but I will cover these elsewhere.Basic Syntax
Below is an example
.java
file that contains all of the above elements, so you can see the basic syntax of a .java
file:package javacore; import java.util.HashMap; public class MyClass { protected final String hello = "value"; { //static initializer } public MyClass() { } public static void main(String[] args) { } }
The first line is the package declaration. The package declaration consists of the word
package
, a space, and then the name of the package the type is to be located in. The .java
file should be located in a directory structure that matches the package name. Packages and package declarations are covered in more detail in the text on Java packages.package javacore;
The second line is the import statements. This example only has a single import statement, but multiple import statements can be used, each on its own line.
import java.util.HashMap;
The third line is the type declaration. In Java a type is either a class, an interface or an enum. In this example it is a class. The type declaration is delimited by a
{
and a }
. As you can see, the beginning {
is listed on the same line as the type declaration. The finishing }
is on the last line of the example.public class MyClass {
The fourth line is a field declaration. The field declaration ends with a semicolon
;
. Fields are covered in more detail in the text on Java fields. A type (class / interface / enum) can have more than one field. This example just has one field:protected final String hello = "value";
The fifth line (or block) is a static initializer block. It begins with a
{
and ends with a }
. Inside this block you can put initialization code that is to be executed when the class is loaded. In this example the block is empty. The text inside the block is just a comment. The Java compiler ignores it.{ //static initializer }
The sixth block is a constructor. Constructors are covered in more detail in the text on Java constructors. A class can have more than one constructor, although this example just shows one.
public MyClass() { }
The seventh block is a static method. Methods are covered in more detail in the text on Java methods. Classes can contain more than one method, but this example just shows one.
public static void main(String[] args) { }
The final line in the example is the end of the type declaration, as mentioned earlier.
}