Page Content

Tutorials

What is the Basic Syntax of Java? With Code Example

Basic Syntax of Java

Due to Java’s strong typing, all variables must be declared with a particular data type before they may be utilized. Class is not the same as class, and main is not the same as Main. It is also case-sensitive, differentiating between capital and lowercase letters. Java requires that every program activity take place inside a class.

Statements and Semicolons

As a complete unit of execution, a statement in Java is analogous to a phrase in normal language. A semicolon (;) must be used to end the majority of Java’s individual statements. This semicolon marks the end of a logical object and serves as a separator.

The end of a line is not recognized by the Java compiler as a statement terminator, enabling flexible formatting in which statements can be positioned on a single line or span numerous lines. But it’s important to realize that a semicolon is more than just “syntactic noise”; having one or not can significantly alter the meaning of your program. Even if the compiler doesn’t specifically point to the semicolon in the error message, positioning it incorrectly can result in unexpected behavior or compilation issues.

Common types of expressions that can be turned into statements by adding a semicolon include:

  • Assignment expressions (e.g., aValue = 8933.234;)
  • Increment (++) or decrement (–) operations (e.g., aValue++;)
  • Method invocations (e.g., System.out.println("Hello World!");)
  • Object creation expressions (e.g., Bicycle myBike = new Bicycle();)

Additionally, a declaration statement declares a variable, such as double aValue = 8933.234;.

Code Blocks using Curly Braces

A group of zero or more statements encased in balanced curly brackets ({}) constitutes a code block in Java. Statements are logically combined into a single unit by these braces. Many situations call for the employment of blocks, such as:

  1. Defining the body of classes and methods.
  2. Grouping statements within control flow constructs like if, else, for, while, and do-while statements.
  3. Exception handling.

A semicolon is not used to end a block of code, in contrast to statements. It’s common practice to move back out one level before a closing brace and indent one level after an opening curly brace for readability and maintainability. Using braces is advised for clarity and to avoid minor issues like the “dangling else” problem, even when the language deems them optional for single-line if or loop bodies.

Java Keywords

In Java, reserved words known as keywords have predetermined meanings for the compiler. Variables, classes, and methods cannot be identified by their names. At the moment, Java defines roughly 50 keywords.

Some examples of Java keywords include:

  • public, private, protected (access modifiers)
  • class, interface, enum
  • static, final, abstract (non-access modifiers)
  • int, boolean, char, double (primitive data types)
  • if, else, switch, for, while, do (control flow)
  • break, continue, return (branching statements)
  • try, catch, finally, throw, throws (exception handling)
  • new (object creation)
  • this, super (keywords for object reference and superclass interaction)

In addition to these keywords, Java reserves the literal values true, false, and null. These also cannot be used as identifiers.

Identifiers (Naming Rules)

Class names, variables, methods, and other user-defined things are examples of identifiers in Java programs.

The following are guidelines and accepted practices for identifying names:

  1. Case Sensitivity: The case of an identifier applies. unique IDs, myVar and MyVar.
  2. Allowed Characters: An identifier may consist of an unbounded string of Unicode characters and numbers.
  3. Starting Character: A letter (A-Z or a-z), the dollar symbol ($), or the underscore character (_) must be used as the first character.
  4. Subsequent Characters: Identifiers may have any combination of letters, numbers, dollar signs, or underscores following the initial character.
  5. No Whitespace: Characters that are used frequently in identifiers are not allowed.
  6. No Keywords: Identifiers cannot be Java keywords or the reserved values true, false, or null.

Naming Conventions (Best Practices): Conventions establish what is good practice, whereas regulations specify what is lawful.

  • Classes: The initial letter of each consecutive word should be capitalized in class names, which should be nouns and begin with an uppercase letter (e.g., MyFirstJavaClass, StudentInfo). PascalCase is what this is called.
  • Methods: Method names should be verbs that begin with a lowercase letter and capitalize the first letter of each word that follows (e.g., main, sayHi, printEmployee). CamelCase is the name for this.
  • Variables: Typically, variable names are capitalized after a lowercase letter, such as empID, firstName, or myVar. Although it is technically acceptable to begin a variable name with the dollar sign ($) and underscore (_), this is not recommended, and user-generated names typically never use the dollar symbol.
  • Constants: The final modifier is usually used for declaring constants, which are composed entirely of capital letters with underscores between words (e.g., BOXWIDTH, PI).
  • Packages: The names of packages are usually all lowercase.
  • Example of Identifiers:
    • Legal: age, $salary, _value, name_of_student, calculateTotal, HelloWorld
    • Illegal: 123abc (starts with a digit), -salary (starts with a special character not allowed), if (is a keyword)

Code Example Demonstrating Basic Syntax

Let’s look at a simple Java program to illustrate these concepts:

// MySampleProgram.java
// This program demonstrates basic Java syntax:
// classes, methods, statements, semicolons, code blocks, and identifiers.
public class MySampleProgram { // Class declaration: identifier 'MySampleProgram', follows PascalCase
    // main method: entry point of the application.
    // Identifier 'main' follows camelCase.
    public static void main(String[] args) { // Method declaration, parameters 'args'
        // Code block for the main method starts here.
        // Variable declaration and assignment statement.
        // Identifier 'message' follows camelCase.
        String message = "Hello from Java!"; // Statement ends with a semicolon.
        // Method invocation statement.
        // System.out.println is a method call.
        System.out.println(message); // Statement ends with a semicolon.
        // Another variable declaration and assignment.
        int number = 10; // Statement ends with a semicolon.
        // if-then statement using a code block.
        // 'if' is a keyword.
        if (number > 5) { // Code block starts for the if statement.
            System.out.println("The number is greater than 5."); // Statement.
            number = number + 5; // Assignment statement.
        } // Code block ends for the if statement.
        // for loop statement using a code block.
        // 'for' is a keyword. 'i' is an identifier for the loop variable.
        for (int i = 0; i < 3; i++) { // Code block starts for the for loop.
            System.out.println("Loop iteration: " + (i + 1)); // Statement.
        } // Code block ends for the for loop.
        // Final output demonstrating variable update.
        System.out.println("Final number value: " + number); // Statement.
    } // Code block for the main method ends here.
} // Code block for the MySampleProgram class ends here.

Code Output:

Hello from Java!
The number is greater than 5.
Loop iteration: 1
Loop iteration: 2
Loop iteration: 3
Final number value: 15

This output shows the sequential execution of each statement, the flow control provided by if and for statements, and the importance of comments and consistent naming in creating a readable program. The structure and operation of Java are based on the rigorous observance of semicolons and the appropriate usage of curly braces for code blocks.

Index