Java Syntax


Before writing complex programs in Java, it’s important to understand its basic syntax. The syntax defines how Java code is written and structured so that the compiler can interpret it correctly. If you’ve worked with C or C++ before, Java’s syntax will feel familiar. But even for beginners, Java is designed to be simple, readable, and organized.

In this tutorial, we’ll walk through the structure of a Java program, rules for naming and writing code, and the role of statements, variables, and data types.

Structure of a Java Program

Every Java program follows a particular structure. Let’s look at the basic format using a simple example:

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, Java Syntax!");
    }
}

Let’s break this down step by step:

  1. class HelloWorld – Every Java program must have at least one class. The class name should match the filename. For example, if your class is HelloWorld, the file name must be HelloWorld.java.

  2. public static void main(String[] args) – This is the entry point of the program. The main method is where the execution starts.

    • public means it can be accessed from anywhere.

    • static allows the method to run without creating an object.

    • void means it does not return any value.

    • String[] args accepts command-line arguments.

  3. System.out.println("Hello, Java Syntax!"); – This line prints output on the screen.

  4. Curly braces { } – Define the beginning and end of blocks, such as a class or method.

  5. Semicolon ; – Every statement must end with a semicolon.

Java Case Sensitivity

Java is a case-sensitive language, which means uppercase and lowercase letters are treated differently.

For example:

System.out.println("Hello");
system.out.println("World");

The first line works fine, but the second will cause an error because System should always start with a capital ‘S’.

Java Comments

Comments are ignored by the compiler but help you describe what the code does. They improve readability, especially in large projects. Java supports three types of comments:

  1. Single-line comment

    // This is a single-line comment
    
  2. Multi-line comment

    /* This is a
       multi-line comment */
    
  3. Documentation comment

    /** This comment is used
        for generating documentation */
    

Java Identifiers

Identifiers are the names you use for classes, variables, methods, and other elements. There are specific rules for naming them:

  • Must start with a letter, underscore (_), or dollar sign ($).

  • Cannot start with a number.

  • Cannot use Java reserved keywords like class, int, public, etc.

  • Names are case-sensitive.

  • Should be meaningful and follow camelCase for variables and methods.

Examples of valid identifiers:

studentName, totalMarks, _result, $price

Invalid identifiers:

2value, total-marks, class

Java Keywords

Java has a set of reserved keywords that have predefined meanings and cannot be used as identifiers.
Examples include:

class, public, static, void, if, else, while, for, return, int, double, new, try, catch, extends, this, and many more.

These keywords form the core grammar of the Java language.

Java Variables

Variables store data that can be used and changed during program execution. Each variable in Java must be declared with a specific data type.

Syntax:

dataType variableName = value;

Example:

int age = 22;
String name = "Priya";

Rules for variables:

  • Must be declared before use.

  • Must have a valid identifier.

  • The value can be changed later if not declared as final.

Java Data Types

Java is a statically typed language, meaning every variable’s type must be known at compile time. Data types define what kind of data a variable can store.

1. Primitive Data Types

These are built-in and directly supported by Java.

Type Size Example
byte 1 byte byte num = 10;
short 2 bytes short val = 200;
int 4 bytes int count = 5000;
long 8 bytes long bigNum = 100000L;
float 4 bytes float rate = 5.5f;
double 8 bytes double price = 99.99;
char 2 bytes char grade = 'A';
boolean 1 bit boolean isActive = true;

2. Non-Primitive Data Types

These are objects and include:

  • Strings

  • Arrays

  • Classes

  • Interfaces

Example:

String city = "Delhi";

Java Statements and Blocks

A statement is a single line of code that performs a specific task, such as declaring a variable or printing output. Each statement ends with a semicolon.

Example:

int x = 10;
System.out.println(x);

A block is a group of statements enclosed within curly braces { }.
Blocks are used in loops, methods, and classes.

Example:

{
   int a = 5;
   int b = 10;
   System.out.println(a + b);
}

Java Whitespace and Indentation

Java ignores extra spaces, tabs, and newlines, but proper indentation makes your code easier to read.
Example:

System.out.println("Hello");   // readable

vs

System.out.println("Hello");

Both work, but the first is cleaner when code is longer.

Java Naming Conventions

Following naming conventions makes your code consistent and professional.

Element Convention Example
Class PascalCase StudentDetails
Method camelCase calculateMarks()
Variable camelCase totalAmount
Constant UPPER_CASE MAX_SPEED

Example Program: Variables and Data Types

class StudentInfo {
    public static void main(String[] args) {
        String name = "Aarohi";
        int age = 20;
        double marks = 85.6;
        boolean passed = true;

        System.out.println("Student Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Marks: " + marks);
        System.out.println("Passed: " + passed);
    }
}

Output:

Student Name: Aarohi
Age: 20
Marks: 85.6
Passed: true

This program shows how variables, data types, and syntax rules come together in a simple Java code.

Summary of the Tutorial

In this chapter, you learned the basic structure of a Java program, how to declare variables, use data types, and follow syntax rules. Understanding syntax is the first step to writing clean and error-free Java programs. Every symbol, keyword, and convention plays a role in making your code understandable for both the compiler and other developers.

In the next tutorial, we’ll explore Java Output, where you’ll learn different ways to display information on the screen using print() and println() methods.


Practice Questions

  1. What is the basic structure of a Java program?

  2. Why must the class name and filename match in Java?

  3. What is the purpose of the main() method in a Java program?

  4. Why is Java considered a case-sensitive language?

  5. What are the different types of comments supported in Java?

  6. What are identifiers in Java, and what rules should be followed while naming them?

  7. What are Java keywords, and why can’t they be used as identifiers?

  8. What is the difference between primitive and non-primitive data types in Java?

  9. What is the importance of semicolons and curly braces in Java syntax?

  10. What naming conventions should be followed for classes, variables, and methods in Java?


Try a Short Quiz.

Java Syntax Quiz

Just finished the tutorial? Try this medium level quiz to lock in the basics.


Go Back Top