Search code examples
javaintlong-integer

Java converts long to int


The following code:

 import java.util.*;

 public class HelloWorld{

 public static void main(String []args){

    Scanner s = new Scanner(System.in);
    
    long N = s.nextLong();
    long[] arr = new long[N];
    
    System.out.println(N);
    
 }
}

Getting this error:

HelloWorld.java:12: error: incompatible types: possible lossy conversion from long to int long[] arr = new long[N];

As far as I understand there is no int involved in the code, can anyone explain why this is happening and how to solve this issue?


Solution

  • The size of arrays in Java can not exceed the range of an int, so the size parameter for array creation is implicitly an int. Change N to an int.

    From JLS 15.10.1 Array Creation Expression (emphasis mine):

    Each dimension expression undergoes unary numeric promotion (§5.6.1). The promoted type must be int, or a compile-time error occurs.