Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a default type for numbers in Java

If I write something like this

System.out.println(18);

Which type has the '18'? Is it int or byte? Or doesn't it have a type yet?

It can't be int, because something like this is correct:

byte b = 3;

And this is incorrect:

int i = 3;
byte bb = i; //error!

EDIT: I think I found the right part in the spec at Assignment Conversion :

The compile-time narrowing of constants means that code such as:

byte theAnswer = 42;

is allowed. Without the narrowing, the fact that the integer literal 42 has type int would mean that a cast to byte would be required:

byte theAnswer = (byte) 42; // cast is permitted but not required

like image 425
colorblind Avatar asked Dec 03 '14 03:12

colorblind


2 Answers

This

18

is known as an integer literal. There are all sorts of literals, floating point, String, character, etc.

In the following,

byte b = 3;

the literal 3 is an integer literal. It's also a constant expression. And since Java can tell that 3 fits in a byte, it can safely apply a narrowing primitive conversion and store the result in a byte variable.

In this

int i = 3;
byte bb = i; //error!

the literal 3 is a constant expression, but the variable i is not. The compiler simply decides that i is not a constant expression and therefore doesn't go out of its way to figure out its value, a conversion to byte may lose information (how to convert 12345 to a byte?) and should therefore not be allowed. You can override this behavior by making i a constant variable

final int i = 3;
byte bb = i; // no error!

or by specifying an explicit cast

int i = 3;
byte bb = (byte) i; // no error!
like image 75
Sotirios Delimanolis Avatar answered Oct 06 '22 09:10

Sotirios Delimanolis


The JLS-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

And JLS-3.10.1 - Integer Literals

An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).

Finally, JLS-3.10.2 - Floating-Point Literals includes

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d (§4.2.3).

As for byte b = 3; it is a Narrowing Conversion from int to byte.

like image 25
Elliott Frisch Avatar answered Oct 06 '22 07:10

Elliott Frisch