简体   繁体   中英

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?

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.

Array subscripts and sizes in Java must always be int , so in this expression new long[N] the N is converted to int , and because long has wider range than int , it's a narrowing conversion which must be done explicitly: new long[(int) N] . Or just read N as int : int N = s.nextInt() .

long[] arr = new long[N];

In this line you are creating an array of size N, but array sizes in Java can only be integers, that's why it's reading N as an int, if your intent is creating an array of N size you should read N as an int

int N = s.nextInt();

The maximum length of an array in java is 2,147,483,647 (2^31 - 1) which is the maximum length of int. So implicitly an array can have maximum the value of an int. So it cannot accept a long number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM