Getting Started

Java Basic Syntax

Understand the fundamental syntax rules of Java — classes, methods, statements, comments, and naming conventions.

Java Program Structure

Every Java program follows a specific structure. Let's look at the anatomy of a basic Java program:

java
// This is a single-line comment

/*
 * This is a multi-line comment
 * It can span multiple lines
 */

package com.bigxstar.tutorial; // Package declaration (optional)

import java.util.Scanner;      // Import statement (as needed)

public class MyProgram {       // Class declaration

    public static void main(String[] args) {  // Main method
        System.out.println("Welcome to Java!"); // Statement
    }
}

Key Syntax Rules

1. Case Sensitivity

Java is case-sensitive. myVariable, MyVariable, and MYVARIABLE are all different identifiers.

java
int age = 25;       // valid
int Age = 30;       // different variable
int AGE = 35;       // yet another different variable

2. Class Name

  • Every Java program must have at least one class
  • The class name must match the filename (for public classes)
  • Class names should be in PascalCase (e.g., MyFirstProgram)
java
// File: MyFirstProgram.java
public class MyFirstProgram {
    // ...
}

3. Main Method

The main method is the entry point of every Java application. The JVM looks for this exact signature:

java
public static void main(String[] args) {
    // Your code starts here
}
KeywordMeaning
publicAccessible from anywhere
staticCan be called without creating an object
voidReturns nothing
mainMethod name (JVM looks for this)
String[] argsCommand-line arguments

4. Statements and Semicolons

Every statement in Java must end with a semicolon ;

java
System.out.println("Hello");   // ✓ Correct
int x = 10;                     // ✓ Correct
// System.out.println("Hello")  // ✗ Missing semicolon — compile error

5. Blocks and Braces

Code blocks are enclosed in curly braces { }:

java
public class Example {                    // Class block
    public static void main(String[] args) { // Method block
        if (true) {                        // If block
            System.out.println("Inside block");
        }
    }
}

Comments in Java

Comments are ignored by the compiler and are used to document your code.

Single-Line Comment

java
// This is a single-line comment
int age = 25; // You can also add comments at end of a line

Multi-Line Comment

java
/*
 * This is a multi-line comment.
 * Use it for longer explanations.
 */

Javadoc Comment

Used to generate API documentation:

java
/**
 * This method calculates the sum of two numbers.
 * @param a First number
 * @param b Second number
 * @return The sum of a and b
 */
public int add(int a, int b) {
    return a + b;
}

Java Keywords

Java has 67 reserved keywords that cannot be used as identifiers. Some common ones:

CategoryKeywords
Data Typesint, float, double, char, boolean, long, short, byte
Control Flowif, else, switch, case, for, while, do, break, continue
Access Modifierspublic, private, protected
Class-Relatedclass, interface, extends, implements, abstract
Objectnew, this, super, instanceof
Exceptiontry, catch, finally, throw, throws
Otherreturn, void, static, final, import, package

Naming Conventions

Java follows specific naming standards:

ElementConventionExample
ClassPascalCaseStudentRecord, HashMap
MethodcamelCasecalculateTotal(), getName()
VariablecamelCasefirstName, totalCount
ConstantUPPER_SNAKE_CASEMAX_SIZE, PI
Packageall lowercasecom.bigxstar.utils

Printing Output

Java provides several ways to print output:

java
public class OutputDemo {
    public static void main(String[] args) {
        // println — prints with a new line
        System.out.println("Hello, World!");
        System.out.println("This is on a new line.");

        // print — prints without a new line
        System.out.print("Hello ");
        System.out.print("World!");
        System.out.println(); // Just a new line

        // printf — formatted output
        String name = "Java";
        int version = 21;
        System.out.printf("Welcome to %s version %d%n", name, version);
    }
}

Output:

Hello, World!
This is on a new line.
Hello World!
Welcome to Java version 21

Reading Input

Use the Scanner class to read user input:

java
import java.util.Scanner;

public class InputDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        System.out.print("Enter your age: ");
        int age = scanner.nextInt();

        System.out.printf("Hello %s, you are %d years old.%n", name, age);

        scanner.close();
    }
}

Output:

Enter your name: Arjun
Enter your age: 22
Hello Arjun, you are 22 years old.

Complete Example

Here's a program that demonstrates multiple syntax concepts:

java
package com.bigxstar.tutorial;

import java.util.Scanner;

/**
 * A simple temperature converter program.
 * Demonstrates basic Java syntax, input/output, and variables.
 */
public class TemperatureConverter {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Get temperature in Celsius
        System.out.print("Enter temperature in Celsius: ");
        double celsius = scanner.nextDouble();

        // Convert to Fahrenheit
        double fahrenheit = (celsius * 9.0 / 5.0) + 32;

        // Display result
        System.out.printf("%.1f°C = %.1f°F%n", celsius, fahrenheit);

        scanner.close();
    }
}

Output:

Enter temperature in Celsius: 37
37.0°C = 98.6°F

Summary

  • Java programs must have a class with a main method as the entry point
  • Java is case-sensitive and every statement ends with a semicolon
  • Code blocks are enclosed in curly braces { }
  • Follow Java naming conventions: PascalCase for classes, camelCase for methods/variables
  • Use System.out.println() for output and Scanner for input
  • Java has three types of comments: single-line (//), multi-line (/* */), and Javadoc (/** */)
  • There are 67 reserved keywords that cannot be used as variable names