Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring long[] array in java

Can anyone tell me why cant i declare array like this?

long[] powers = { 0, 0, 1, 7, 35, 155, 651, 2667, 10795, 43435,
                174251, 698027, 2794155, 11180715, 44731051, 178940587,
                715795115, 2863245995, 11453115051, 45812722347, 183251413675,
                733006703275, 2932028910251, 11728119835307, 46912487729835,
                187649967696555, 750599904340651, 3002399684471467};

Compiler says that the literal of type int is out of range. I also tried to to cast it to long like this

long[] powers = { 0, 0, 1, 7, 35, 155, 651, 2667, 10795, 43435,
                174251, 698027, 2794155, 11180715, 44731051, 178940587,
                715795115, (long)2863245995, (long)11453115051, (long)45812722347, etc ...

but nothing changed also tried someting like this Long.valueOf(x) where x is number whitch compiler has problem with.

Any ideas?

Thanks in advance

like image 942
Yetti Avatar asked Nov 24 '13 13:11

Yetti


People also ask

What is long [] in Java?

The Java long keyword is a primitive data type. It is used to declare variables. It can also be used with methods. It can hold a 64-bit two's complement integer.

Can we declare long array in Java?

You cannot, by virtue of the fact that arrays are int-indexed.

How do I add a long array in Java?

Create an ArrayList with the original array, using asList() method. Simply add the required element in the list using add() method. Convert the list to an array using toArray() method.

What is array [] in Java?

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.


1 Answers

Plain number is considered as int in java. Append L which are bigger than Integer.MAX_VALUE to convert long.

long[] powers = {..., 2863245995L, 11453115051L, ...};

According to docs

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.

The suffix L is preferred, because the letter l (ell) is often hard to distinguish from the digit 1 (one).

like image 148
Masudul Avatar answered Sep 20 '22 07:09

Masudul