Java Syntax
Java is an object-oriented programming language that is known for its simplicity, portability, and robustness. The syntax of Java programming language is very closely aligned with C and C++, which makes it easier to understand.
Java Syntax refers to a set of rules that defines how Java programs are written and interpreted by the compiler. These rules ensure that your code is readable, logically correct, and error-free. Now, let’s understand the Syntax and Structure of Java Programs with a basic “Hello World” program.
Structure of Java Program
A basic Java program consists of several components that create a functional application. We can learn about basic Java Syntax using the following program:
// FileName : "Geeks.java".
public class Geeks {
// Program begins with a call to main() method
// main method is the entry point of a Java Program
public static void main(String args[])
{
// Prints "Hello World" to the console
System.out.println("Hello World");
}
}
Output
Hello World
Explanation: The above program shows the basic Java program that contains Class declaration, Main Method, Statements, etc. Let’s try to understand them one by one.
Note: In the above code, although we did not explicitly import any package, the java.lang package is automatically imported by default in every Java program. This package contains essential classes like System, Math, and String, which is why we can use System.out.println(“Hello World”); without any additional imports.
Terminologies of a Basic Java Program
1. Class Declaration: Every Java program starts with a class declaration using the class keyword. “A class is a blueprint of an object” and we can also define class as a logical template that shares common properties and methods.
2. Object: The object is an instance of a class. It is an entity that has behavior and state.
- Example: Dog, Cat, Monkey etc. are the object of the “Animal” class.
- BehaviourJava: Running on the road.
3. Main Method: The public static void main(String args[]) method is the entry point where the program starts execution.
4. Statements: Each line of code inside the method must end with a semicolon(;)
Steps to Compile and Run a Java Program in a Console
1. Run the javac command to compile the Java Program
javac Geeks.java
The Java compiler(javac) reads the source code(Geeks.java) and generates a bytecode file(Geeks.class) in the same directory
2. Use the java command to execute the compiled bytecode
java Geeks
Note:
- Do include the .class extension in the command.
- Make sure the Geeks.class file is in the current directory.
Java Syntax Key Elements
1. Comments in Java
There are three types of comments in Java.
- Single line Comment
// This is a single-line comment
- Multi-line Comment
/* This is
a multi-line comment */
- Documentation Comment
It is also known as a doc comment
/** This is a doc comment */
2. Source File Name
Source File Name Rule in Java
1. When There is a public class in the file
The name of a source file must exactly match the name of the public class name with the extension. java
Example: Assume you have a public class named GFG.
import java.io.*;
public class GFG {
public static void main (String[] args) {
System.out.println("Hello World!");
}
}
Note:
- GFG. java is a Valid Syntax
- gfg.java is a Invalid Syntax
2. When There is no public class in the file
The source file name can be anything, but it must have the .java extension.
class Program {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Here, the class is not declared as public so you can make the file name anything like Example.java, Program.java etc
3. Case Sensitivity
Java is a case-sensitive language, which means that the identifiers AB, Ab, aB , and ab are different in Java.
System.out.println(“Hello World”); // valid syntax
system.out.println(“Hello World”); // invalid syntax because of the first letter of System keyword is always uppercase.
4. Class Names
- The first letter of the class should be in Uppercase (lowercase is allowed but discouraged).
- If several words are used to form the name of the class, each inner word’s first letter should be in Uppercase. Underscores are allowed, but not recommended. Also allowed are numbers and currency symbols, although the latter are also discouraged because they are used for a special purpose (for inner and anonymous classes).
class MyJavaProgram // valid syntax
class 1Program // invalid syntax
class My1Program // valid syntax
class $Program // valid syntax, but discouraged
class My$Program // valid syntax, but discouraged (inner class Program inside the class My)
class myJavaProgram // valid syntax, but discouraged
6. Method Names
- All the method names should start with a lowercase letter (uppercase is also allowed but lowercase is recommended).
- If several words are used to form the name of the method, then each first letter of the inner word should be in Uppercase. Underscores are allowed, but not recommended. Also allowed are digits and currency symbols.
public void employeeRecords() // valid syntax
public void EmployeeRecords() // valid syntax, but discouraged
7. Identifiers in Java
- Identifiers are the names of local variables, instance and class variables, and labels, but also the names for classes, packages, modules and methods. All Unicode characters are valid, not just the ASCII subset.
- All identifiers can begin with a letter, a currency symbol or an underscore ( _ ). According to the convention, a letter should be lowercase for variables.
- The first character of identifiers can be followed by any combination of letters, digits, currency symbols and the underscore. The underscore is not recommended for the names of variables. Constants (static final attributes and enums) should be in all Uppercase letters.
- Most importantly identifiers are case-sensitive.
A keyword cannot be used as an identifier since it is a reserved word and has some special meaning.
Legal identifiers: MinNumber, total, ak74, hello_world, $amount, _under_value
Illegal identifiers: 74ak, -amount
8. White spaces in Java
A line containing only white spaces, possibly with the comment, is known as a blank line, and the Java compiler ignores it.
9. Access Modifiers
These modifiers control the scope of class and methods.
- Access Modifiers: default, public, protected, private.
- Non-access Modifiers: final, abstract, static, transient, synchronized, volatile, native.
Access Modifier | Within Class | Within Package | Outside Package by subclass only | Outside Package |
Private | Yes | No | No | No |
Default | Yes | Yes | No | No |
Protected | Yes | Yes | Yes | No |
Public | Yes | Yes | Yes | Yes |
10. Java Keywords
Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to be used as variable names or objects.
abstract | assert | boolean | break |
byte | case | catch | char |
class | const | continue | default |
do | double | else | enum |
extends | final | finally | float |
for | goto | if | implements |
import | instance of | int | interface |
long | native | new | package |
private | protected | public | return |
short | static | strictfp | super |
switch | synchronized | this | throw |
throws | transient | try | void |
volatile | while |