typestar

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

  1. An int fits in a double, so that conversion happens silently.
  2. (int) 3.99 truncates to 3 — narrowing always asks for the cast.
  3. Integer.parseInt and Double.parseDouble read numbers from text.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Variables & types, step 2 of 29 in Language basics.

← Previous Next →

Numbers & casts in other languages