0 votes
1 view
in Java by (3.4k points)

I can't understand where the final keyword is really handy when it is used on method parameters.

If we exclude the usage of anonymous classes, readability and intent declaration then it seems almost worthless to me.

Enforcing that some data remains constant is not as strong as it seems.

If the parameter is a primitive then it will have no effect since the parameter is passed to the method as a value and changing it will have no effect outside the scope.

If we are passing a parameter by reference, then the reference itself is a local variable and if the reference is changed from within the method, that would not have any effect from outside of the method scope.

Consider the simple test example below. This test passes although the method changed the value of the reference given to it, it has no effect.

public void testNullify() {

    Collection<Integer> c  = new ArrayList<Integer>();      

    nullify(c);

    assertNotNull(c);       

    final Collection<Integer> c1 = c;

    assertTrue(c1.equals(c));

    change(c);

    assertTrue(c1.equals(c));

}

private void change(Collection<Integer> c) {

    c = new ArrayList<Integer>();

}

public void nullify(Collection<?> t) {

    t = null;

}

1 Answer

0 votes
by (39.8k points)

Sometimes it's right to be specific (for readability) that the variable doesn't break. Here's a simplistic example anywhere practicing final can avoid any potential headaches:

public void setTest(String test) {

    test = test;

}

If you ignore the 'this' keyword on a setter, then the variable you require to insert doesn't get set. Nevertheless, if you practiced the final keyword on the parameter, then the fault would be found at compile time.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...