Learn about final variable in java with example that is how to use final variable in a class field, methods parameter and in an interface in java.

We use final keyword before variables in java programs, so, we cannot modify the value once the final variable is initialized.

Final variables can be used in multiple situations, for example, you may want a class field to be final. Within a method parameter, so, we cannot modify it accidentally inside the method and used in an interface.

Final prevents a variable and method parameter to be modified

Examples of final variables in Java

Let’s see examples of using final variable for class field, as a method parameter and how we use in an interface in java programs.

Perquisite: class in java.

final class field

If we make a class filed final, then it cannot be modified and act as a constant. In this code, print() method is trying to modify the value of final field “a” resulting a compiler error that “final field X:a cannot be assigned”

class X{
	final int a = 10;
	
	public void print(){
		
		a =20;// compiler error: final field X:a cannot be assigned
		System.out.println("a = "+a);
	}
}

Prerequisite: methods in java.

final variable in method parameter

If a parameter of a method is final then it cannot be modified inside the method. If we try then compiler complain as final local variable cannot be assigned. In below program, method m is trying to change the value of final variable y resulting an error.

class X {
	
	public void m(final int y) {

		// order argument cannot be modified inside the function
		y = 20;// error: final local variable cannot be assigned

	}
}

Prerequisite: interface in java.

final variable in an interface

In an interface, all variables are by default final and they cannot be changed from outside of interface. Typically, we keep collections of constants in an interface in java application.

interface Math{
	public static final double	PI = 3.14;
	public static final double ELUERNUMBER  = 2.718;
	public static final double SQRT = 1.41421;
}

Related Posts