In this tutorial, we'll go over the basics of Java syntax. Java syntax refers to the set of rules and conventions for writing programs in Java.
Java is case-sensitive, which means that Hello
and hello
are different identifiers.
For all class names, the first letter should be in Upper Camel Case. If several words are used to form the name of the class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.
Example: public void myMethodName()
The name of the program file should exactly match the class name. When saving the file, you should save it using the class name (Remember Java is case-sensitive) and append .java
to the end of the name (if the file is saved with a .java
extension).
Example: Assume 'HelloWorld' is the class name. Then the file should be saved as HelloWorld.java
.
Every Java application must contain a main
method whose signature is:
java1public static void main(String[] args)
This method is the entry point for the program and will subsequently invoke all the other methods required by your program.
Java supports single-line and multi-line comments very similar to C and C++. Comments in Java are ignored by the compiler and can be used to provide information or explanation about the variable, method, class, or any statement.
Example:
java1// This is a single-line comment 2 3/* 4This is a multi-line comment 5that spans over multiple 6lines 7*/
All Java components require names. Names used for classes, variables, and methods are called identifiers.
identifier
and Identifier
would have different meaning in Java.Java provides a number of access modifiers to set access levels for classes, variables, and methods. The four access levels are:
Java also has a number of non-access modifiers, such as static
, abstract
, synchronized
, native
, volatile
, and transient
.
Java programming language supports the following types of variables:
static
modifier within a class, but outside any method.In Java, arrays are objects that store multiple variables of the same type. However, the size of an array must be decided upon instantiation.
Example:
java1int[] myIntArray = new int[10]; // Declares an array of integers. 2myIntArray[0] = 100; // Accesses the first element of the array and sets it to 100.
Enums were introduced in Java 5. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums.
Example:
java1enum Color { 2 RED, GREEN, BLUE; 3} 4 5Color myVar = Color.RED; // myVar can only be one of RED, GREEN, or BLUE.
_
).