1. java
  2. /basics
  3. /syntax

The Basics of Java Syntax

Getting Started

If you're just starting on your Java journey, getting accustomed to the basic syntax is the logical first step. One of the core characteristics of the language is its statically typed nature. Unlike its dynamically typed counterparts such as Python or JavaScript, Java requires us to explicitly declare the data type of a variable when it's first introduced.

With this approach, we can make our codebases more predictable and catch potential bugs early in the process. Specifically, by enforcing type-checking during the compilation process, Java ensures that type-related errors are caught before the code is executed, making our programs more reliable.

We'll cover some of the syntax intricacies including whitespace, identifiers, keywords, data types, control flow statements, and more.

Identifiers and Keywords

In the realm of Java, identifiers refer to how we name our code elements. They're case-sensitive and follow naming conventions for classes, methods, and variables, ensuring that our code is comprehensible. We should note that identifiers can consist of Unicode characters, punctuation like underscores, and currency signs such as $.

However, these identifiers cannot start with a digit or a reserved keyword. We need to steer clear of using these keywords since they hold special meanings within the language and attempting to use them as identifiers can trigger errors due to naming conflicts.

With a table of Java keywords handy, you can easily avoid unintentional misuses, keeping your code safe from potential mishaps.

KeywordDescription
abstractIndicates that a class or method is incomplete
assertTests a condition and throws an error if it's false
booleanRepresents a boolean value (true or false)
breakExits a loop or switch statement
byteRepresents an 8-bit integer value
caseA branch in a switch statement
catchHandles exceptions in a try-catch block
charRepresents a single character
classDeclares a class
continueSkips the rest of the current iteration of a loop
defaultThe default branch in a switch statement
doStarts a do-while loop
doubleRepresents a double-precision floating-point value
elseThe branch of an if statement that is executed if false
enumDeclares an enumerated type
extendsIndicates that a class is a subclass of another class
finalIndicates that a variable or method cannot be changed
finallyCode that is executed after a try-catch block
floatRepresents a single-precision floating-point value
forStarts a for loop
ifTests a condition and executes code if true
implementsIndicates that a class implements an interface
importImports a package or class into your program
instanceofTests whether an object is an instance of a particular class
intRepresents a 32-bit integer value
interfaceDeclares an interface
longRepresents a 64-bit integer value
nativeIndicates that a method is implemented in native code
newCreates a new object
packageDeclares a package
privateIndicates that a variable or method is only accessible within the class where it is declared
protectedIndicates that a variable or method is only accessible within the class where it is declared or its subclasses
publicIndicates that a variable or method is accessible from anywhere in the program
returnReturns a value from a method
shortRepresents a 16-bit integer value
staticIndicates that a variable or method belongs to a class, not an instance of the class
strictfpIndicates that floating-point calculations should be performed strictly according to the IEEE 754 standard
superRefers to the superclass of a class
switchStarts a switch statement
synchronizedIndicates that a method can only be accessed by one thread at a time
thisRefers to the current object
throwThrows an exception
throwsIndicates that a method can throw a particular
transientIndicates that a variable should not be included when an object is serialized
tryStarts a try-catch block
voidIndicates that a method does not return a value
volatileIndicates that a variable may be modified by multiple threads
whileStarts a while loop

Basic Structure of a Java Program

Every Java program, no matter how simple or complex, consists of one or more classes. Think of a class as a layout for creating objects equipped with properties and methods. To truly grasp the concept, let's dissect its fundamental structure.

public class ClassName {
    // Fields, constructors, and methods
    public static void main(String[] args) {
        // Code to be executed when the program is run
    }
}

So, the public keyword signals that the class is accessible from outside the package. A class name must be a valid Java identifier, starting with a capital letter. Within the class body, we'll find fields (variables), constructors (methods invoked upon object creation), and methods (functions that perform actions or return values).

Now, let's turn our attention to the main method, as the core of a Java program. This special method springs into action when we run the program.

public static void main(String[] args) {
    // Code to be executed when the program is run
}

Once again, public, denotes that the method can be called from outside the class. Then, the static keyword specifies that the method belongs to the class, rather than an instance of it, while the void conveys that the method doesn't return a value, and main serves as the method name.

Lastly, the String[] args parameter is an array of strings passed to the program as command-line arguments.

We can declare a class by following the public class ClassName {} syntax. For instance, to declare a class called Person, we'd write:

public class Person {
    // Fields, constructors, and methods
}

When declaring a method, we use the syntax public static returnType methodName(parameters) {}. As an example, let's declare an add method that accepts two integers and returns their sum.

public static int add(int a, int b) {
    return a + b;
}

Whitespace

Whitespace, the unassuming combination of spaces, tabs, and new lines, plays a vital role in separating statements in Java programs. While it isn't strictly necessary for a Java program to run correctly, its subtle presence significantly enhances code readability.

Java employs whitespace to separate statements within a block of code, as demonstrated below.

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

Notice the whitespace between the first two statements. This seemingly trivial space provides a clear distinction between the class declaration and the main method declaration, improving the code's overall readability.

Data Types and Variables

Java embraces two primary categories of data: primitive and non-primitive. Primitive data types, the bedrock of all data, encompass int, boolean, char, float, double, byte, short, and long. On the other hand, non-primitive data types consist of more complex structures such as arrays, strings, and classes.

Simply put, variables act as storage units for data in our programs, each boasting a name, a data type, and a value. To declare a variable in Java, we use the syntax data_type variable_name = value;.

int age = 27;

Operators and Expressions

Operators in Java programs serve as the tools for performing operations on data. Four distinct types of operators populate the Java landscape:

  • Arithmetic operators: +, -, *, /, and %

  • Comparison operators: ==, !=, <, >, <=, and >=

  • Logical operators: &&, ||, and !

  • Assignment operators: =, +=, -=, *=, /=, and %=

Expressions, on the other hand, are intricate blends of operators, variables, and literals. They are instrumental in performing calculations or evaluating conditions within Java programs.

For instance, we can calculate the area of a circle with a radius of 5 to demonstrate the claim.

double radius = 5;
double area = Math.PI * radius * radius;

Control Flow Statements

Control flow statements in Java dictate the order in which statements are executed. There are three primary types of control flow statements:

  • If-else statements: Execute code based on the result of a condition.

  • Switch statements: Execute different branches of code depending on the value of a variable.

  • Loops: Repeatedly execute a block of code.

Consider the example of a for loop that prints the numbers from 1 to 10.

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

Exception Handling

Exceptions are unforeseen errors that arise during the execution of a Java program. Basically, exception handling is a way of catching and managing these errors to prevent our program from crashing. In Java, we can leverage try-catch blocks as trusty tools to handle exceptions. Observe the syntax of a try-catch block that handles a NumberFormatException.

try {
    int num = Integer.parseInt("hello");
} catch (NumberFormatException e) {
    System.out.println("Invalid number format");
}

Final Thoughts

Getting accustomed to these basic syntax concepts is just the first step. We advise you to dedicate some time to practice, as an essential step towards becoming a proficient Java user. We'll continue to explore the vast landscape of Java by covering these concepts individually and in-depth, to complement your existing knowledge. Moreover, we encourage you to check out our additional resources found below.

Useful Resources

A Comprehensive Guide to Java Comments