Instructor: Stefan Mitsch
struct Node { int value; Node* next; }
Node* getNext (Node* x) {
return x->next;
}
class Main () {
public static void main (String[] args) {
System.out.println( 1 - 2 );
System.out.println( "dog" - "cat" );
}
}
struct Node { int value; Node* next; }
Node* getNext (Node* x) {
return x->next;
}
#;> (- 5 "hello")
Error in -: expected type number, got '"hello"'.
f runs
#;> (define (f) (- 5 "hello"))
#;> (f)
Error in -: expected type number, got '"hello"'.
javac rejects code with (5 - "hello")
$ javac Typing01.java
Typing01.java:5: error: bad operand types for binary operator '-'
System.out.println ("Result = " + (a - b));
^
first type: int
second type: String
class Typing01 {
public static void main (String[] args) {
int a = 5;
String b = "hello";
System.out.println ("Result = " + (a - b));
}
}
$ java Typing01
ClassCastException: class String cannot be cast to class Integer
at Typing01.main(Typing01.java:5)
class Typing01 {
public static void main (String[] args) {
int a = 5;
String b = "hello";
System.out.println ("Result = " + (a - (int)(Object)b));
}
}
StaticLanguages
staticlanguages, variables also have types
$ javac Typing06.java
Typing06.java:4: error: incompatible types: String cannot be converted to int
a = "hello";
^
class Typing06 {
public static void main (String[] args) {
int a = 5;
a = "hello";
}
}
$ java Typing06
ClassCastException: class String cannot be cast to class Integer
at Typing06.main(Typing06.java:4)
class Typing06 {
public static void main (String[] args) {
int a = 5;
a = (int)(Object)"hello";
}
}
varvar
$ javac Typing06.java
Typing06.java:4: error: incompatible types: String cannot be converted to int
a = "hello";
^
class Typing06 {
public static void main (String[] args) {
var a = 5;
a = "hello";
}
}
DynamicLanguages
dynamiclanguages
#;> (define (main)
(define a 5)
(set! a "hello")
(display a)
)
#;> (main)
"hello"
int f (int i, String s) {
return true ? i : s;
}
var x = 1;