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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)