Page 1 of 12
Java Platform and Compilation
flowchart LR
Source -- Compiler --> Output(Byte code) --JRE/Platform Independent--> Runtime
Output(Byte code) -- Platform dependent --> Platform dependent OS
- Source code is compiled to byte code.
- Platform Independent: Runs on JRE.
- Platform Dependent: Runs on specific OS.
flowchart TD
class -- contains statements --> JVM
class -- contains statements --> Library Classes
JVM & Library Classes --> JRE
JDK --> JRE + Development tools
flowchart TD
ClassLoader --> ByteCodeVerifier --> Interpreter --> Runtime --> Hardware
hardware→ Hardware- Runtime includes Class Loader, Byte Code Verifier, Interpreter, Runtime, and Hardware.
Object-Oriented Design (Objectville)
When designing a class:
- Think about the objects that will be created from that class type. Think about:
- Things object knows → instance variables
- Things object does → methods
Example:
- Shopping cart
- It knows content
- class addToCart()
- removeFromCart()
- It knows content
Page 2 of 12
Example: Television Object
- It knows channel locations
- class changeChannel()
- changeVolume()
- class changeChannel()
Class vs Object
- A class is a blueprint for an object.
- It tells the VM how to make an object of that particular type.
- Object, on the other hand, is like one entry in your address book.
Variables
Variables know about their nature:
flowchart LR
Variable -- Points to --> Object Reference
- Used as:
- Instance variables
- Local variables
- Arguments
- Return types
Primitive Types
| Type | Size |
|---|---|
| byte | 8 bit |
| short | 16 bit |
| int | 32 bit |
| long | 64 bit |
| float | 32 bit |
| double | 64 bit |
| char | 16 bit |
| boolean | 1 bit |
Object Reference
- There is nothing like object variable, only references.
Page 3 of 12
Garbage Collection
flowchart LR
Ref1 --> Obj1
Ref2 -.-> Obj1
Ref2 --> null
Obj1 --> Heap
- If an object is not referenced, it goes to garbage.
- Ref2 = null, but Obj1 is not null.
Encapsulation
- Always make
getters→ getters as public & setters. - Make instance variables as private.
Instance Variables (Default Values)
- integer: 0
- float: 0.0
- boolean: false
- Reference: null
- Local variables are declared within a method.
- Local variables must be initialized before use.
- Method parameters are also local.
Page 4 of 12
Comparing Variables
- Pointers:
== - References:
== - Objects:
.equals()
Example:
byte a = 3;
int b = 3;
a = b; // true
Inheritance
flowchart TD
b --> a
- Use inheritance when one class is a more specific type of a superclass.
- Use when you have behavior to be shared among multiple classes of the same type.
- Do NOT use just to reuse code from another class—an "is-a" test must be passed.
Polymorphism
Can make polymorphic arrays:
Animal[] anim = new Animal[5];
anim[0] = new Dog();
anim[1] = new Wolf();
Can have polymorphic arguments & return types:
class Vet {
public void giveShot(Animal a) {
a.makeNoise();
}
}
Example usage:
Vet v = new Vet();
Dog d = new Dog();
Hippo h = new Hippo();
v.giveShot(d);
v.giveShot(h);
Page 5 of 12
- Just remember, you can point superclass references to the reference of a subclass object.
Method Overriding
- Arguments must be the same & return types must be compatible.
- The method can't be less accessible.
Method Overloading
- Arguments change
on their→ in their data type. - Only return type can't do overloading.
- Access levels can be varied.
Serious Polymorphism
One requirement in certain design patterns is not to create parent class objects; this behavior can be achieved using abstract classes.
abstract class <class-name> {
// abstract class definition
}
Animal a = new Dog(); // ✓
Animal o = new Animal(); // ✗
Page 6 of 12
- Concrete class, on other hand, is not abstract.
- Abstract class has no use, no value, only can be extended or have static members (later).
- Methods can be abstract too, only possible inside abstract class.
- It has no body.
public abstract void eat();
- It might not look that it has some purpose, but it allows for a set of protocols.
- They need to be implemented by first concrete class, or maybe by an abstract class (not mandatory).
Class Object
- It is the superclass of everything.
- Every class
not→ that doesn't extend it explicitly, extends it indirectly.
What's in the Object Class?
equals(Object o)hashCode()getClass()toString()- and many more.
Page 7 of 12
- It can be used to:
- Act as polymorphic type for methods.
- Provide real methods/code that all objects in Java need at runtime.
- Thread related (later).
Example
Object o = new Dog();
o.bark(); // X, not possible
Because there is confusion since object is superclass of everything.
classDiagram
Object <|-- Dog
Dog : bark()
Dog : eat()
Dog : toString()
Dog d = new Dog();
Object o = d;
classDiagram
Object <|-- Dog
DogObj <|-- Dog
Casting can be done for sure:
Dog d1 = (Dog) getObject();
"instanceof" operator is helpful.
Page 8 of 12
Interfaces (100% pure abstract class)
public interface Pet {
public abstract void beFriendly(); // not required (implicit)
}
How to Decide?
- Make a class that doesn't extend anything when your new class doesn't pass the ISA test for any other type.
- Make a subclass only when you need to make a more specific version of a class & need to override or add new behavior.
- Use an abstract class when you want to define a template for a group of subclasses.
- Use an interface when you want to define a role that other classes can play, regardless of where those classes are in the inheritance tree.
Page 9 of 12
Garbage Collection (& Constructors)
flowchart TD
Stack --> Heap
main --> Dog --> Animal --> Object
Heap -.-> "so-called garbage collectable heap"
- (Constructor Chaining)
- Either write
super(args)explicitly on first line of constructor or do nothing. this()is used to call other constructors. Note: super() & this() can't exist together in a constructor. this() must be the first line.- Life & the entirety of a variable's living scope: currently on top of stack frame.
static & final
- Static variables are stored among all instances of the class.
- Static methods make use of static variables, can be called without creating an object.
- Also, they can't access non-static methods.
Page 10 of 12
static final
- global constant (
final) - Needs to be initialized at the time of declaration or static initializer must be used.
static final int CONST = 3;
-
Final variable can't change its value.
-
Final method can't be overridden.
-
Final class can't be extended.
-
Private constructor means no object can be created.
MULTI-THREADING
- Thread t1 = new Thread();
- t1.start();
If it has no job: 😞
Each thread has a separate call stack.
flowchart LR
MainThread[Main thread] --> baz()
MainThread --> bar()
MainThread --> foo()
MainThread --> main()
AnotherThread[Another thread] --> doMore()
AnotherThread --> go()
AnotherThread --> doStuff()
AnotherThread --> sum()
Page 11 of 12
Launching a Thread with a Job
Runnable threadJob = new MyRunnable();
Thread t = new Thread(threadJob);
t.start();
class MyRunnable implements Runnable {
public void run() {
// code
}
}
stateDiagram-v2
[*] --> Runnable
Runnable --> Running
Running --> Dead
Running --> Blocked : sleep/wait for input
Blocked --> Running
-
Life of a Thread
-
Thread Scheduler decides what to do, but there is a sleep() method.
Thread.sleep(milliseconds); // must be wrapped in try/catch
-
t.setName(String), Thread.currentThread().getName();
-
synchronizedkeyword helps in creating locks on an object method, but lock is obtained on object. -
If there are two synchronized methods, a key is needed by thread to enter any of them.
Page 12 of 12
- Every object has a single lock, with a single key for that lock.
- Even if object has more than one synchronized method, there is still one key.
Deadlock
flowchart LR
obj1 -- lock --> t1
obj2 -- lock --> t2
t1 -- waiting for obj2: xyz() --> obj2
t2 -- waiting for obj1: alpha() --> obj1
- If t1 has lock on obj1 because of obj1.foo() method, and t2 has lock on obj2 because of obj2.bar() method, both are waiting for each other's resources.
- All foo, bar, xyz, alpha are synchronized.
- There are two objects.
- Java doesn't have deadlock preventing mechanism, so it's all up to the design by programmer.
References & Related Topics
- Java Documentation
- "Head First Java" by Kathy Sierra & Bert Bates
- Effective Java by Joshua Bloch
- Related: OOP Principles, JVM Internals, Java Concurrency, Design Patterns