0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Java】型変換時の注意点

Last updated at Posted at 2020-12-13

【概要】

JavaSilver範囲の型変換に関しての注意点についてです。

【説明】

変数に進数を使用するときの注意

まず進数について軽くおさらいをする。

  • 2進数: コンピュータの中では、0と1でデータを扱っている。
  • 10進数: 人間がよく使う0~9までの数字で表す
  • 16進数: カラーコードなどに使われる0~9 とA ~ F

以上を踏まえて下記のコードでかく変換の仕方をおさらいする。

10進数の「28」 を 2進数に変換する

28 / 2 = 14 余り 0
14 / 2 = 7 余り 0
7 / 2 = 3 余り 1
3 / 2 = 1 余り 1

★☆★☆★☆★☆★☆★☆★☆★★☆★☆★☆★☆★☆★☆

28 / 2 = 14 余り 0
14 / 2 = 7 余り 0    ↑
7 / 2 = 3 余り 1    ↑ 
3 / 2 = 1 余り 1    ↑
矢印のとおりに読む → → →

★☆★☆★☆★☆★☆★☆★☆★★☆★☆★☆★☆★☆★☆

// 2進数
11100 

2進数を10進数に変換する

2進数表記された値は、下記のように右のビットから1, 2, 4, 8, 16, 32, 64..と書いていき、ビットが「1」の箇所を合計する。

//以下の場合は「146」になる。
010010010 = 146

 0   1  0  0   1   0  0  1  0 
256 128 64 32  16  8  4  2  1 //上の値が「1」の箇所を探す
128 + 16 + 2 = 146 // 対応した値を合計する。

サンプルコード

byte型で2進数の変数e を出力しようとしますが、上記の理由によりコンパイルエラーになります。

public static void main(String[] args) {
        // 明示的なキャスト
        int a = 100;
        // short型に変換
        short b = (short) a;

        // byte 型は -128 ~ 127までの値を扱うデータ型なので、範囲を超えるとエラーとなる。
        // byte の範囲内のint型のリテラルのためcompile可能
        byte c = 127;
        // byte の範囲に収まらないint型のリテラルのためコンパイルエラー
        byte d = 128;
        // 10進数にすると256になるため、コンパイルエラー
        byte e = 0b10000000;

        System.out.println(e);
    }

long型のリテラルをInt型変数に代入【コンパイルエラー】

下記のように、long型のリテラルをInt型変数に代入することは出来ません。

public static void main(String[] args) {
        int f = 2 * 3L;

        System.out.println(f);
    }
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	型の不一致: long から int には変換できません

double型のリテラルをfloat型変数に代入【コンパイルエラー】

下記のように、double型の変数「g」にそれより小さな値しか使えないfloat型を代入しようとしているため、これもコンパイルエラーがおきます。

public static void main(String[] args) {
        float g = 10.0;

        System.out.println(g);
    }
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	型の不一致: double から float には変換できません

【まとめ】

試験対策としてこれらの挙動は把握しておくこと。

また、byteとshortは扱える範囲が狭いため、正確に範囲を覚えておくこと。

  • byteは -128 ~ 127
  • shortは 32768~32767

参考文献・記事

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?