Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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 (46k 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.

Related questions

0 votes
1 answer
asked Jul 16, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...