Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why int[] a = new int[1] instead of just int a?

Tags:

java

integer

Is there some hidden meaning in this code which I don't see in java? How can it be useful?

int[] a = new int[1];

than just

int a;

because from my point of view it's the same?

like image 876
Sergey Avatar asked Jun 03 '11 02:06

Sergey


2 Answers

int a

defines a primitive int.

int[] a = new int[1];

defines an array that has space to hold 1 int.

They are two very different things. The primitive has no methods/properites on it, but an array has properties on it (length), and methods (specifically its on clone method, and all the methods of Object).

Arrays are a bit of a weird beast. They are defined in the JLS.

In practice, it would make sense to do this when you need to interact with an API that takes an array and operates on the results. It is perfectly valid to pass in a reference to an array with 0, 1, or n properties. There are probably other valid reasons to define an array with 1 element.

I can't think of any use cases where you would want to define an array with one element, just to bypass the array and get the element.

like image 95
hvgotcodes Avatar answered Nov 17 '22 22:11

hvgotcodes


One is on the stack, one is on the heap.

like image 7
user541686 Avatar answered Nov 17 '22 20:11

user541686