1

I'm passing in a java.lang.Long class instance to a method (obviously as reference), and I'm wondering whether it's possible to modify its long value so that the caller can get the modified value. I've looked at the documentation for java.lang.Long, but there doesn't seem to exist any setter method for this type. Is this correct?

JosephH
  • 8,465
  • 4
  • 34
  • 62

3 Answers3

6

You can not change Long value. Its immutable. Check this and that for more info

Community
  • 1
  • 1
BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
  • 2
    Well not without hacking the VM via native code or reflection at any rate. Which of course is an EXTREMELY BAD IDEA. – Antimony Mar 10 '13 at 14:58
3

java.lang.Long is a immutable, the only way is to reassign the modified value to the previous reference.

public Long someMethod(Long l) {
    l = watever;
    return l;
}

public void someOtherMethod() {
    Long l = 22235637334634263464L;
    l = someMethod(l);
}
Ian2thedv
  • 2,691
  • 2
  • 26
  • 47
PermGenError
  • 45,977
  • 8
  • 87
  • 106
1

Long is immutable in Java. You can change it inside a method in the following way:

  1. Wrap it
  2. Use AtomicLong
  3. Return changed value and reasign it outside the method
Alexander Bezrodniy
  • 8,474
  • 7
  • 22
  • 24