Version without JavaScript, read-only: workshops, quizzes and running code are not available here. Full version · Catalogue · Sign in

Lecture notes · chapter 4

Basic semantics

Instructions, assignment, variable scope and operators.

4.1 Instructions

There are two kinds of instructions: variable declarations, and instructions to execute (assignment, input, output…). Instructions are executed in the order in which they are written.

instruction 1;
instruction 2;
// ...
instruction n;

4.2 Assignment operator

The assignment operator = places the result of an expression in a variable:

  1. the expression on the right of the operator is evaluated;
  2. the result is stored in the variable on the left.

An assignment can be made when a variable is declared: this is called initialisation.

int monAge = 10;
int anneeEnCours = 1999;

4.3 Blocks, scope and declarations

A program can be split into different blocks enclosed in braces {}.

  • A child block has access to the elements of the parent block; the reverse is not true.
  • A variable ceases to exist as soon as the block that declares it ends: mind the scope!
  • Redeclaring a variable is forbidden.

Scope, as the compiler sees it

public class Demo {
    public static void main(String[] args) {
        int dehors = 1;
        {
            int dedans = 2;
            System.out.println("the child block sees dehors: " + dehors);
            System.out.println("and dedans: " + dedans);
        }
        // System.out.println(dedans);  <- dedans no longer exists here
        System.out.println("end: " + dehors);
    }
}

4.4.1 Arithmetic operators

OperatorDescription
+Addition
-Subtraction
*Multiplication
/Division
%Modulo (remainder of integer division)
<<Left bit shift
>>Right bit shift

4.4.2 Comparison and bitwise operators

OperatorMeaning
>strictly greater than
<strictly less than
>=greater than or equal to
<=less than or equal to
==equality
!=not equal to
&bitwise AND
^bitwise exclusive OR
|bitwise OR
&&logical AND
||logical OR

4.4.3 Shorthand notation

a++; // equivalent to: a = a + 1;
a--; // equivalent to: a = a - 1;
a++; // Returns the value of a THEN increments it
--b; // Decrements b THEN returns its value

The basic operators can be combined with assignment:

a /= 10;  // same as: a = a / 10
a -= 10;  // same as: a = a - 10
a *= 10;  // same as: a = a * 10
a |= 10;  // same as: a = a | 10
a <<= 10; // same as: a = a << 10

Pre-increment versus post-increment

public class Demo {
    public static void main(String[] args) {
        int a = 5;
        System.out.println("a++ prints " + (a++) + " then a is " + a);
        int b = 5;
        System.out.println("++b prints " + (++b) + " and b is " + b);

        int c = 5;
        c += 10;
        System.out.println("c after c += 10: " + c);
        System.out.println("17 % 5 = " + (17 % 5));
    }
}