Sage-Code Laboratory
index<--

Java Syntax

Java is a language inspired from C++. Therefore syntax rules, symbols, operators and keywords are similar. The difference is C++ is multi-paradigm while Java is Object Oriented. In this article I will explain Java syntax in full. Do not worry about C++, it is not necessary to know it before learning Java.

Punctuation

Java is a case sensitive language. It has reserved keywords that may be full English words or abbreviations. Most keywords are lowercase. For names Java is using a curious notation that is based on alternation between uppercase and lowercase letters called CamelCase. Let's investigate an example program: HelloWorld.java

Example:

/* This is the most simple Java program.
   It demonstrates many Java syntax rules. */
class HelloWorld {
    // java main method is mandatory
    public static void main(String args[]) {
        System.out.println("Hello, World");
    }
}

Notes:

Statement

Java is a statement based language in contrast with other newer languages that can be expression based. So you need to understand this concept first before you learn the language. Later we explain also the expressions. Java uses simple statements or composite statements.

Rules:

Java uses curly brackets {...} to mark the beginning and ending of a "block of code" like C and any other language from curly bracket family. This makes the program sometimes hard to read, therefore curly brackets are organized using spaces and are usually aligned using code indentation.

Code indentation is optional in Java. However it is strongly recommended. For proper indentation professional developers convert tabs into 4 spaces and do not use tab indentations in a program file. This is very important to avoid conflict between different alignment conventions. It may improve readability and reduce number of trivial errors.

Keywords

Keywords are used to create declarations or statements. Some keywords represents constants that can be used in expressions. In IDE tools you will see these keywords highlighted with color so is very unlikely you will mess up.

Basic

assert char byte break try
boolean double enum float for
import const goto int do
return main new void if
switch case else static long
continuewhile null short  

Advanced

abstract class default final
implements interface package this
protected instanceof package super
synchronized transient public native
extends strictfp throw catch
volatile finally throws  

Declarations

Java is a strong typed language. That means we need to define data using types and names before we can create expressions. To do this we create identifiers and we associate data types to these identifiers.

An identifier start with a letter that can be lowercase or uppercase. Identifiers are associated to data types or can represent data types themselves. After you define one data type you can create other identifiers to use that data type. In Java user defined data types are called "Class".

Expressions

An expression contains identifiers, operators, parentheses and separators. Expressions can be used to create statements. One statement can contain multiple expressions. We can combine small expressions into large expressions. The order of execution can be controlled with round parenthesis (...) like in mathematical expressions.

Examples:

/* numeric expressions */
1 + 1
4 + 3/2
(1 + x) /42

/* Boolean expressions */
!true
(a && b) || c
Info:  Other languages can be "expression oriented", that means stand-alone expressions can be executed and the result of expression is automatically printed out. Java is "statement oriented". Therefore in Java expression are used in statements and can't be stand-alone.

Primitive Types

Java has eight special types named primitive types. Users can't create primitive types. Understanding primitive data types is a fundamental skill you need before you can declare classes, properties and methods. Here are these types:

Notes:

  • Primitive type, names start with lowercase letters,
  • For every primitive type, there is associated a set of operators,
  • For every primitive type, there is a class that have same name but start with uppercase.

  • Operators

    Learning the operators is the easy part of a language and is important for learning everything else. So read this table careful to understand Java expressions later. Many developers consider operators trivial but you can do many mistakes in a program if you do not understand them properly.

    Arithmetic Operators

    These operators are used to create numeric expressions.

    Operator Name Description Example
    + Addition Adds together two values x + y
    - Subtraction Subtracts one value from another x - y
    * Multiplication Multiplies two values x * y
    / Division Divides one value by another x / y
    % Modulus Returns the division remainder x % y
    ++ Increment Increases the value of a variable by 1 ++x
    -- Decrement Decreases the value of a variable by 1 --x

    Comparison Operators

    These operators are used to create logical expressions.

    Operator Name Example
    == Equal to x == y
    != Not equal x != y
    > Greater than x > y
    < Less than x < y
    >= Greater than or equal to x >= y
    <= Less than or equal to x <= y

    Boolean Operators

    A Boolean expression is an expression that returns a Boolean value: true or false. Let's consider two variables: a == true and b == true. In next table we use these two variables to make next examples:

    Operator Name Description Expression Result
    &&  and Returns true if both statements are true a && b true
    ||  or Returns true if one of the statements is true a || b true
    ! not Reverse the result, returns false if the result is true !a false

    Bitwise Operators

    These operators are used to create numeric expressions using bit level operations. We consider 1 = true and 0 = false. Then we can make logical operations between bits on same position. Some of these operators require two operands. Some are unary operators.

    Operator Description
    & AND - Sets each bit to 1 if both bits are 1
    | OR - Sets each bit to 1 if any of the two bits is 1
    ~ NOT - Inverts all the bits
    ^ XOR - Sets each bit to 1 if only one of the two bits is 1
    << Zero-fill left shift - Shift left by pushing zeroes in from the right and letting the leftmost bits fall off
    >> Signed right shift - Shift right by pushing copies of the leftmost bit in from the left and letting the rightmost bits fall off
    >>> Zero-fill right shift - Shift right by pushing zeroes in from the left and letting the rightmost bits fall off

    Variable Modifiers

    These operators are also called "in-place" modifiers. Have double role: make an operation and assign the result to left operand. The right operand can be a constant, variable or expression that return same type as the left operand.

    Operator Name Expression Equivalent
    = Assignment x = 1 x = 1
    += Addition x += 1 x = x + 1
    -= Subtraction x -= 1 x = x - 1
    *= Multiplication x *= 1 x = x * 1
    /= Division x /= 1 x = x / 1
    %= Modulo x %= 1 x = x % 1
    &= Bitwise and x &= 1 x = x & 1
    |= Bitwise or x |= 1 x = x | 1
    ^= Bitwise not x ^= 1 x = x ^ 1
    >>= left shift x >>= 1 x = x >> 1
    <<= right shift x <<= 1 x = x << 1

    Packages

    In Java the source code is created using files. Each file can contain one single Public class. You can create a Java program without packages. However a larger project need packages. One package is usually one file, but packages can be implemented partial in several *.java files. One package is an abstract concept used for 3 advantages.

    Advantages

    Packages can be reused. A package that is reusable is called library. Java packages use a curious name convention. It is closely related to folder names and is backward domain name and folder name structure. For example: "net.sage.axia.engine" can be the name of a package used by Axia project.


    Read next: Data Types