When to use Long vs long in java?

long is a primitive, which must have a value. Simple.

Long is an object, so:

  • it can be null (meaning whatever you like, but "unknown" is a common interpretation)
  • it can be passed to a method that accepts an Object, Number, Long or long parameter (the last one thanks to auto-unboxing)
  • it can be used as a generic parameter type, ie List<Long> is OK, but List<long> is not OK
  • it can be serialized/deserialized via the java serialization mechanism

Always use the simplest thing that works, so if you need any of the features of Long, use Long otherwise use long. The overhead of a Long is surprisingly small, but it is there.


1 Long is the object orientated counter part of long. The difference is as follows, and it applies to Float to float, Integer to integer etc.

  • long is a primitive type, while Long is a Java class (and so it will inherit Object).
  • long must be assigned with a valid number, while Long can be null
  • long instances can't use the benefits of OO, while instances of Long are real Java objects
  • Long is a serializable so it will be very useful when doing file, database or network IO
  • long is more efficient than Long considering memory space and processing speed

If you are doing heavy calculations, use primitive types. Otherwise if you're concerning more about design, the object counter parts will be very useful.

2 Since you are not using any frameworks if I'm observing correctly, I suggest you make an interface like Validated with a method bool validate(). And every time you try to put a input into the database call validate in advance.


I don't think there's a single correct answer. A few suggestions:

  • The biggest difference I see between long and Long in this context is that Long may be null. If there's a possibility you might have missing values, the Long object will be helpful as null can indicate missing values. If you're using primitives, you'll have to use some special value to indicate missing, which is probably going to be a mess. Speed or size is not likely to be an issue unless you're planning on making an array of a million of these things and then serializing.

  • My preference for validation logic is to throw some sort of custom ValidationException at the point at which the thing could fail. If you're just creating these things with a constructor, the simplest thing would be just to validate there, e.g.

     public ClientInput(Long userid, Long clientid, Map<String, String> parameterMap, Long timeout_ms, boolean debug) throws ValidationException {          
    
          if (userid == null) throw new ValidationException("UserId is required"); 
                ...etc, etc...
    }
    

Ultimately, the ValidationException is only useful if you can catch it at a point where you can do something useful with it - echo it back to a user or whatever.