6

1l for long, 1f for float, 1d for double, what about byte?

long l = 1l;
float f = 1f;
double d = 1d;
// byte b = 1?;

What's the equivalent for byte? Does it exist?

Roman C
  • 49,761
  • 33
  • 66
  • 176
sp00m
  • 47,968
  • 31
  • 142
  • 252

4 Answers4

7

No, there is no suffix you can append to a numeric literal to make it a byte.

See 3.10 Literals in the Java Language Specification.

Jesper
  • 202,709
  • 46
  • 318
  • 350
4

You need to cast to byte like this:

byte b = 1;

b = (byte) 5;

Since by default these numeric constant are treated as int in Java.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Except that it is not necessary in this case, because the literal is a compile-time constant. `byte b = 1;` is perfectly legal. – Jesper Mar 29 '13 at 10:53
  • 2
    yes, `byte b=1` works fine, unfortunately for every other operation but the initialization the cast is again necessary. Even the seemingly harmless `b+=1`. I understand that this must be like this, it's just... annoying to cast everytime – GameDroids Mar 29 '13 at 10:57
1

there is no suffix you can append a numeric literal

Anthon
  • 69,918
  • 32
  • 186
  • 246
PSR
  • 39,804
  • 41
  • 111
  • 151
1

There is no such suffix for bytes, see the Java Language Specification section 3.10.1:

DecimalIntegerLiteral:
    DecimalNumeral IntegerTypeSuffix(opt)

IntegerTypeSuffix: one of
    l L

Note (opt) signifies it is optional. So to assign you need to explicitly cast using (byte) 1.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197