Introduction
Java syntax refers to the set of rules that define how a Java program should be written. Understanding these rules is essential for writing correct Java code. Think of syntax as the grammar of the Java language.
Basic Program Structure
Template of a Java Program:
// Comments
package packageName; // Optional
import java.util.*; // Optional
public class ClassName {
// Class body
// Main method
public static void main(String[] args) {
// Program statements
}
// Other methods and fields
}
1. Comments
Comments are notes in the code that are ignored by the compiler. They help explain code to humans.
Types of Comments:
a) Single-line Comment:
// This is a single-line comment
int age = 25; // Age of the person
b) Multi-line Comment:
/*
This is a multi-line comment
It can span multiple lines
Used for longer explanations
*/
int salary = 50000;
c) Documentation Comment (JavaDoc):
/**
* This method calculates sum
* @param a first number
* @param b second number
* @return sum of a and b
*/
public int add(int a, int b) {
return a + b;
}
Rules:
- Comments are ignored by compiler
- Don’t nest multi-line comments
- Use comments to make code clearer
2. Case Sensitivity
Java is case-sensitive, meaning uppercase and lowercase letters are different.
Examples:
int age = 25; // 'age' variable
int Age = 30; // 'Age' is different variable
int AGE = 35; // 'AGE' is another different variable
String name = "John"; // 'name'
String Name = "Jane"; // 'Name' is different
Important:
HelloWorld≠helloworld≠HELLOWORLD- Class names, variable names, method names are all case-sensitive
- Keywords must be lowercase:
public,class,int(notPublic,Class,Int)
3. Class Name
Rules:
- Must start with: Letter, underscore (_), or dollar sign ($)
- Cannot start with: Number
- Can contain: Letters, numbers, underscore, dollar sign
- Cannot be: Java keyword
- Should match: Filename (for public classes)
Naming Conventions:
- Start with uppercase letter
- Use PascalCase (capitalize first letter of each word)
- Be descriptive
Valid Examples:
public class Student { } // Good
public class EmployeeDetails { } // Good
public class _MyClass { } // Valid but not recommended
public class $Helper { } // Valid but not recommended
Invalid Examples:
public class 123Student { } // ❌ Starts with number
public class My-Class { } // ❌ Contains hyphen
public class My Class { } // ❌ Contains space
public class class { } // ❌ Java keyword
Filename Rule:
- If class is
public, filename must match class name exactly public class HelloWorldmust be inHelloWorld.java
4. Identifiers
Identifiers are names given to variables, methods, classes, etc.
Rules:
- Can contain: letters, digits, underscore (_), dollar sign ($)
- Must start with: letter, underscore, or dollar sign
- Cannot start with: digit
- Cannot be: Java keyword
- Case-sensitive
- No length limit
Valid Identifiers:
age
_name
$salary
firstName
rollNumber123
__temp
$price
Invalid Identifiers:
123name // ❌ Starts with digit
first-name // ❌ Contains hyphen
my name // ❌ Contains space
int // ❌ Java keyword
@value // ❌ Contains @
Naming Conventions:
Variables and Methods:
- Start with lowercase
- Use camelCase
int age;
String firstName;
void calculateSalary() { }
Classes:
- Start with uppercase
- Use PascalCase
class Student { }
class EmployeeDetails { }
Constants:
- All uppercase
- Words separated by underscores
final int MAX_VALUE = 100;
final double PI = 3.14159;
Packages:
- All lowercase
package com.company.project;
5. Keywords (Reserved Words)
Keywords are reserved words with predefined meanings. Cannot be used as identifiers.
List of Java Keywords:
| 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 |
| instanceof | int | interface | long | native |
| new | package | private | protected | public |
| return | short | static | strictfp | super |
| switch | synchronized | this | throw | throws |
| transient | try | void | volatile | while |
Special Keywords:
true,false,nullare literals (not keywords but reserved)constandgotoare reserved but not used
Examples:
int count = 10; // 'int' is keyword
public class Demo { } // 'public' and 'class' are keywords
if (x > 5) { } // 'if' is keyword
6. Statements and Blocks
Statement
A complete line of code that performs an action. Ends with semicolon.
int age = 25; // Statement
System.out.println("Hello"); // Statement
int sum = a + b; // Statement
Block
A group of statements enclosed in braces {}.
{
int x = 10; // Statement 1
int y = 20; // Statement 2
int sum = x + y; // Statement 3
} // This is a block
Rules:
- Every statement must end with semicolon (;)
- Blocks are enclosed in braces { }
- Blocks can be nested
7. Whitespace
Whitespace includes spaces, tabs, and newlines. Java ignores extra whitespace.
These are all equivalent:
// Version 1
int age = 25;
// Version 2
int age=25;
// Version 3
int age = 25 ;
// Version 4
int
age
=
25
;
Best Practice:
- Use whitespace for readability
- Follow consistent indentation
- One statement per line
8. Semicolons
Semicolon (;) marks the end of a statement.
Rules:
- Every statement must end with semicolon
- Missing semicolon causes compilation error
- Not needed after class/method declaration opening brace
Correct:
int x = 10;
int y = 20;
int sum = x + y;
Incorrect:
int x = 10 // ❌ Missing semicolon
int y = 20 // ❌ Missing semicolon
9. Braces { }
Braces define blocks of code.
Rules:
- Every opening brace
{must have closing brace} - Enclose class body
- Enclose method body
- Enclose control structures (if, for, while)
Example:
public class Demo { // Opening brace for class
public static void main(String[] args) { // Opening brace for method
if (x > 0) { // Opening brace for if
System.out.println("Positive");
} // Closing brace for if
} // Closing brace for method
} // Closing brace for class
Common Error:
public class Demo {
public static void main(String[] args) {
System.out.println("Hello");
}
// } ❌ Missing closing brace causes error
10. Data Types (Brief Overview)
Java has two categories of data types:
Primitive Types:
byte,short,int,long(integers)float,double(floating-point)char(character)boolean(true/false)
Reference Types:
- Classes
- Interfaces
- Arrays
- Strings
Examples:
int age = 25; // Primitive
String name = "John"; // Reference
boolean isStudent = true; // Primitive
11. Variables
Variables store data values.
Syntax:
type variableName = value;
Examples:
int age = 25;
String name = "Alice";
double salary = 50000.50;
boolean isActive = true;
12. Literals
Literals are fixed values written directly in code.
Types:
Integer Literals:
int decimal = 100; // Decimal
int octal = 0144; // Octal (starts with 0)
int hex = 0x64; // Hexadecimal (starts with 0x)
int binary = 0b1100100; // Binary (starts with 0b)
Floating-point Literals:
double d1 = 123.45;
double d2 = 1.23e2; // Scientific notation (123.0)
float f = 123.45f; // Must have 'f' or 'F' suffix
Character Literals:
char c1 = 'A';
char c2 = '9';
char c3 = '\n'; // Newline
String Literals:
String s1 = "Hello";
String s2 = "Java Programming";
Boolean Literals:
boolean b1 = true;
boolean b2 = false;
13. Operators (Brief)
Arithmetic Operators:
+ - * / %
int sum = 10 + 5; // 15
int diff = 10 - 5; // 5
int product = 10 * 5; // 50
int quotient = 10 / 5; // 2
int remainder = 10 % 3; // 1
Assignment Operators:
= += -= *= /= %=
int x = 10;
x += 5; // x = x + 5 = 15
Comparison Operators:
== != > < >= <=
boolean result = (10 > 5); // true
14. Access Modifiers
Control visibility of classes, methods, and variables.
Types:
public: Accessible from anywhereprivate: Accessible only within classprotected: Accessible within package and subclasses- default (no modifier): Accessible within package
Example:
public class Student {
public String name; // Accessible everywhere
private int age; // Only within Student class
protected double marks; // Within package and subclasses
String address; // Within package (default)
}
15. Method Syntax
Basic Structure:
accessModifier returnType methodName(parameters) {
// Method body
return value; // If returnType is not void
}
Example:
public int add(int a, int b) {
int sum = a + b;
return sum;
}
public void printMessage() {
System.out.println("Hello");
// No return statement needed for void
}
Common Syntax Errors and Solutions
Error 1: Missing Semicolon
int x = 10 // ❌ Error
int x = 10; // ✓ Correct
Error 2: Unmatched Braces
public class Demo {
public static void main(String[] args) {
System.out.println("Hello");
}
// Missing closing brace ❌
Error 3: Case Sensitivity
String name = "John";
System.out.println(Name); // ❌ Error: 'Name' not defined
System.out.println(name); // ✓ Correct
Error 4: Using Keywords as Identifiers
int class = 10; // ❌ Error: 'class' is keyword
int myClass = 10; // ✓ Correct
Error 5: Filename Mismatch
// File: HelloWorld.java
public class Hello { } // ❌ Error: class name doesn't match
public class HelloWorld { } // ✓ Correct
Best Practices
- Use meaningful names:
studentAgeinstead ofx - Follow naming conventions: Classes start uppercase, variables lowercase
- Add comments: Explain complex code
- Proper indentation: Makes code readable
- One statement per line: Don’t cram multiple statements
- Consistent style: Stick to one coding style
Exam Tips
Remember:
- Java is case-sensitive:
age≠Age - All statements end with semicolon:
; - Braces must match: Every
{needs} - Keywords are lowercase:
public,class,int - Public class name = filename:
HelloWorldclass inHelloWorld.java - Identifiers rules: Start with letter, _, or $
- Comments are ignored: Use // or /* */
- Main method signature: Must be exact
Common Exam Questions:
- Which are valid identifiers?
- Identify syntax errors in given code
- What is the difference between keywords and identifiers?
- Explain case sensitivity with examples
- Why do we need semicolons?
- What are the rules for naming a class?
- Differentiate between statements and blocks
Summary
Java syntax includes:
- Comments: //, /* _/, /** _/
- Case sensitivity: Uppercase ≠ lowercase
- Identifiers: Names for variables, methods, classes
- Keywords: Reserved words
- Statements: End with semicolon
- Blocks: Enclosed in braces
- Naming conventions: PascalCase for classes, camelCase for variables
- Access modifiers: public, private, protected, default
Mastering these basics is essential for writing correct Java programs!