Int for long parsing error

  class Test{  
    static void testCase_1(long l){System.out.println("Long");}  
    static void testCase_2(Long l){System.out.println("Long");}

    public static void main(String args[]){  
        int a = 30; 

        testCase_1(a);  // Working fine
        testCase_2(a);  // Compilation time error

        //Exception - The method testCase_2(Long) in the type Test is not applicable for the arguments (int)
      }   
    } 

testCase - 1: int - long working fine

testCase - 2: int to L ong throws an exception

Why does the testCase_2 () method throw an exception for compilation?

+4
source share
2 answers

When you do

  testCase_1(a); 

you pass intinstead long, widening primitive conversion.

In the second case

testCase_2(a);  

you cannot convert a primitive to an object. Autoboxing / unboxing does not work because it is longnot a wrapper int.

+10
source

When called testCase_1(a), it is aautomatically converted from intto long.

int long (, ), int long. .

testCase_2(a), , (cast autobox) int long. , , .

:

testCase_2(Long.valueOf(a));

.

+3

Source: https://habr.com/ru/post/1622703/


All Articles