mrdaliri
mrdaliri

Reputation: 7358

narrow casting int to smaller types

If every operand in assignment and mathematical operations, before the expression performed, promote to int (if it doesn't have L, f, d flags);

And putting an int into a smaller primitive type (such as byte) should be done with narrow-casting;

So how the following assignment works?

byte a = 100;

If 100 is an integer, so putting it into a byte needs casting.

Upvotes: 4

Views: 452

Answers (3)

Radiodef
Radiodef

Reputation: 37875

byte a = 100;

This works because...

If the right-hand side in an assignment context is a constant expression,

A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

Where

Literals of primitive type [...]

are a constant expression.

And the range of a byte is

[...] from -128 to 127, inclusive.

Upvotes: 2

dReAmEr
dReAmEr

Reputation: 7196

byte a = 100; 

This works because byte range in java is from-128 to 127,so if you assign value upto 127,there is no need for cast.

Try to assign 128,you will get compiler error.

byte a = 128 ; //compiler error(incompatible type)
byte a = (byte)128;

Upvotes: 2

It's a compile-time constant, and the compiler can determine that it'll fit in a byte. This actually did require a narrowing conversion in older versions of Java.

Upvotes: 1

Related Questions