Java Basic Syntax or Grammar: An Easy Tutorial

Hello there! Are you ready to dive into the world of Java programming? If so, you’re in the right place. In this tutorial, we’ll explore the basic syntax of Java, the popular object-oriented programming language. So, buckle up and let’s get started!

Understanding Java Syntax Or Grammar

Java syntax, huh? Sounds like a mouthful, but it’s really not that scary. Think of it as the grammar rules for the Java language. Just like you need to know where to put your commas and periods in English, you need to know where to put your semicolons and brackets in Java.

Grammar Rule 1: Semicolons ;

Every Java statement ends with a semicolon, just like this:

System.out.println("Hello, World!");
Java

See that little semicolon at the end? That’s Java’s version of a period. It tells the computer, “Hey, I’m done with this thought. On to the next one!”

Grammar Rule 2: Brackets {}

All contents inside a class and method are put inside a pair of curly bracket {}; we learn what a class and method are later in this tutorial.

Just for now, just know that we need to put content of a class and method inside a curly or second bracket {}.

Check out the following example, both Main class and main method use the second bracket {}.

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

Grammar Rule 3: Comment //

So, when you write code, you just don’t write all the lines for only for the computer to understand. You write many things for yourself as well so that when you or some else come back to read or debug the code in future, you can understand the code easily. In other world, you make comments about the code in human language.

Comments in Java are notes that we can write in our code that the computer ignores. They’re just for humans to read. They’re great for explaining what our code is doing or leaving notes for other programmers (or for ourselves!).

There are two types of comments in Java:

  1. Single-line comments: These start with //. Everything after // on the same line is a comment.
// This is a single-line comment
int myNumber = 10; // You can also put comments at the end of a line
  1. Multi-line comments: These start with /* and end with */. Everything in between is a comment, even if it spans multiple lines.
/* This is a multi-line comment.
   You can write as many lines as you want!
   The computer will ignore all of them. */
int myNumber = 10;

Remember, comments are your friends! They can help make your code easier to understand.

More Grammar Rules

Check out the next section (how a Java program is structured).

Java Program Structure

Understanding the structure of a Java program is crucial for any beginner. Let’s break down the structure using the classic “Hello, World!” program as an example.

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

Let’s understand the code using a movie analogy: Imagine you’re a director making a movie. In Java, writing a program is like directing a movie.

  1. public class HelloWorld: This is like declaring the title of your movie. In our case, the movie (or program) is called “HelloWorld”.
  2. public static void main(String[] args): This is the main scene of your movie. It’s where all the action happens. The main part is like saying “Action!” on set. It’s what starts everything off.
  3. System.out.println(“Hello, World!”);: This is the main line of dialogue in your scene. In this case, the line is “Hello, World!”. When the scene (or program) is played, this line is delivered.

So, in simple terms, we’ve made a movie called “HelloWorld”, with one scene that delivers the line “Hello, World!”. And just like how every movie needs a director to yell “Action!”, every Java program needs a main method to kick things off.

Technically, in this example, HelloWorld is our class, main is our method. But we’ll try to understand what class and object are in a later section. But before that, let’s learn some key concept such as Variables, Data Types, Operators, control statements, loops and functions.

Java Variables and Data Types

Variables are like containers that store data.

For example, in the following code:

int myNumber = 5;

myNumber is a variable that holds the value 5.

int is the data type called integer. But what is a data type.

Data type is a keyword that determines the size and type of value it can hold. For example, int keyword indicates that the variable will store integer value (such as 1, 2, 3 etc).

Grammar Rule: Rule 1 for variables

A variable must have a data type and a name. Data type determines the size and type of value it may hold.

Code Example

So why don’t you try running the following code?

public class PracticeJavaVariable {
    public static void main(String[] args) {
        int myNumber = 10; // Here, 'myNumber' is a variable of type 'int' (integer).
        System.out.println(myNumber); // This will print: 10
    }
}
Java

In this code, we’re creating a box named myNumber and putting the number 10 inside it. Then, we’re showing what’s inside the box.

If we run the code in IntelliJ IDEA, we will see the output ’10’ in the console; just see below.

Run Java code to understand the concept of variable
Run Java code to understand the concept of variable

More about variables

Here are more examples of variable declarations using different data types:

// Declaring and initializing variables in Java
int myAge = 25; // integer
double myWeight = 70.5; // floating-point number
char myInitial = 'A'; // character
boolean isJavaFun = true; // boolean

In the above code, myAge, myWeight, myInitial, and isJavaFun are variables of types int, double, char, and boolean, respectively.

