Chapter 212 min read

Java Syntax Basics

Understanding data types, variables, operators, arrays, and program structure.

Released1995
Core MottoStatically-Typed & Platform-Independent
CreatorsOracle / Sun Microsystems

1. Overview

Java is a statically-typed, object-oriented, and platform-independent programming language.
Code compiles into intermediate bytecode executed by the Java Virtual Machine (JVM).

Platform Independence

Write Once, Run Anywhere (WORA):Java programs can be compiled on one machine (e.g., Windows) and executed on another (e.g., macOS, Linux).
Bytecode Execution:Source code converts to bytecode (.class), eliminating the need to modify code for different OS environments.

Static Typing

Explicit Declaration:Every variable must be declared with a specific data type before it can be used.
Compile-Time Safety:Mismatched types and assignments are caught during compilation rather than at runtime.

2. Data Types

Java separates memory management into Primitive Types and Objects/Reference Types.

Primitive Types

Integer Types:byte (8-bit), short (16-bit), int (32-bit), long (64-bit)
Decimal Types:float (32-bit), double (64-bit)
Character Type:char (16-bit Unicode)
Boolean Type:boolean (true or false)

Reference Types

Memory Allocation:Stores memory references/pointers pointing to object heap locations.
Default State:Can hold a null reference.
String Class:Fundamental reference type used to wrap character sequences.
Classroom Discussion Starter
Why are char literals surrounded by single quotes ('a') while String literals use double quotes ("a")?
Takeaway Goal: Primitive characters represent single 16-bit Unicode characters, whereas Strings are full reference objects wrapping character sequences.

3. Declaring & Initializing Variables

Declaration requires a strict data type and identifier name.
All Java statements must terminate with a semicolon (;).

Default Values & Declaration

Uninitialized Class Fields:Assigned defaults automatically (0 for int, 0.0 for double, false for boolean).
Local Variables:Must be explicitly initialized before reading.
java
int a;
int b;
double c;

Assignment Operator (=)

Inline Initialization:Assign values at the time of declaration.
Strict Syntax Rules:Semicolons are mandatory to terminate statements.
java
int a = 10;
int b = 5;
double c = a + b;

System.out.println(a + " + " + b + " = " + c);
// Output: 10 + 5 = 15.0

String, Char, and Boolean Literal Declaration

String Literals:Wrapped using double quotes (" ").
Char Literals:Wrapped using single quotes (' ').
Boolean Literals:Assigned direct keywords (true / false).
java
String name = "Baeldung Blog";
char toggler = 'Y';
boolean isVerified = true;

4. Arrays

Arrays are fixed-size reference objects storing indexed elements of a single uniform type.

Declaring and Indexing Arrays

Zero-Based Indexing:The first element begins at index 0, terminating at length - 1.
Fixed Allocation:Array sizes cannot be altered once created in memory.
Length Property:Access array capacity directly using the .length property.
java
// Declare an array holding up to 100 integers
int[] numbers = new int[100];

// Assign values by index
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;

// Access an element & get total length
int thirdElement = numbers[2];
int lengthOfNumbersArray = numbers.length;

5. Java Keywords

Keywords are reserved syntax terms that hold strict structural meanings in the compiler.

Identifier Rules

Reserved Names:public, static, class, main, new, instanceof cannot be redefined.
Reserved Values:Words like true, false, and null are reserved literal constants.

6. Operators in Java

Java provides built-in operators for arithmetic, bitwise, logical evaluations, and comparisons.

6.1 Arithmetic Operators

Standard Math:Operators include +, -, *, /, and % (modulus/remainder).
String Concatenation:The + operator automatically joins strings with primitive types.
java
String output = a + " + " + b + " = " + c;

6.2 Logical Operators (&&, ||, !)

Logical AND (&&):Evaluates to true if both conditions are met.
Logical OR (||):Evaluates to true if at least one condition is met.
Logical NOT (!):Inverts boolean state.
java
int number = 6;

// Logical AND example
if (number % 2 == 0 && number % 3 == 0) {
    System.out.println(number + " is divisible by 2 AND 3");
}

// Logical OR example
if (number % 2 == 0 || number % 5 == 0) {
    System.out.println(number + " is divisible by 2 OR 5");
}

6.3 Comparison Operators

Value Checks:Compare numeric values with <, <=, >, >=.
Equality Checks:Use == (equal to) and != (not equal to).
java
public boolean canVote(int age) {
    if (age < 18) {
        return false;
    }
    return true;
}

7. Program Structure

Classes form the primary structure of Java programs. Executable programs require a main entry point.

Executable Java Class

Source Naming:File names must match the public class name (e.g., SimpleAddition.java).
Entry Point:Java applications execute sequentially starting from public static void main(String[] args).
java
public class SimpleAddition {

    public static void main(String[] args) {
        int a = 10;
        int b = 5;
        double c = a + b;
        System.out.println(a + " + " + b + " = " + c);
    }
}

8. Compiling & Executing

Compile Java source code into bytecode (.class) via javac, then run using the java command.

CLI Commands

Step 1:javac SimpleAddition.java produces compiled platform-independent bytecode.
Step 2:java SimpleAddition launches the JVM to run the bytecode.
bash
# Step 1: Compile .java source code into .class bytecode
javac SimpleAddition.java

# Step 2: Execute bytecode using the Java Runtime Environment
java SimpleAddition

# Console Output:
# 10 + 5 = 15.0