Essay
Learning Java, Part 2: Data Types and Operators
Study notes on Java's eight primitive types, literals, scope, arithmetic and logical operators, short-circuiting, widening and casting, and how expressions are promoted. Written entirely by an AI model.
Part 1 showed that every Java variable has a declared type. This part covers the basic types and the operators that work on them. Most surprises for Python programmers are here: integers that overflow, division that throws away the fraction, and characters that are numbers.
The eight primitive types
Java has eight primitive types. They hold a value directly rather than pointing at an object, and their sizes are fixed on every platform.
| Type | Size | Range or meaning | Literal |
|---|---|---|---|
byte |
8 bits | −128 to 127 | (byte) 7 |
short |
16 bits | about ±32,000 | (short) 7 |
int |
32 bits | about ±2.1 billion | 7 |
long |
64 bits | about ±9.2 × 10¹⁸ | 7L |
float |
32 bits | about 7 significant digits | 7.5f |
double |
64 bits | about 15 significant digits | 7.5 |
char |
16 bits | one UTF-16 code unit | 'A' |
boolean |
— | true or false |
true |
int and double are the defaults: a whole-number literal is an int and a literal with a decimal point is a double. Use long when values can pass two billion, such as milliseconds or populations.
Python integers grow without limit. Java’s do not. Going past the end wraps around silently:
public class Overflow {
public static void main(String[] args) {
int big = Integer.MAX_VALUE;
System.out.println(big);
System.out.println(big + 1); // wraps to the most negative int
long safe = big + 1L; // 1L makes the sum a long
System.out.println(safe);
System.out.println(Math.addExact(1, 2)); // throws on overflow instead
}
}
2147483647
-2147483648
2147483648
3
Math.addExact and Math.multiplyExact throw an ArithmeticException instead of wrapping, which is useful when overflow would be a bug.
Characters are numbers
A char holds a 16-bit code. You can do arithmetic on it, which is how many classic exercises shift letters:
public class Letters {
public static void main(String[] args) {
char c = 'A';
c++;
System.out.println(c);
System.out.println((int) 'a');
System.out.println((char) ('a' + 2));
System.out.println('a' + 'b'); // two chars add as numbers
}
}
B
97
c
195
Note the double quotes for strings ("A") and single quotes for characters ('A'). They are different types, and 'AB' does not compile.
boolean is not a number
boolean holds only true or false. Unlike Python, you cannot use 0, an empty string or null as false: if (count) is a compile error. Write if (count != 0).
Literals
- Underscores may group digits:
1_000_000. - Hexadecimal starts
0x(0xFFis 255), binary0b(0b1010is 10), and octal is a leading zero (017is 15). That last one is a trap:010is eight, not ten. - Escape sequences inside quotes:
\nnewline,\ttab,\"quote,\\backslash,\'single quote,\u00e9a Unicode character.
Modern Java. Text blocks (Java 15) write multi-line strings between triple quotes, """, the way Python does.
Scope and lifetime
A variable exists from its declaration to the end of the block (the braces) it was declared in. An inner block can see outer variables, but a variable declared inside a block disappears when the block ends.
public class Scope {
public static void main(String[] args) {
int outer = 1;
{
int inner = 2;
System.out.println(outer + inner);
}
// System.out.println(inner); // compile error: inner is out of scope
System.out.println(outer);
}
}
3
1
Two more rules differ from Python. You cannot declare an inner variable with the same name as an outer local one. And a local variable must be definitely assigned before it is read; the compiler rejects int x; System.out.println(x);.
Arithmetic
+ - * / % work as you expect, with one big exception: dividing two integers gives an integer, throwing the fraction away (rounding towards zero). Python’s / always gives a float; Java’s / follows the types of its operands.
public class Division {
public static void main(String[] args) {
System.out.println(7 / 2);
System.out.println(7 / 2.0);
System.out.println(-7 / 2); // towards zero, unlike Python's //
System.out.println(-7 % 2); // sign follows the left operand
System.out.println(7.5 % 2);
double avg = (3 + 4) / 2; // integer division happens first
System.out.println(avg);
}
}
3
3.5
-3
-1
1.5
3.0
The last case is a classic bug: the division is done in int and only then widened to double. Write (3 + 4) / 2.0 or cast one operand. Integer division by zero throws ArithmeticException, while double division by zero gives Infinity or NaN.
Increment and decrement
x++ and ++x both add one. The difference is only visible when the expression’s value is used: x++ gives the old value, ++x the new one.
public class Increment {
public static void main(String[] args) {
int x = 5;
int a = x++; // a gets 5, then x becomes 6
int b = ++x; // x becomes 7, then b gets 7
System.out.println(a + " " + b + " " + x);
}
}
5 7 7
Keep ++ on its own line in real code. Exam questions love the mixed form.
Relational and logical operators
The comparisons == != < <= > >= give a boolean. The logical operators are symbols, not words:
| Java | Python | Note |
|---|---|---|
&& |
and |
short-circuit |
|| |
or |
short-circuit |
! |
not |
|
& | |
— | evaluate both sides |
^ |
— | exclusive or |
Short-circuit operators skip the right side when the left already decides the answer. That makes guards like this safe:
public class Guard {
public static void main(String[] args) {
int people = 0;
int cakes = 6;
if (people != 0 && cakes / people > 1) {
System.out.println("plenty");
} else {
System.out.println("no division happened");
}
}
}
no division happened
With & instead of &&, the division would run and throw. Java has no comparison chaining: 0 < x < 10 does not compile. Write 0 < x && x < 10.
Assignment and shorthand
= assigns and is also an expression, so a = b = 0; sets both. The shorthand forms (+= -= *= /= %= and others) include a hidden cast back to the variable’s type:
public class Shorthand {
public static void main(String[] args) {
int total = 10;
total += 2.7; // allowed: means total = (int) (total + 2.7)
System.out.println(total);
// total = total + 2.7; // compile error: possible lossy conversion
}
}
12
Widening and casting
Java converts automatically when no information can be lost. This is called widening: byte → short → int → long → float → double, and char → int. Going the other way needs an explicit cast, which can lose information:
public class Casting {
public static void main(String[] args) {
long l = 42; // int widens to long
double d = l; // long widens to double
int i = (int) 9.99; // cast truncates
byte b = (byte) 300; // keeps only the low 8 bits
System.out.println(d + " " + i + " " + b);
System.out.println(Math.round(9.5) + " " + Math.round(-9.5));
}
}
42.0 9 44
10 -9
(int) chops towards zero; Math.round rounds halves up (towards positive infinity), which differs from Python’s round-half-to-even.
Promotion in expressions
Inside an expression, byte, short and char are promoted to int first. Then, if either operand is long, float or double, the other is promoted to match. That is why this fails:
byte a = 10, b = 20;
byte c = a + b; // compile error: a + b is an int
byte d = (byte) (a + b); // fine
Precedence
From high to low: postfix x++; unary ++x ! - and casts; * / %; + -; shifts; relational < >; equality == !=; &; ^; |; &&; ||; the ternary ?:; assignment. You don’t need to memorise all of it. Add parentheses whenever a reader might hesitate.
Exam-style checks
- What do
7 / 2,7 / 2.0and-7 / 2print, and why? - Why does
int x = Integer.MAX_VALUE + 1;compile, and what value does it hold? - Explain short-circuit evaluation with a two-line example where it prevents an exception.
- Why does
byte c = a + b;fail whenaandbare bothbyte? - Explain the difference between
x++and++xwith a three-line example.
Where to practise
Do Schildt’s Chapter 2 self test and the truth-table exercise, which prints the results of &, |, ^ and ! for every pair of inputs. In jshell, try every row of the division example with your own numbers until you can predict each result before pressing Enter.