IT DOES NOT MAKE SENSE, RIGHT? Check out the detailed tutorial on Java Variables.

Java Operators

Operators in Java are special symbols like plus (+), minus (-) and so on.

Operators are used to perform operations (such as addition) on variables and values.

For example, the + operator adds two numbers together, like so:

int sum = 5 + 3; // sum is now 8

Code Example

Let’s see a code example which you can running yourself and understand. Practice make a person perfect!

public class Main {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 5;
        int sum = num1 + num2;
        System.out.println(sum);
    }
}
Java

Here, we have two boxes, num1 and num2. We’re adding the numbers inside these boxes together and putting the result in a new box named sum. Then, we’re showing what’s inside the sum box.

More about Operators

Here are more examples:

// Using operators in Java
int a = 10;
int b = 20;
int sum = a + b; // addition
int diff = a - b; // subtraction

In the above code, + and - are arithmetic operators that perform addition and subtraction, respectively.

There are many types of operators in Java, including arithmetic operators (+, -, *, /, %), relational operators (==, !=, <, >, <=, >=), and bitwise operators (&, |, ^, ~, <<, >>, >>>). But don’t worry, we’ll go over each of these in detail later on.

Java Control Statements

Control statements in Java allow you to control the flow of program execution based on certain conditions. The if-else and switch statements are popular control statements in Java.

Control statements like if, else are used to make decisions in the code.

For example, int the following code snippet, first we are putting a value (85) in a variable (like a box or container). Then program decides grades based on score; if the score is more than or equal to (>=) 90, it will print “Excellent”.

// Using if-else statement in Java
int score = 85;
if (score >= 90) {
    System.out.println("Excellent!");
} else if (score >= 75) {
    System.out.println("Good job!");
} else {
    System.out.println("Keep trying!");
}
Java

In the above code, the program prints different messages based on the value of score.

Code Example

Let’s see a code example which you can running yourself and understand. Practice make a person perfect!

public class Main {
    public static void main(String[] args) {
        int num = 10;
        if (num > 5) { // 'if' is a control statement.
            System.out.println("Number is greater than 5"); // This will print: Number is greater than 5
        }
    }
}
Java

In this code, we’re checking if the number inside the box num is bigger than 5. If it is, we’re saying “Number is greater than 5”.

Java Loops

Loops in Java are used to repeatedly execute a block of code as long as a certain condition is met. Java provides several types of loops: for, while, and do-while.

// Using a for loop in Java
for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}
Java

In the above code, the for loop prints the numbers 1 through 5 to the console.

Code Example

Let’s see a code example which you can running yourself and understand. Practice make a person perfect!

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            System.out.println(i);
        }
    }
}
Java

Here, we’re counting from 0 to 4. For each count, we’re showing the current number.

Java Functions

Functions in Java, often referred to as methods, are blocks of code that perform a specific task. A function is defined with the name of the function, followed by parentheses ().

// Creating and calling a function in Java
void greet() {
    System.out.println("Hello, Java learner!");
}

// Call the function
greet();
Java

In the above code, greet is a function that prints a greeting message. The function is then called using its name followed by parentheses.

Code Example

Let’s see a code example which you can running yourself and understand. Practice make a person perfect!

public class Main {
    public static void main(String[] args) {
        greet();
    }

    public static void greet() {
        System.out.println("Hello, Java learner!");
    }
}
Java

In this code, we’re calling a set of instructions named greet. When we call greet, it says “Hello, Java learner!”.

Java Classes, Objects, Variables and Methods: An easy-peasy analogy

In Java, everything revolves around objects and classes.

Let’s use the analogy of a kitchen to understand these concepts:

  1. Class: Think of a class as a blueprint for a kitchen. It defines the structure and properties of the kitchen. For example, the blueprint might specify that a kitchen has cabinets, a refrigerator, an oven, a sink, etc.
  2. Object: An object is an instance of a class. So, using the blueprint (class), you can build a kitchen (object). Each kitchen (object) you build with the blueprint (class) will have the same structure and properties, but you can set different values for those properties. For example, one kitchen might have white cabinets and a stainless steel refrigerator, while another kitchen might have brown cabinets and a black refrigerator.
  3. Variable: Variables are like the properties of the kitchen. For example, the color of the cabinets, the brand of the refrigerator, the number of burners on the stove, etc. are all variables of the kitchen. They represent the state of the kitchen.
  4. Method: Methods are like the actions you can perform in the kitchen. For example, you might have a method for cooking a meal, which involves a series of steps like turning on the stove, placing a pan on the burner, adding ingredients to the pan, etc. Another method might be cleaning the kitchen, which involves steps like washing the dishes, wiping down the counters, sweeping the floor, etc.

