I was wondering if it fits to include the final keyword in a method signature when giving an instance of java.lang.Number (for example, java.lang.Long)?
java.lang.Number demonstration
public class Demo {
public static void main(String[] args) {
Long longValue = 1L;
System.out.println("Long before: " + longValue);
System.out.println(trickyMethod(longValue));
System.out.println("Long after: " + longValue);
BigInteger bigIntegerValue = BigInteger.ONE;
System.out.println("BigInteger before: "+ bigIntegerValue);
System.out.println(trickyMethod(bigIntegerValue));
System.out.println("BigInteger after: " + bigIntegerValue);
}
private static String trickyMethod(Long value) {
value = 10L;
System.out.println(" trickyMethod: " + value);
if (value.equals(10L))
return " equal";
else
return " different";
}
private static String trickyMethod(BigInteger value) {
value = BigInteger.TEN;
System.out.println(" trickyMethod: " + value);
if (value.equals(BigInteger.TEN))
return " equal";
else
return " different";
}
}
And the result
Long before: 1
trickyMethod: 10
equal
Long after: 1
BigInteger before: 1
trickyMethod: 10
equal
BigInteger after: 1
POJO demonstration
public class Demo {
static class Container {
private Long l;
public Container(Long l) {
this.l = l;
}
@Override
public String toString() {
return String.valueOf(l);
}
@Override
public boolean equals(Object obj) {
Container c = (Container) obj;
return l.equals(c.l);
}
}
public static void main(String[] args) {
Container container = new Container(1L);
System.out.println("Container before: "+ container);
System.out.println(trickyMethod(container));
System.out.println("Container after: " + container);
}
private static String trickyMethod(final Container container) {
container.l = 10L;
System.out.println(" trickyMethod: " + container);
if (container.equals(new Container(10L)))
return " equal";
else
return " different";
}
}
And the result
Container before: 1
trickyMethod: 10
equal
Container after: 10
It does not make sense to me because Java passes object reverences via value. That is, Java sends a copy of the original reference. Any changes to this Number's value are invisible outside of the procedure. Thus it makes no difference whether the method modifies or not the value within the method.
Of course, when we give a pojo to a method, we should use the final keyword, but that is a distinct issue.
In the case of Long, why do developers include final keywords in method signatures such as this String method(final Long value)?
asd