Thursday, February 27, 2014

final keyword to primitive and non primitive variables in Java

On using Final Keyword to a primitive variable, the value of the primitive variable cannot be changed while for non primitive variable the value of the variable can be changed.

Here is an example to show the use of Final keyword to primitive and non primitive variables.

Code: 


  1. public class FinalToPrimitive {

  2. /**
  3. * @param args
  4. */
  5. public static void main(String[] args) {
  6. // TODO Auto-generated method stub
  7. final int i=10;
  8. i=30;    //it will throw an error "The final local variable i cannot be assigned. It must                                            // be blank and not using a compound assignment"
  9. }

  10. }
While it is possible to change the value of a non primitive final variable.

Code:


  1. public class FinalToNonPrimitive {
  2. int i=10;

  3. /**
  4. * @param args
  5. */
  6. public static void main(String[] args) {
  7. // TODO Auto-generated method stub
  8. final FinalToNonPrimitive fnp = new FinalToNonPrimitive();
  9. fnp.i=30;   // it's possible to use final non primitive variable and change their values
  10. }

  11. } 


No comments:

Post a Comment