So, in summary:

  • A class is like a blueprint for a kitchen.
  • An object is a kitchen built from that blueprint.
  • A variable is a property of the kitchen, like the color of the cabinets or the brand of the refrigerator.
  • A method is an action you can perform in the kitchen, like cooking a meal or cleaning up.

Sure, here’s a simple example of a Kitchen class in Java:

public class Kitchen {
    // Variables (properties of a kitchen)
    String cabinetColor;
    String refrigeratorBrand;
    int numberOfBurners;

    // Constructor (used to create a kitchen object)
    public Kitchen(String cabinetColor, String refrigeratorBrand, int numberOfBurners) {
        this.cabinetColor = cabinetColor;
        this.refrigeratorBrand = refrigeratorBrand;
        this.numberOfBurners = numberOfBurners;
    }

    // Method (an action you can perform in the kitchen)
    public void cookMeal() {
        System.out.println("Cooking a meal in the " + cabinetColor + " kitchen with a " + refrigeratorBrand + " refrigerator and " + numberOfBurners + " burners.");
    }
}
Java

You can create an instance (object) of the Kitchen class and call the cookMeal method like this:

public class Main {
    public static void main(String[] args) {
        // Create a Kitchen object
        Kitchen myKitchen = new Kitchen("white", "Samsung", 4);

        // Call the cookMeal method
        myKitchen.cookMeal();
    }
}
Java

When you run the Main class, it will print:

Cooking a meal in the white kitchen with a Samsung refrigerator and 4 burners.

This is a very basic example. In a real program, the Kitchen class might have more complex methods and variables, and it might interact with other classes as well.

More Code Examples For Practice

Let’s look at two complete Java programs that demonstrate the basic syntax.

Example 1: A Simple Java Program to Add Two Numbers

public class AddNumbers {
    public static void main(String[] args) {
        int num1 = 5, num2 = 15, sum;
        sum = num1 + num2;
        System.out.println("The sum is: " + sum);
    }
}
Java

When you run this program, it adds two numbers and prints the sum to the console.

Example 2: A Java Program to Check if a Number is Even or Odd

public class CheckNumber {
    public static void main(String[] args)
        int num = 20;
        if (num % 2 == 0) {
            System.out.println(num + " is even.");
        } else {
            System.out.println(num + " is odd.");
        }
    }
}
Java

In this program, we use the modulus operator % to find the remainder of the number when divided by 2. If the remainder is 0, the number is even; otherwise, it’s odd.

Wrapping Up

Congratulations! You’ve just taken a big step in your Java learning journey. We’ve covered a lot of ground in this tutorial, from understanding classes and objects, variables and data types, operators, control statements, loops, to functions in Java. Remember, practice is key when it comes to programming. So, try to write and run as many programs as you can.

Frequently Asked Questions (FAQ)

  • What is Java basic syntax?

    Java basic syntax refers to the set of rules defining how a Java program is written and interpreted.

  • How to write a syntax in Java?

    In Java, syntax is written using a combination of classes, objects, variables, data types, operators, control statements, loops, and functions.

  • What is the first syntax of Java?

    The first syntax of Java is the class definition. Every Java program starts with a class definition.

  • What is the basic syntax of a code?

    The basic syntax of a code refers to the rules and conventions that dictate how the code is written in a specific programming language.

  • What is the difference between class and object in Java?

    A class is a blueprint from which objects are created. An object is an instance of a class.

  • How do loops work in Java?

    Loops in Java are used to repeatedly execute a block of code as long as a certain condition is met.

  • What are Java functions?

    Functions in Java, often referred to as methods, are blocks of code that perform a specific task.

  • What are Java operators?

    Operators in Java are special symbols that perform specific operations on one, two, or three operands and then return a result.

  • What are control statements in Java?

    Control statements in Java allow you to control the flow of program execution based on certain conditions.

  • What are variables in Java?

    Variables in Java are like containers that store data. Every variable has a data type, which determines the size and type of value it can hold.

  • Java OOP Concepts: Learn about the four main concepts of object-oriented programming (OOP) in Java: encapsulation, inheritance, polymorphism, and abstraction.
  • Java Exception Handling: Understand how to handle errors in your Java programs using try, catch, and finally blocks.
  • Java File I/O: Get to grips with reading from and writing to files in Java.
  • Java Multithreading: Discover how to write programs that do multiple things at once with Java multithreading.

Remember, the journey of a thousand miles begins with a single step. So, keep learning and keep coding! Happy programming!

Scroll to Top