Syntax:
- Java looks very similar to C!
Punctuation:
- each statement ends with a semicolon (;)
Operators:
- logical operators ( e.g., ||, &&),
- arithmetic operators ( e.g. +, -, *, /),
- relational operators (e.g., ==, <=, !=),
- bitwise operators ( e.g., |, &)
Control flow:
- there are five basic statements: if-else, do-while, while, for, switch
Data types: Java supports eight primitive data types:
- byte: one byte long, signed value
- short: two-byte long, signed value
- int: four-byte long, signed value
- long: eight-byte long, signed value
- float: four-byte long, signed floating point
- double: eight-byte long, signed floating point
- char: two-byte long, Unicode character
- boolean: non-numeric value of true or false
Comments: Java supports three kinds of comments:
- // comments single line comment
- /* comments */ multi-line comment
- //* comments */ javadoc comment
Classes and objects
Java, like any object-oriented programming, uses the notions of classes and objects. Every object in Java has a class that defines its data and behaviour. Each class can contain two kinds of members:
- Data members are fields of data variables associated with a class.
- Function members, that are called methods, are executable code of a class. A function member, called constructor, is invoked after the object creation. Constructors have the same name as the class. A method that is not declared as void returns a value (see getX). Methods declared as void do not return anything (see translate).
The members can be public or private. A private member is accessible only by the class in which it is defined. A public member is accessible by the other classes as well.
class Point {
private int x;
public int y;
Point()
{
x = 10;
y = 10;
}
public void translate(int dx, int dy)
{
x = x + dx;
y = y + dy;
}
public int getX()
{
return x;
}
}
To create a new reference of an object:
Point p1 = new Point();
Calling methods:
p1.translate( 10, 30);
x = p1.getX();
Access to the data member using the dot (.) notation:
p1.x is not possible because it is a private data member
p1.y is allowed
Variables
At any place within the body of the method, you can declare variables that are local and only live while the method is executed.
Arrays
For an 1D array of size N, the index starts with 0 and ends with N-1.
An array can be created as follows:
int[] array = new int[200];
Java provides multidimensional arrays but, for efficiency reasons, we will only use 1D arrays.
|