Comet copies a Java line into her sketch notebook and frowns. "Why does Java write int before grams? Python never makes me do that."
Wren taps a line on Nova's projection. "What do you notice? Every line inside main ends with a semicolon, too."
Nova splits the view again. "How can I help?" she asks. "In Java, every variable is declared, with its type, before it is used. Try dividing seven grams into two parts in both languages."
Comet grins. "Easy. It is three and a half."
Wren raises an eyebrow. "Maybe. Let us look at the evidence first."
Java is statically typed. Every variable is declared, with its type, before it is used.
int is one of eight primitive types in Java. String and boolean are two more types you will see today.
A Java statement ends with a semicolon. A block is statements between curly braces, where Python uses indentation.
// Types.java
public class Types {
public static void main(String[] args) {
int grams = 7;
int parts = 2;
String label = "S04";
boolean heavy = grams >= 50;
System.out.println(grams / parts);
System.out.println(label + " heavy: " + heavy);
}
} # type_demo.py grams = 7 parts = 2 label = "S04" heavy = grams >= 50 print(grams / parts) print(grams // parts) print(label + " heavy: " + str(heavy))
Java output, then Python output:
3 S04 heavy: false
3.5 3 S04 heavy: False
| Python line | Java line |
|---|---|
| grams = 7 | int grams = 7; |
| label = "S04" | String label = "S04"; |
| heavy = grams >= 50 | boolean heavy = grams >= 50; |
| print(grams // parts) | System.out.println(grams / parts); |
A Java String is a sequence of characters. A String object cannot be changed once it is made.
In both languages, + joins text. Java's println printed heavy as false without any help. Python needed str(heavy) to join it to the text.
# type_demo.py (str removed) grams = 7 parts = 2 label = "S04" heavy = grams >= 50 print(grams / parts) print(grams // parts) print(label + " heavy: " + heavy)
3.5
3
Traceback (most recent call last):
File "type_demo.py", line 8, in <module>
print(label + " heavy: " + heavy)
~~~~~~~~~~~~~~~~~~~^~~~~~~
TypeError: can only concatenate str (not "bool") to str | Statement | True or false? |
|---|---|
| In Java, a variable is declared with its type before it is used. | ? |
| int is one of eight primitive types in Java. | ? |
| A Java String can be changed letter by letter after it is made. | ? |
| Python uses curly braces to group a block. | ? |
| In the runs above, Java's 7 / 2 with two ints printed 3. | ? |
Types and semicolons are no longer a mystery, lead programmer. Tomorrow you will read the Sample class in Java.