Java is a statically-typed language
# Python function declared with type hints
def hello(name: str)->str:
return 'Hi, ' + n
Math.sin(30, 20)
Math.sin("30")
null
object referenceStatic checking can detect errors related to type of a variables. Static checking guarantees that a variable will have some value from its type, but we don’t know until runtime exactly which value it has. So if the error would be caused by certain values, like divided-by-zero or index-out-of-range, then the compiler won’t raise a static error about it
int x = 5 / 2;
or double y = 5 / 2
will not return a fraction, it returns a truncated integer 2
and 2.0
=> wrong answers, no errorsdouble
that you’d expect to produce dynamic errors, like dividing by zero or taking square root of a negative number, you will get one of these special values instead -> bad final answersint n = - 5;
if (n) {
System.out.println("n is a positive number");
}
answer: static error, because if
statement requires an expression of boolean
type, but n
has int
type. Changing the code to if (n > 0) ...
would fix it
2.
int big = 200000;
big = big * big; // 40 bn now
answer: no error, wrong answer, this is an integer overflow, because an int
value can’t represent a number bigger than 2^31 (2 bn), it isn’t caught statically and caught dynamically, it overflows quietly produce the wrong answer
3.
double x = 5.0 / 2; // x = 2.5
double y = 5 / 2; // y = 2.0
int sum = 0;
int n = 0;
int avg = sum / n;
answer: dynamic error, divided-by-zero
double sum = 7;
double n = 0;
double avg = sum / n;
answer: no error, but wrong answer, division by zero can’t produce a real number either, but double has a special value for POSITIVE_INFINITY
, so that’s what it returns when you divide a positive integer by zero
sqrt()
can handle numbers with fractional parts
arrays are fixed-length sequences of types
int[] a = new int[100]
a[2]
a[2] = 0;
a.length
lists are variable-length sequences of another type
List< Integer> list = new ArrayList< Integer>();
list.get(2)
list.set(2, 0)
list.size()
List
is an interface, a type that can’t be constructed directly, but that instead just specifies the operations that a List
must provide.
ArrayList
is a class, a concrete type that provides implementations of those oeprations
final int n = 5;
final
variable will only be assigned once at runtime, then it will produce a compiler error => final
gives you static checking for unreassignable referencesList< Integer> list
a final
Programs have to be written with two goals in mind: