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.");
}
}
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;
Operators perform functions on one or two varables (compare - add - assign value et c.)
See Chapter Nuts and Bolts of the Java language - Operators.
+ (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--)
> , <, <=, >=, ==, !=
variable = variable (or expression)
a series of variables and operators resulting a value
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 (expression) statement
while expression is true do the 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'; }
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;
}
for (initialization; termination; increment) statement
do {statements} while (booleanExpression);