Rishabh Agarwal
Rishabh Agarwal

Reputation: 1

How to declare array to type long in java?

I am trying to execute this code:

long n = in.nextLong();
    long k = in.nextLong();
    long[][] arr = new long[n][2];

But the is Compiler showing this error-

Main.java:9: error: incompatible types: possible lossy conversion from long to int


long[][] arr = new long[n][2];

Can someone explain why this is happening?

Upvotes: 0

Views: 2245

Answers (4)

irfan
irfan

Reputation: 896

array index is always int and you are trying to assign long to index hence the error, long has 8 bytes while int has 4 bytes so if you try to covert long to int then there may be chance of loss of precision and compiler won't allow this. By default any digit value is treated as int in java, use int value for array index , in your code simple type casting should work try

long[][] arr= new long [(int)n][2];

Upvotes: 0

ashish2199
ashish2199

Reputation: 393

Arrays use integers as indexes. So the long is converted to int in order to be used as index. Hence the error being shown as you could have input something larger than what a int can hold which on conversion to int would cause loss of information.

Main.java:9: error: incompatible types: possible lossy conversion from long to int

Also since you cannot create a array large enough that it is beyond the range of int to index it so int were chosen as datatype to index arrays.

Upvotes: 0

owmasch
owmasch

Reputation: 69

The error you are getting is because you're trying to use a long as an integer. The indices of arrays are always integers. Java prevents you from converting from long to int because you are removing 32-bits of information.

Upvotes: 2

Bill the Lizard
Bill the Lizard

Reputation: 405775

In new long[n][2], both n and 2 are array dimension sizes, so they should be type int, not long. Even if the array itself holds long values.

Change your first line of code to

int n = in.nextInt();

Upvotes: 3

Related Questions