Java notes #
Hello World #
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!!!");
}
}
Import #
import com.compamy.somepackage.Name; // imports only specified package
import com.compamy.somepackage.*; // imports each class in this package,
// BUT don't import classes in subpackages
Infrastructure #
JRE = JVM + SE Libs
JDK = JRE + DevTools
Data types #
Elementary (simple) data types:
- Integer
- byte (8 bit, -2^7…2^7-1)
- short (16 bit, -2^15…2^15-1)
- int (32 bit, -2^31…2^31-1)
- long (64 bit, -2^63…2^63-1)
- Float
- float (32 bit, 1.4e-45…3.4e+38)
- double (64 bit, 4.9e-324…1.8e+308)
- Symbol
- char (16 bit)
- Boolean
- boolean
- true
- false
- boolean
Flow control #
if (a > b) {
...
} else {
...
}
If we skip curly brackets, “else” owns only first following expression.
Type conversion #
a + b = result
if a || b is double:
result is double
else if a || b is float:
result is float
else if a || b is long:
result is long
else:
result is int
Referencing subclass objects #
Let’s define few example classes:
class SuperClass {
...
}
class SubClassOne extends SuperClass {
...
}
class SubClassTwo extends SuperClass {
...
}
There are two ways to refer to a subclass object:
- Subclass reference:
SubClassOne varOne = new SubClassOne();
SubClassTwo varTwo = new SubClassTwo();
- Superclass reference:
SuperClass varOne = new SubClassOne();
SuperClass varTwo = new SubClassTwo();
- We cannot assign an object of one subclass to the reference of another subclass because they don’t inherit each other:
SubClassOne varOne = new SubClassTwo(); // Error!!1!
- We cannot assign an object of the parent class to the reference of int subclass:
SubClassOne varOne = new SuperClass(); // Error!!1!
Polymorphism #
Polymorphism means that something (an object or another entity) has many forms.
Java provides two types of polymorphism:
- static (compile-time; achieved by method overloading)
- dynamic (run-time; based on inheritance and method overriding)
Method overriding is when a subclass redefines a method of the superclass with the same name.
The run-time polymorphism relies on two principles:
- a reference variable of the superclass can refer to any subtype object;
- a superclass method can be overridden in a subclass.