Java

A attempt at distilling the essence

Java Architecture

Source (.java) => Compiler => Byte code (.class)

Encapsulation

Access specifiers:

  • public: Accessible by any class, across packages.

  • package-private: The default - accessible only within package.

  • protected: Accessible by all classes within the package and sub-classes in other packages.

  • private: Accessible only within the class.

main method is always public - public static void main (String[] args) {}

All access specifiers apply to class members i.e., fields and methods; but only public and package-private (the default modifier) apply to classes.

Naming Conventions

  • Names of packages and members (variables and methods) start with a lowercase alphabet.

  • Names of variables and classes do NOT start with a number.

  • Class names start with an uppercase alphabet.

  • Multi-word names can be formed using underscores ("_") or in camelCase.

Primitive Datatypes

Integers:

  • byte: 8 bits long. From -128 to 127. Default is 0

  • short: 16 bits long. From -32768 to 32767. Default is 0

  • int: 32 bits long. From -2^31 to (2^31)-1 (signed). Default is 0

  • long: 64 bits long. From -2^63 to (2^63)-1. Default is 0l.

Since Java 8, long is from 0 to (2^64)-1.

Decimals:

  • float : 32 bits. 6 decimals precision. Default is 0.0f.

  • double : 64 bits. 15 decimals precision. Default is 0.0d.

float and double should not be used for precise calculations. Use java.math.BigDecimal instead. Primitive datatypes can cast e.g.:int <double-cast-int> = (int) <double-field>

Characters:

char : 16 bits. From \u0000 (0) to \uffff (65535). Default is \u0000. Can accept char codes e.g. char A = 65.

Boolean:

true and false. Default is false.

Non-primitive Datatypes

//TODO

Operators

Relational (Comparison):

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

= is assignment operator and == is equals to comparison operator.

Logical:

  • & - And (all are true)

  • | - Or (at least one is true)

  • ! - Not ()

  • ^ - Exclusive Or (only one is true)

& and | are exhaustive i.e., they evaluate all the operands. && and !! are non-exhaustive i.e., they evaluate till the first false or true, respectively.

Loops

for:

for (<init.>; <cond.>; <incr./decr.>)
{
...
}

while:

<init.>;
while (<cond.>) {
<incr./decr.>
}

do while:

<init.>;
do {
<incr./decr.>
} while (<cond.>);

Arrays

Data structure object holding like (homogeneous) elements. Has datatype and size. Initialized arrays hold 0 in all elements. Elements can be accessed using index. Index starts at 0. Array elements are stored sequentially in memory.

Classes and Objects

//TODO