In the last tutorial we discussed about final keyword. In this post we are gonna discuss about final method parameters. You must have seen the use of final keyword in method arguments. Lets take an example to understand it:
class FinalDemo { public void myMethod(int num, final String str){ // This is allowed as num is not final num = num+10; /* This is not allowed as String str is final and * we cannot change the value of final parameter. * we can just use it without modifying its value. */ str = str+"XYZ"; System.out.println(num+str); } public static void main(String args[]){ FinalDemo obj= new FinalDemo(); obj.myMethod(10, "BeginnersBook.com"); } }
Output: The above program would throw the following compile time error because we are trying to change the value of final parameter.
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The final local variable str cannot be assigned.
If we comment out the statement str = str+"XYZ";
in above program then it would run fine without any issues.
Leave a Reply