Java

Java Feature

Java Suites

JRE

JDK (Java Development Kit)

SDK (Software Development Kit)

Java EE (Enterprise Edition)

Set Environment Variables

e.g.

// Append a directory in front of the existing PATH
prompt> set PATH=d:\bin;%PATH%

Reference: http://www3.ntu.edu.sg/home/ehchua/programming/howto/environment_variables.html

Java Compilation & Execution

	javac <file-name>.java
	java <class-name>

Compilation is done by JVM which uses JDK libraries to check the syntax and compile the source file.

Execution is taken care by JRE Java Runtime Environment which loads the class on to memory for execution only when there is a main method in the class.

Primitive Datatypes

byte, 8 bit
short, 16 bit signed
int, 32 bit signed
long, 64 bit signed
float, 32 bit
double, 64 bit
boolean
char, 16 bit
Special case of String (technically not, but behaves like one)

Literals

11001100
true
1234
1.01
'a'
"hello"

Operators

postfix: expr++, expr--
unary: ++expr, --expr, +expr, -expr, ~, !
multiplicative: *, /, %
additive: +, -
shift: <<, >>, >>>
relational: <, >, <=, >=
equality: ==, !=
bitwise: &, ^, |
logical: &&, ||
ternary: ? :
assignment: =, +=, -=, *=, /=, &=, ^=, |=, <<=, >>=, >>>=
signed shift: keep the sign, use the most left digit in binary representation of a number as a filler
unsigned shift: always use zero as a filler

Control statements

if else then
switch
(do) while
for

Access specifiers / modifiers

Some Key Word

this

super

final

static

Static Variable

Static Method

non-static block

the block will be called when the class is initiated

class Test{
{...}
}

break

example of labeled break statement:

search:
	for (i = 0; i < arrayOfInts.length; i++) {
		for (j = 0; j < arrayOfInts[i].length;
			 j++) {
			if (arrayOfInts[i][j] == searchfor) {
				foundIt = true;
				break search;
			}
		}
	}

transient

Serialization

All the java objects are temporary for each JVM instance. if we need to store them in a file OR need to transfer over the network, they must be retained even after the JVM instance is dead. This reauires those java objects to have “persistence” property. This process of giving an object a persistence property is called as “Serialization”.

Inheritance

An object or class is based on another object or class, using the same implementation to maintain the same behavior. When a subclass is initiated, it needs to (invoke the superclass’s constructor to) create an instance of the superclass object When using inheritance, invoking a subclass will automatically load super class’s “no argument constructor” if no other super class’s “with argument constructor” is called

Encapsulation

packing of data and functions into a single component The features of encapsulation are supported using classes in most object-oriented programming languages.

Polymorphism

many: A reference variable can refer to any object of its declared type or any subtype of its declared type. It is the provision of a single interface to entities of different types.

One thing to notice when using polymorphism

e.g.

class A
class B extends A
A instance = new B();
instance.field -> A
instance.method() -> B

Exception

Checked Exception

Unchecked Exception

Exceptions that are not checked at compiled time such as err & runtime exception.

Exception Handing

After try catch, the program will continue to execute.

Throwed exception must be caught somewhere. A mehtod that throws exception must be surrounded by try-catch block.

public void sample() throws ArithmeticException{
  
  ...

  throw new ArithmeticException();
  
  ...
}

Generic

Generic Collection

List < String > strings = new ArrayList < String >();
strings.add("a String");
String aString = strings.get(0);

Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time.

Generic Method

specify, with a single method declaration, a set of related methods

public static < E > void printArray( E[] inputArray ){...}
...
printArray( intArray  ); // pass an Integer array
printArray( doubleArray ); // pass a Double array

Generic Class

specify, with a single class declaration, a set of related types.

// The < T > is a type token that signals that this class can have a type set when instantiated.
public class Box < T > {...}
...
Box < Integer > integerBox = new Box < Integer >();
Box < String > stringBox = new Box < String >();

Generic WildCard

a collection whose element type matches anything

// here you can pass a Collection< String > or Collection< Integer >
void printCollection(Collection<?> c) {
    for (Object e : c) {
        System.out.println(e);
    }
}

Bounded WildCard

restrict the kinds of unknown type

public void addRectangle(List<? extends Shape> shapes) {
    // Compile-time error!
    shapes.add(0, new Rectangle());
}

Bounded Type Parameters

restrict the kinds of types that are allowed to be passed to a type parameter

For example, a method that operates on numbers might only want to accept instances of Number or its subclasses.

// the maximun() can only accept types that extends Comparable
public static < T extends Comparable < T > > T maximum(T x, T y, T z){...}

Interfaces

can have only method signatures and fields & static final constants

interface Bicycle {
     static final int startSpped = 0;
     void speedUp(int increment);
     void changeGear(int newValue);
}

interface v.s. abstract class

// example of interface
interface DaoService {
	void add(...);
	void delete(...);
	void update(...);
	void findById(int id);
}

// example of abstract class
public abstract class RequestService() {
	void preService();
	void doService();
	void postService();
}
public class UserAlfaRequestService() {
	...
}
public class UserBetaRequestService() {
	...
}

mark interface

marker interface in Java is used to indicate something to compiler, JVM or any other tool but Annotation is better way of doing same thing. One example is Serialization.

Read more: http://javarevisited.blogspot.com/2012/01/what-is-marker-interfaces-in-java-and.html#ixzz3bxihc6nj

Classes

Anonymous class

create a class without naming the class

// class
new ServiceImpl().doSomething();  // ServiceImpl is a Class

// interface
Arrays.sort(input[], new Comparator<Integer>() {  // anonymous class
    @Override
    public int compare(int a, int b) {
        return (a-b);
    }
});

Inner classes

class inside class

// example
< outer-class-object >.new < inner-class-name >().< inner-class-member-function >();

Abstract class

implemented in subclasses

public abstract class GraphicObject {
     ...
     // declare fields
     // declare nonabstract methods

     abstract void draw();

     void changeBrush(){
          ...
     }
}

Concrete class

has ALL its methods implemented

Coding Standards

Advenced Topic

Java 8

Fork me on GitHub