1

I'm currently trying to get my head around a piece of code that I found. Firstly, I'm not sure why the code appears like:

byte z[] = new byte[5];

instead of:

byte[] z = new byte[5];

I mean, is byte z[] not there to declare an array of bytes? Or is this code doing something else?

Secondly, why would someone choose bytes over doubles or ints. It seems that a byte is any number from -128 to 127. What's the point in choosing that over a double?

Zetland
  • 569
  • 2
  • 11
  • 25
  • http://stackoverflow.com/questions/2229602/is-there-any-difference-between-object-x-and-object-x – assylias Apr 14 '15 at 15:52
  • 3
    *What's the point in choosing that over a double?* To consume **less memory**. each data type takes some memory. [Read more about it](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html). – Braj Apr 14 '15 at 15:53
  • 1
    It's better to ask two questions when they are entirely unrelated. Otherwise your asking people to answer two questions. – weston Apr 14 '15 at 15:56
  • It also depends what you want to do with the values. If you are doing bitwise operations for example you would not want to use `double`. – Paul Boddington Apr 14 '15 at 15:57

2 Answers2

3

byte[] z is equivalent to byte z[] are just two different methods of represent the same.

Note that the java code conventions of sun (before becoming Oracle) propose to use the first over the second. So it preferreable to use

byte[] z = new byte[5];

instead of

byte z[] = new byte[5];

For the second part of your question.

byte uses 1 byte
char uses 2 bytes
int  uses 4 bytes
long uses 8 bytes

So the best is to use the smallest numeric type to avoid memory occupancy.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
0

For the array declaration: Java supports c-style array declaration aswell as it's own way that is usually used. byte[] z is equivalent to byte z[]. byte takes less memory than double and int and provides better performance than bigger datatypes (especially better than double).

  • "and provides better performance than bigger datatypes." Source? – resueman Apr 14 '15 at 15:55
  • addition is always faster, the smaller the datatype. simply due to the way adders are built, due to the fact that smaller amounts of data need to be loaded, etc.. I won't search a source for something **that** obvious. –  Apr 14 '15 at 15:58
  • 1
    [This answer](http://stackoverflow.com/a/5069643/2499035) says that operations on the CPU's native word size tend to be faster than other sizes, which is the opposite of your claim. – resueman Apr 14 '15 at 16:03