Javaで数値を扱ううえで重要な点の1つは、整数(小数点以下の桁がない数値)と浮動小数点数(小数点以下の桁が0個以上ある数値)の区別です。
Javaには、intとdoubleのほかにもデータ型があります。
// 8-Bit Integer
byte a = 127;
// 16-Bit Integer
short b = 262143;
// 64-Bit Integer
long d = 18446744073709551999L;
// 32-bit Single-Precision Floating-Point
float e = 5409.29f;
整数も浮動小数点数も、_を_桁区切り_として使えます。大きな数値を定義するときに役立ちます。
int largeInt = 1_000_000;
// => 1000000
double largeDouble = 9_876_543.21;
// => 9876543.21
計算には、標準の算術演算子(+、-、*など)を使います。
数値は、標準の比較演算子(<、>=など)に加えて、等価演算子(==)や不等価演算子(!=)を使って比較できます。
5 * 6
// => 30
1.2 > 0.8
// => true
120 == 100
// => false
2 != 4
// => true
数値型の間で変換するとき、型変換には2種類あります。
intはdoubleよりも精度が低いため、intからdoubleへの変換は安全で、暗黙の型変換になります。
一方、doubleからintへの変換ではデータが失われる可能性があるため、明示的な型変換が必要です。
int i = 9;
double d = 2.72;
// Safe conversion, thus implicit conversion
double fromInt = i;
// Potentially unsafe conversion, thus explicit conversion
int fromDouble = (int)d;