Java: Long result = -1: cannot convert from int to long

后端 未结 7 780
你的背包
你的背包 2020-12-03 19:39

I\'m using eclipse java ee to perform java programming.

I had the following line of code in one of my functions:

Long result = -1;

相关标签:
7条回答
  • 2020-12-03 19:50

    To specify a constant of type long, suffix it with an L:

    Long result = -1L;
    

    Without the L, the interpreter types the constant number as an int, which is not the same type as a long.

    0 讨论(0)
  • 2020-12-03 19:54
    Long result = -1L;
    
    0 讨论(0)
  • 2020-12-03 20:03
     Long result = -1L;
    
     Long result = (long) -1;
    
     Long result
         = Long.valueOf(-1);  // this is what auto-boxing does under the hood
    

    How it happened in the first place is that the literal -1 is an int. As of Java5, you can have it auto-boxed into an Integer, when you use it as on Object, but it will not be turned into a Long (only longs are).

    Note that an int is automatically widened into a long when needed:

    long result = -1;   // this is okay
    

    The opposite way needs an explicit cast:

    int number = (int) result;
    
    0 讨论(0)
  • 2020-12-03 20:04

    -1 is a primitive int value, Long however is the wrapper class java.lang.Long. An primitive integer value cannot be assigned to an Long object. There are two ways to solve this.

    1. Change the type to long

      If you change the type from the wrapper class Long to the primitive type long java automatically casts the integer value to a long value.

      long result = -1;

    2. Change the int value to long

      If you change the integer value from -1 to -1L to explicit change it to an long literal java can use this primitive value to automatically wrap this value to an java.lang.Long object.

      Long result = -1L;

    0 讨论(0)
  • 2020-12-03 20:10

    There is no conversion between the object Long and int so you need to make it from long. Adding a L makes the integer -1 into a long (-1L):

    Long result = -1L;
    

    However there is a conversion from int a long so this works:

    long result = -1;
    

    Therefore you can write like this aswell:

    Long result = (long) -1;
    

    Converting from a primitive (int, long etc) to a Wrapper object (Integer, Long etc) is called autoboxing, read more here.

    0 讨论(0)
  • 2020-12-03 20:12

    -1 can be auto-boxed to an Integer.

    Thus:

    Integer result = -1;
    

    works and is equivalent to:

    Integer result = Integer.valueOf(-1);
    

    However, an Integer can't be assigned to a Long, so the overall conversion in the question fails.

    Long result = Integer.valueOf(-1);
    

    won't work either.

    If you do:

    Long result = -1L;
    

    it's equivalent (again because of auto-boxing) to:

    Long result = Long.valueOf(-1L);
    

    Note that the L makes it a long literal.

    0 讨论(0)
提交回复
热议问题