LoginSignup
2
0

More than 3 years have passed since last update.

【Java】型の変換時にエラったので調べた。<キャスト演算子>

Last updated at Posted at 2019-05-17

はじめに

自分の学習メモ。

オブジェクト指向を理解しようとして、ババ抜きを作成中。
その中にこのような記述が

int pos;
pos = (int) (Math.random() * number);

(int)(Math.random() * number);ってなんだ。ってなりました。
pos = Math.random() * numberは無理なのかと思いトライしてみると案の定エラー

調べてみた

結論から言えば、「キャスト演算子」というものでおそらく基礎なんだろうけど読み飛ばしていたのか。。

データ型の違うものを代入しようとしたときに発生するエラーを防いでくれるもの!

具体的にはこう書いてました。

サイズが大きい型から小さい型への変換など必ずキャスト演算子を使ってデータ型を変換する必要がある

ここでいう大きいサイズとは、「ビット数」のことを指してます。

データ型 意味 サイズ
byte 整数 8bit
short 整数 16bit
int 整数 32bit
long 整数 64bit
float 浮動点小数点 32bit
double 浮動点小数点 64bit
char 1文字 16bit
boolean 真偽値 1bit

〜追記〜

→暗黙型変換

byte short/char int long float double

←キャストによる型変換

double(64bit) -> int(32bit)で表現するときには
(大きい)→(小さい)なので、明示的に書いてあげないといけない。

int pos;
pos = (int) (Math.random() * number);
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0