電子書籍の厳選無料作品が豊富!

教えてください。

次のプログラムの出力は「2」になるんですがイマイチ解釈できません。

分かりやすい説明などあればご教授願います。

class NarrowingConversion{

public static void main (String[] args){

byte b;
int i = 258;
b = (byte)i;

System.out.println(b);

}

}

よろしくお願いいたします。

A 回答 (1件)

Javaの仕様でそうなると決まっているから。

自分で仕様を読みに行く、以外で分かる方法はなく、自分だけで考えようとしてもわかるはずがない。

どう決まっているかというと

http://java.sun.com/docs/books/jls/third_edition …

>5.5 Casting Conversion

>Casting conversion is applied to the operand of a cast operator (§15.16): the type of the operand expression must be converted to the type explicitly named by the cast operator. Casting contexts allow the use of:

>A value of a primitive type can be cast to another primitive type by identity conversion, if the types are the same, or by a widening primitive conversion or a narrowing primitive conversion.

narrowing primitive conversionにある方法を使え、ってんで、後から見に行くと

http://java.sun.com/docs/books/jls/third_edition …

>5.1.3 Narrowing Primitive Conversions
>The following 22 specific conversions on primitive types are called the narrowing primitive conversions:
(中略)
>int to byte, short, or char

>The following 22 specific conversions on primitive types are called the narrowing primitive conversions:

>A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

符号付き整数から、汎整数型(integral type)Tへの縮小変換は、単に低い方nビットを捨てる。なお、nは型Tを表現するのに必要なビット数とする。その値の大きさに関する情報の欠落に加え、この変換は、結果の値の符号が入力値と異なるものになることがある。

http://java.sun.com/docs/books/jls/third_edition …

>4.2 Primitive Types and Values

(略)

>The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing UTF-16 code units (§3.1).

byteは8bitで、int型は16bit。258は00000001 00000010で表されるから
00000010だけが残る。これは整数の2だ。

だから同様に

http://ideone.com/NqWmg

ね、-1になったでしょ?「書いてある通り」

==============
ちなみに、Integral Typeとは
http://java.sun.com/docs/books/jls/third_edition …

>4.2.1 Integral Types and Values
The values of the integral types are integers in the following ranges:

For byte, from -128 to 127, inclusive
For short, from -32768 to 32767, inclusive
For int, from -2147483648 to 2147483647, inclusive
For long, from -9223372036854775808 to 9223372036854775807, inclusive
For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535
「java 初心者ですが・・・・」の回答画像1
    • good
    • 0
この回答へのお礼

とても丁寧な説明をありがとうございます。
分かりやすかったですよ!

これからも精進して参りますのでよろしくお願いいたします。

お礼日時:2011/05/24 21:53

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!