Skip to content
Explainer ยท Data Structures and Algorithms

Java Syntax Explained for Beginners: Program Structure, Data Types, Loops, Methods and Examples

By Younus FardeenUpdated 4 Nov 20264 min read
Short answer

A Java program lives inside a class and starts running from the main method. The basic syntax rules are: Java is case-sensitive, every statement ends with a semicolon, blocks use curly braces, the file name must match the public class name, and every variable needs a declared type. Compile with javac and run with java.

Java is strict, which makes it a good first language for learning how programs are built. Learn the handful of rules below and most beginner errors disappear.

Your first Java program

Save this as Hello.java. The file name must match the public class name exactly.

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, Masai!");
    }
}
  • public class Hello declares a class. All Java code lives in classes.
  • public static void main(String[] args) is where the program starts.
  • System.out.println(...) prints a line of text.
  • Curly braces { } mark the start and end of a block, and each statement ends with ;.

Compile and run from a terminal, with a JDK installed:

javac Hello.java
java Hello

Output: Hello, Masai!. From Java 11 you can also run a single file with java Hello.java.

The core syntax rules

  • Case-sensitive. Main and main are different names.
  • Semicolons end statements.
  • Class names start with a capital letter (BankAccount); methods and variables with a lowercase letter (totalMarks).
  • One public class per file, and the file name matches it.
  • Declare before use. Every variable has a type.
  • Comments: // one line, /* many lines */, /** documentation */.

Data types and variables

TypeHoldsExample
intWhole numbers (32-bit)int age = 21;
longLarge whole numbers (64-bit)long population = 1400000000L;
doubleDecimal numbersdouble cgpa = 8.7;
booleantrue or falseboolean placed = false;
charOne characterchar grade = 'A';
StringText (an object)String name = "Asha";
int age = 21;                  // whole number
double cgpa = 8.7;              // decimal number
char grade = 'A';               // one character, single quotes
boolean placed = false;         // true or false
String name = "Asha";           // text, double quotes
final int MAX_ATTEMPTS = 3;     // constant: cannot change

Operators

KindOperators
Arithmetic+ - * / % ++ --
Comparison== != > < >= <=
Logical&& || !
Assignment= += -= *= /=

Use == to compare numbers and .equals() to compare the contents of strings.

Decisions and loops

int marks = 72;
if (marks >= 90) {
    System.out.println("Distinction");
} else if (marks >= 60) {
    System.out.println("First class");
} else {
    System.out.println("Keep going");
}

for (int i = 1; i <= 3; i++) {
    System.out.println("Round " + i);
}

int n = 3;
while (n > 0) {
    System.out.println(n--);
}

Output: First class, then Round 1, Round 2, Round 3, then 3, 2, 1.

Methods

A method has a return type, a name and parameters. void means it returns nothing.

public class Calculator {
    static int add(int a, int b) {        // return type, name, parameters
        return a + b;
    }

    public static void main(String[] args) {
        int sum = add(4, 5);
        System.out.println("Sum = " + sum);   // Sum = 9
    }
}

Arrays

int[] marks = {72, 85, 90};
System.out.println(marks.length);      // 3
System.out.println(marks[1]);          // 85
for (int m : marks) {                  // enhanced for loop
    System.out.println(m);
}

An array has a fixed size, and indexes start at 0.

Reading input

import java.util.Scanner;

public class Greeting {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Your name: ");
        String name = in.nextLine();
        System.out.println("Welcome, " + name);
        in.close();
    }
}

Classes and objects

A class is a blueprint and new makes an object. The full example, with the four OOP ideas, is on the OOP page.

The most common Java errors for beginners

Error messageUsual cause
';' expectedA missing semicolon
cannot find symbolA typo, wrong capitalisation, or a variable used before it is declared
class X is public, should be declared in a file named X.javaFile name and class name do not match
incompatible typesPutting a value of the wrong type into a variable, such as a double into an int
missing return statementA method that should return a value has a path that does not
ArrayIndexOutOfBoundsExceptionUsing an index outside 0 to length - 1
NullPointerExceptionCalling a method on a variable that is null

Where to practise

Frequently asked questions

What is the basic syntax of Java?

A class containing a main method, statements ending in semicolons, code blocks in curly braces, typed variables and a file named after the public class.

Why does Java need a main method?

It is the entry point. The Java runtime looks for public static void main(String[] args) to start the program.

Is Java case-sensitive?

Yes. Hello, hello and HELLO are three different names.

What is the difference between int and Integer in Java?

int is a primitive type holding a value. Integer is an object wrapper around an int, used where objects are required, such as in collections.

Is Java easy to learn?

The syntax is stricter than Python's, which means more to type, but the rules are consistent and the compiler catches many mistakes early.

Learn this with mentors

Programmes for builders and engineers with admissions open: live classes, mentors and project work.

Continue learning

Learning path

Data Structures and Algorithms learning path

Arrays to dynamic programming in order, with a problem plan.

Explainer

Object-oriented programming explained

Classes, objects and the four pillars, with examples.

Open →
Learning path

Software Development learning path

One language, DSA, full-stack, tests and deployment.