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

后端 未结 7 831
你的背包
你的背包 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 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.

提交回复
热议问题