-2

I'm working with a quite old codebase, so much of deprecated or outdated code exists. Most of it is simple pre-boxing.

But this one raised a question with me:

private java.lang.Long version = Long.valueOf(-1L);

Does the -1L not define the value as a Long already? Was this even possible before?

Note it's not -1l but -1L.

I would understand if it was written as -1 or even -1l. Can someone explain to me what is going on?

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
Mathijs Segers
  • 6,168
  • 9
  • 51
  • 75
  • "An integer literal is of type `long` if it ends with the letter `L` or `l`" - https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html – Jiri Tousek Mar 10 '16 at 13:46
  • I've asked this to my collegues yesterday, And they weren't sure. It must be that we might be too young to know. But I do have the feel this is a legit question and the downvotes is a bit of a pity. I did now realise that assuming 1L would be a Long is a silly thing to assume. I do wonder why they allow both l and L now though. – Mathijs Segers Mar 11 '16 at 10:12

1 Answers1

5

-1l and -1L are the same - both are primitive long literals.

Long.valueOf() returns a Long instance having the same value as the passed primitive.

It's important to note that Long.valueOf() uses the LongCache when you pass small values to it (i.e. values between -128 and 127), and therefore it doesn't have to create a new Long instance.

Simply assigning Long version = -1L; would auto-box the -1L primitive literal to a Long. Whether a new Long instance will be created by the auto-boxing or the compiler will be smart enough to use the LongCache depends on the compiler. I guess whoever wrote the code you posted didn't want to rely on the compiler doing the smart thing.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Allright, that explains I assumed the 1L meant Long. when I think about it that makes sense since writing a value directly is impossible with a pointer. Just thinking wrong on my side. Pity of all the downvotes :-) – Mathijs Segers Mar 11 '16 at 10:08
  • Note that some of this code is from 2005 not sure if the compiler was smart enough back then. – Mathijs Segers Mar 11 '16 at 10:09