Basic Building Blocks of Java

Components of Java Programs

Java source code files

The Java compiler imposes some specific rules on the naming of source code files.

Statements

Statements in Java are made up of:

Escape Sequences

String and character literals can contain special escape sequences that represent single characters that cannot be represented with a single character in code.
Escape
Sequence
Meaning
\n newline
\t tab
\b backspace
\r carriage return
\" double quote
\' single quote
\\ backslash

Comments

Comments are used to improve the readability of code. Comments are ignored by the compiler. There are two styles of comments in Java:

Variables

Variables are used to store data. Every Java variable has a:

Identifiers

Identifiers are the names for things (variables, functions, etc) in the language. Some identifiers are built-in, and others can be created by the programmer.

Style-conventions (for indentifiers)


Primitive Data Types

Java has a small set of what are known as primitives. These are basic data types that are predefined for the language.

Declaring Variables


Initializing Variables

Constant Variables

(Woohoo! An oxymoron!) A variable can be declared constant by using the keyword final
  final double PI = 3.14159;
After this, PI cannot be changed. The following would not work:
  PI = 15;

Operators



Assignment Operator


Arithmetic Operators

Name Symbol Arity Usage
Add + binary x + y
Subtract - binary x - y
Multiply * binary x * y
Divide / binary x / y
Modulus % binary x % y
Minus - unary -x

Operator precedence


Some short-cut assignment operators (with arithmetic)

 
  v += e;    means    v = v + e;
  v -= e;    means    v = v - e;
  v *= e;    means    v = v * e;
  v /= e;    means    v = v / e;
  v %= e;    means    v = v % e;

Increment and Decrement Operators

  ++x;  // pre-increment (returns reference to new x)
  x++;  // post-increment (returns value of old x)
                // shortcuts for x = x + 1

  --x;  // pre-decrement
  x--;  // post-decrement
                // shortcuts for x = x - 1

Type Conversions

When working with mixed primitive types, conversions can take one of two forms:
  int i1 = 5, i2;
  short s1 = 3;		
  double d1 = 23.5, d2;
  float f1 = 12.3f;
  byte b1 = 10;

  d2 = i1;	  // automatically allowed
  i1 = b1;	  // automatically allowed
  s1 = (short)i1;  // requires cast operation (some data may be lost)
  i2 = (int)d1;	  // requires cast operation (decimal data may be lost)

  d2 = f1 + d1;	  // automatically allowed
  i2 = b1 + s1;	  // automatically allowed