Variables and types
In Java you declare each variable's type and it can't change later. This is static typing, and it lets the compiler catch many mistakes before the program runs.
JAVA · inside main
int age = 21; double gpa = 4.5; String name = "Sara"; boolean isMis = true; char grade = 'A'; System.out.println(name + " " + age + " " + gpa + " " + isMis + " " + grade);
Output
Sara 21 4.5 true A
| int | whole number: 21 |
| double | decimal: 4.5 |
| String | text in " ": "Sara" |
| boolean | true or false |
| char | one character in ' ': 'A' |
Watch division: dividing two ints gives an int and drops the fraction. Cast one of them to double for a decimal result.
JAVA · inside main
int a = 7, b = 2; System.out.println(a / b); System.out.println(a % b); System.out.println((double) a / b); System.out.println(a + b + "!"); System.out.println("!" + a + b);
Output
3 1 3.5 9! !72
Watch out
+ is read left to right: a + b + "!" adds the numbers first (9!), while "!" + a + b turns everything into text from the start (!72).Same idea in both languages
Python
name = "Sara" age = 21 gpa = 4.5
Java
String name = "Sara"; int age = 21; double gpa = 4.5;