ExpressionsDynamicallyTypedDRAFT
In general, one has to evaluate an expression (or at least some parts of it) to figure out the type of the expression. E.g., the type of Math.sin(x)*a
may depend on the values of x
and a
, or the type of c?s:t
may depend on the values of c
, s
, and/or t
.
One has to evaluate an expression to determine its type
The type of expressions is determined, without evaluation, at compile time
CorrectionHere is what's right.
Java is a statically typed language, which means that one can determine the types of everything statically—without executing (without evaluating).
You can determine the type of any expression without knowing the values of the variables it uses, or the bodies of the methods it invokes. You can just look at the declared types of the variables and the signatures of the methods.
Examples
Math.sin(x) * a
Given class Math { public static double sin(double v) {...} }
and given double x
and int a
,
we can statically determine the type of the expression Math.sin(x)*a
.
We know that Math.sin
returns a double
.
So we will have to multiply a double
with an int
,
which means the int
is first converted to a double
,
and then two double
s are multiplied, resulting in a double
.
Thus, no matter what the values of x
and a
are,
and no matter what the sin
method does internally,
the type of the above expression is double
.
c ? s : t
Assuming c
is of type boolean
, and s
and t
are of type String
,
the entire expression has type String
.
We don’t need to know the value of c
to determine the type of c ? s : t
.
Java enforces that the types of s
and t
are the same,
and thus we do not need to know whether c
is true
or false
to determine the type of the expression.
It’s going to be String
no matter what.
OriginWhere could this misconception come from?
Students may have some familiarity with dynamically typed languages like Python or JavaScript.
ValueHow can you build on this misconception?
This misconception is valuable when introducing the students to other, dynamically typed, programming languages.