Numbers & casts in Java
Widening is automatic, narrowing needs a cast, and longs wear an L.
int count = 42;
double precise = count; // widening happens on its own
int back = (int) 3.99; // narrowing needs a cast, and truncates
long big = 7_000_000_000L; // underscores keep long literals readable
int parsed = Integer.parseInt("123");
double half = Double.parseDouble("2.5");
System.out.println(precise + " " + back + " " + big);
System.out.println((parsed + 1) + " and " + (half * 2));
How it works
- An
intfits in adouble, so that conversion happens silently. (int) 3.99truncates to 3 — narrowing always asks for the cast.Integer.parseIntandDouble.parseDoubleread numbers from text.
Keywords and builtins used here
doubleintlong
The run, in numbers
- Lines
- 9
- Characters to type
- 417
- Tokens
- 92
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 61 seconds.
Step 2 of 3 in Variables & types, step 2 of 29 in Language basics.