Back to Study Material Java

Java Syntax

Java syntax refers to the set of rules that govern how valid Java programs are written. Java inherits much of its syntax from C and C++, so developers comi...

Java Syntax

Rules and Structure of Java Source Code

Java syntax refers to the set of rules that govern how valid Java programs are written. Java inherits much of its syntax from C and C++, so developers coming from those languages find many familiar patterns. However, Java enforces stricter rules than C++ in several important areas, which helps prevent common programming mistakes.

Every Java program is organized into classes. A source file must have the same name as the public class it contains, with the .java extension. For example, a public class named Calculator must be saved in a file named Calculator.java. This naming convention is enforced by the compiler. A file may contain multiple classes, but only one can be declared public.

Java is case-sensitive. The identifiers System, system, and SYSTEM are three completely different names. Keywords like class, public, void, and static are all lowercase, and using the wrong case causes a compile error. Class names conventionally begin with an uppercase letter (UpperCamelCase), while variable and method names conventionally begin with a lowercase letter (lowerCamelCase). Constants are written in UPPER_SNAKE_CASE.

Statements in Java end with a semicolon. Blocks of code are enclosed in curly braces { }. Proper indentation is not required by the compiler but is essential for readable code. A minimal syntactically valid program looks like this: public class Example { public static void main(String[] args) { int x = 10; System.out.println(x); } }. This program declares a class, defines the main method, declares an integer variable, and prints its value.

Whitespace — spaces, tabs, and newlines — is largely ignored by the compiler except where it separates tokens. You can spread a long statement across multiple lines for readability. String literals, however, cannot span multiple lines in the traditional sense; for multiline text you use text blocks (introduced in Java 15) delimited by triple double-quotes.

Java supports three kinds of comments. Single-line comments begin with // and extend to the end of the line. Multi-line comments begin with /* and end with */. Documentation comments, used by the javadoc tool, begin with /** and end with */ and can include tags like @param and @return to document method signatures.

Interview tip: A common trick question asks whether a Java file can have more than one class. The answer is yes, but only one class can be declared public, and the filename must match that public class. Any additional classes in the file must be package-private (no access modifier).