Skip to content

Java Syntax for Beginners: Variables, Methods and Program Structure

Quick answer

Learn Java syntax step by step: class and main method, variables and types, methods, control flow, common mistakes and practice exercises.

Java Syntax for Beginners: Variables, Methods and Program Structure

Java syntax is the set of rules for writing valid Java code. Every program lives inside a class, starts running at the main method, ends each statement with a semicolon, groups code in curly braces and declares the type of every variable. Master that structure, plus methods and control flow, and you can read and write most beginner Java programs.

Key takeaways

  • Every Java program needs a class, and execution starts in the main method.
  • Types are declared and fixed, so int, double, boolean, char and String behave differently.
  • Integer division drops the fraction. Cast to double when you need decimals.
  • Use equals() for strings, match the file name to the public class and expect case-sensitivity.

On this page:

Syntax elementExampleRule to remember
Classpublic class Main { }A public class name must match the file name, Main.java
Entry pointpublic static void main(String[] args)The JVM starts here
Statementint age = 20;Ends with a semicolon
Variabledouble price = 49.5;Type first, then name, and the type is fixed
Block{ ... }Groups statements for classes, methods and loops
Comment// note or /* note */Ignored by the compiler
CaseString is not stringJava is case-sensitive

What does a basic Java program look like?

A basic Java program is one class with one main method. Save this as Main.java.

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

Compile and run from a terminal:

javac Main.java
java Main

Read it line by line. public class Main declares a class. main is where execution begins. static lets the JVM call it without creating an object, and void means it returns nothing. System.out.println prints a line. If your setup fails at this step, follow setting up your Java development environment.

How do variables, data types and statements work?

You declare a variable with its type, and Java enforces that type. The common beginner types are:

  • int and long for whole numbers.
  • double for decimals.
  • boolean for true or false.
  • char for one character, in single quotes.
  • String for text, in double quotes. It is a class, not a primitive.
int marks = 87;
double price = 49.5;
boolean passed = marks >= 40;
String name = "Asha";
char grade = 'A';
System.out.println(name + " passed: " + passed);   // Asha passed: true
System.out.println(7 / 2);     // 3, integer division drops the fraction
System.out.println(7 / 2.0);   // 3.5

The last two lines catch many beginners. When both operands are int, the result is int. Make one operand a double to get a decimal. More detail is in Java variables and Java data types.

How do methods and control flow work?

A method is a named block of code that takes inputs and may return a value. Control flow decides which lines run: if/else for choices, for and while for repetition.

public class Main {
    static String gradeFor(int marks) {
        if (marks >= 80) return "A";
        else if (marks >= 60) return "B";
        else if (marks >= 40) return "C";
        return "F";
    }

    public static void main(String[] args) {
        int[] scores = {87, 55, 32};
        int total = 0;
        for (int s : scores) {
            total += s;
            System.out.println(s + " -> " + gradeFor(s));
        }
        System.out.println("Average: " + (double) total / scores.length);
    }
}

Output:

87 -> A
55 -> C
32 -> F
Average: 58.0

Notice (double) total. Without the cast, 174 / 3 is integer division. Here it happens to divide evenly, but the cast is the habit that keeps averages correct. The method has a return type (String), parameters (int marks) and a return on every path.

Which beginner mistakes should you avoid, and what should you practise?

Most early errors are syntax or type mistakes that the compiler reports. Read the message and the line number before changing anything.

  • Missing semicolon or brace: the error often points to the line after the real problem.
  • Using = instead of ==: = assigns, == compares.
  • Comparing strings with ==: use a.equals(b). The operator compares references, not text.
  • File and class name mismatch: public class Main must live in Main.java.
  • Array index out of bounds: valid indices run from 0 to length - 1.
  • Wrong case: system.out.println fails, System.out.println works.

Practice set, in order of difficulty:

  1. Print your name and city on separate lines.
  2. Read two numbers and print their sum, difference and integer quotient.
  3. Write isEven(int n) and test it on five values.
  4. Print the multiplication table of any number using a for loop.
  5. Find the largest value in an int[] without using a library method.

When these feel easy, read Java programming basics and fundamentals, then common Java interview questions. Undecided between languages? See Python vs Java for beginners.

Next step

Syntax is the first layer. The next is data structures, algorithms and applying code to real problems such as machine learning. If AI is where you want to go, look at the Artificial Intelligence and Machine Learning programme from Vishlesan i-Hub, IIT Patna and check its page for the current batch date and eligibility.

Frequently asked questions

What is the basic syntax of a Java program?

A Java program has a class, usually with a public static void main(String[] args) method. Statements end with semicolons, blocks use curly braces, variables need declared types, and the language is case-sensitive.

Why must the file name match the class name in Java?

When a class is declared public, the Java compiler requires the file to carry the same name, so public class Main must be saved as Main.java. Otherwise javac reports an error.

What is the difference between int and double in Java?

int stores whole numbers and double stores decimals. Dividing two ints gives an int, so 7 / 2 is 3, while 7 / 2.0 is 3.5 because one operand is a double.

Why should I use equals() instead of == for strings?

The == operator compares whether two references point to the same object. equals() compares the text. Use equals() whenever you want to know if two strings have the same content.

Is Java case-sensitive?

Yes. String and string are different, and so are main and Main. Most beginner compile errors that say cannot find symbol come from a wrong capital letter or a typo in a name.

How long does it take to learn Java syntax?

It depends on your practice time. The core syntax in this guide is small. Working through exercises daily matters more than the calendar, and the real learning comes from writing programs, not reading.

Share LinkedIn X WhatsApp
×

Our Courses

Practice-Based Learning Tracks, Supercharged By A.I.