The basic building blocks of the Java language

The Java language is based on the syntax of C++. Main differences are in the program structure and extensive use of Javas classes (api). Java hase no pointer types. Everything has to be declared as members of a class.

For more information see Javatutor (Nuts and Bolts of the Java Language)

A simple Java Program counts the characters in input.

class Count { 
  public static void main(String[] args) 
    throws java.io.IOException 
  { 
     int count = 0;
     while (System.in.read() != -1) 
        count++; 
     System.out.println("Input has " + count + " chars."); 
   } 
}

Variables and data types

A variable has a type , a name and a content.

All variables must be declared (at declaration they gan be given the initial value)

int x;

int y = 0;

Types

Operators

Operators perform functions on one or two varables (compare - add - assign value et c.)

See Chapter Nuts and Bolts of the Java language - Operators.

Arithmetics

+ (addition), - (subtraction), * (multiplication), / (division), and % (modulo)

+ can also catenate two character strings "ab" + "ba" => "abba"

++ adds one its operand (count++)

-- subtracts one of its operand (count--)

Relational and conditional expressions

> , <, <=, >=, ==, !=

Conditional

Assignment

variable = variable (or expression)

Expressions

a series of variables and operators resulting a value

Control flow

Java program consists of statements.

A statement can be a single statment.A single statems ends with ;

i = i+1;
System.out.println( ... );

or a statement block enclosed in curly brackets

{ i=i+3; s=t/4;}

While-statement

while (expression) statement 

while expression is true do the statement;

If - statement

if (expression) statement 

If expression is true do the statement.

If statemnt can contain an else part

if (testscore >= 90) 
  { grade = 'A'; } 
else if (testscore >= 80) 
  { grade = 'B'; } 
else if (testscore >= 70) 
  { grade = 'C'; } 
else if (testscore >= 60) 
  { grade = 'D'; } 
else { grade = 'F'; }

Switch statemens

Alternative actions among known alternative values

int month; 
. . . 
switch (month) {
case 1:  System.out.println("January"); break;
case 2:  System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break; 
case 6: System.out.println("June"); break; 
case 7: System.out.println("July"); break; 
case 8: System.out.println("August"); break; 
case 9: System.out.println("September"); break; 
case 10: System.out.println("October"); break; 
case 11: System.out.println("November"); break; 
case 12: System.out.println("December"); break; 
}

Loop statement

for (initialization; termination; increment) statement

Do-While

do {statements} while (booleanExpression);