Unboxing Long in java

前端 未结 9 1319
别跟我提以往
别跟我提以往 2021-01-15 16:44

In some code I see this:

private void compute(Long a, Long b, Long c) {
        long result = a-(b+c);
...


        
相关标签:
9条回答
  • 2021-01-15 17:23

    Usually you should prefer using primitives, especially if you are certain they cannot be null. If you insist on using the boxed types always think extra hard about what happens when it is null. Java will do the boxing and unboxing automatically for you, but staring at an int and wondering why you got a NullPointerException can be fun.

    0 讨论(0)
  • 2021-01-15 17:30

    The reason is obvious: result is declared as primitive.

    0 讨论(0)
  • 2021-01-15 17:34

    The answer for your doubt is

    1. autoboxing and autounboxing in Java which converts from primitive to wrapper class objects and vice versa respectively.
    2. autoboxing means internally compiler uses valueOf() method of primitive classes ans autounboxing means internally compiler uses xxxValue() method.
    3. Suppose for private void compute(Long a, Long b, Long c) { long result = a-(b+c);

    its makes this conversion a.longValue()-(b.longValue()+c.longValue()) Which means even before your statement performs addition the compiler provides the primitives of long type as input to your operands Remember that this goes in hand as JAVA is statically and strongly typed language.

    Hence you get long type output

    I hope i cleared your doubt

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