$show=/label

Java Final Keyword in Depth for Beginners

SHARE:

1. Overview In this tutorial, We'll learn how to use the final keyword in java with example programs . Final is one of the keywords in j...

1. Overview

In this tutorial, We'll learn how to use the final keyword in java with example programs.

Final is one of the keywords in java and final is used to restrict access to java entities.

Interestingly, the final keyword can be used on variable, method and class levels.

Java Final Keyword

All examples are shown in this article are available on GitHub.


2. What is the Final Keyword in java?


The final keyword in java is a non-access modifier and used to restrict the access of variables, methods or classes.

If any variable is declared as final then its value can not be changed and reassigned with the new values.

If the method is declared as the final method then the method can not be overridden in the subclasses and prevents providing classes own implementations.

If the class is declared as final then the class can be inherited by any other class.

Let us look at each area in detail with examples.


3. Final Variables in Java With Examples

Usage of the final keyword on the variable is allowed in java. This indicates that once the variable is declared as final then its value can not be modified or reassigned.

3.1 Local variable vs Local Final Variable

Look at the simple example which shows the difference between the normal local variable and the final local variable.

Example 1

package com.javaprogramto.keywords.finals;

public class FInalVaraibleExamples {

	public static void main(String[] args) {

		// normal local variable
		int i = 10;
		System.out.println("local i = " + i);

		// final local variable
		final int k = 20;
		System.out.println("final j = "+k);
	}

}

Output

local i = 10
final j = 20


3.2 What happens if the final and normal local value changes?

Let us try to change both local and final variable values.

Example 2


package com.javaprogramto.keywords.finals;

public class FInalVaraibleExamples {

	public static void main(String[] args) {

		// normal local variable
		int i = 10;
		i = 20;
		System.out.println("local i = " + i);

		// final local variable with value reassignment
		final int j = 10;
		j = 20; // compile time error
		System.out.println("final j = " + j);
	}

}


Output

This program did not compile because of final variable value is changed. Because the final variable is considered as constant in java.

How to create constants in java?

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The final local variable j cannot be assigned. It must be blank and not using a compound assignment

	at com.javaprogramto.keywords.finals.FInalVaraibleExamples.main(FInalVaraibleExamples.java:14)


3.3 Create Local Final Variable without assigning value

Do you think is it possible to declare the local variable as final without assigning any value?

Assume, we do not know the value now and that will be given at a later point in time. In such cases, can we declare the final variable not assigning any value?

Example 3


package com.javaprogramto.keywords.finals;

public class FInalVaraibleExamples2 {

	public static void main(String[] args) {

		// final local variable with no value assigned at the time of declaration
		final int j;
		int i = 20;
		
		j = 20; 
		System.out.println("final j = " + j);
	}

}


Output

final j = 20

From the above program, we could see that program was compiled and executed with no errors.

Hence, it is allowed to declare the final local variable without any value and can be assigned with a value later point of time for final local variables.

If the final variable is not initialized with the value at the time of declaration and the value will be assigned later point of time then it is called "Blank Final Variable".

3.4 Applying the final variables on instance variables

We can use the final keyword on the instance variables.

The final instance variable can be initialized with the value at the time of declaration.

If you do not assign the value to it then it must be initialized from the initializer block or constructor.

If any class has multiple constructors then the blank final variable must be initialized from the constructors of the class.

If blank final variables are not assigned with the value at declaration and value is not initialized in constructor or initializer block then we will get the compile-time error.


Example on final instance varaible

package com.javaprogramto.keywords.finals;

public class FInalVaraibleExamples3 {

	final int limit = 3;

	public static void main(String[] args) {

		FInalVaraibleExamples3 fInalVaraibleExamples3 = new FInalVaraibleExamples3();
		System.out.println("limit " + fInalVaraibleExamples3.getLimit());

	}

	public int getLimit() {

		return this.limit;
	}

}


Output

limit 3


Example - Blank final variable + constructor initialization

limit is a regular instance variable but newLimit is a final instance variable without initialization.

newLimit is initialized from the constructor so it will compile and run fine.

package com.javaprogramto.keywords.finals;

public class Customer {

	private int limit;
	private final int newLimit;

	public Customer(int limit, int newLimit) {

		this.limit = limit;
		this.newLimit = newLimit;
	}
	
}

If we remove the constructor from the above example then it will give the compile-time error saying "The blank final field newLimit may not have been initialized".


Example - Blank final variable + initialization block

package com.javaprogramto.keywords.finals;

public class Customer {

	private int limit;
	private final int newLimit;

	{
		newLimit = 100;
	}
	
}


Example - Blank static final variable

If the final instance variable is declared as static then it must be only initialized from the static initializer block


package com.javaprogramto.keywords.finals;

public class Customer {

	private int limit;
	private static final int newLimit;

	static {
		newLimit = 200;
	}
	
}


3.5 Applying the final Reference variables

We can declare StringBuffer or Employee classes as final reference variables.

When we do like this will allow modifying the object values but reference can be reassigned with the new one.

Look at the below code.

package com.javaprogramto.keywords.finals;

public class FInalVaraibleExamples4 {

	public static void main(String[] args) {

		final StringBuffer sb = new StringBuffer("hello");
		
		sb.append(" world");
		
		System.out.println("sb value - "+sb.toString());
	}

}

Modifying the value of the final ref variable is allowed but if we try to reassign the sb with a new StringBuffer object then will give compile time error as below.


// reassigning with new string buffer object which is not allowed on final varaibles.
sb = new StringBuffer(); // compile time error


3.6 When to use final variables in java?

The main difference between the normal and final variables is normal value can be changed as many times as needed but the final variables can not be modified once assigned.

Use java variables as final only if you want to have only assigned value throughout the program remain as same as constant.


4. Final Methods in Java With Examples

The main usage of the final method is to avoid and restrict method access by the subclasses.

And also this prevents providing the unwanted and improper use of definitions of the same method.

For example, create the class Car with the method fogLightsOn(). This method has to on only the fog lights.

And this class has subclasses such as FordCar, HondaCar classes. These two classes can override fogLightsOn() method with different behaviour. So to prevent unwanted behaviours.,

Example

package com.javaprogramto.keywords.finals;

public class FinalMethodExample1 {

	public static void main(String[] args) {

		Car ford = new FordCar();
		ford.fogLightsOn();

		Car honda = new HondaCar();
		honda.fogLightsOn();

	}
}

class Car {

	public void fogLightsOn() {
		System.out.println("Fog lights turned on now");
	}
}

class FordCar extends Car {

	public void fogLightsOn() {
		System.out.println("Lights are turned off");
	}
}

class HondaCar extends Car {

	public void fogLightsOn() {
		System.out.println("Lights are turned off permanently");
	}
}


Output

Lights are turned off
Lights are turned off permanently

In this example, fogLightsOn() method is overridden and provided with different logic rather than turning on fog lights. To avoid unwanted definitions, we have to make the Car.fogLightsOn() method as final as below.


class Car {

	public final void fogLightsOn() {
		System.out.println("Fog lights turned on now");
	}
}


Subclasses will get the compile-time error once the parent method is declared as final.


5. Final Classes in Java With Examples

In java, the final keyword is allowed to use on the class level along with the access modifiers. Usage of final in the class declaration will prevent other classes to extend or inheriting or creating the sub classes.

Final classes in java

If any other class tries to extend it then will get the compile-time error.

Example


final class Java {

	public void sayHelloWorld() {
		System.out.println("hello world");
	}
}

class JavaProgamTo extends Java {

}


Compile time error

The type JavaProgamTo cannot subclass the final class Java


6. Conclusion

In this article, we have seen in-depth about the Java Final keyword. 

The final keyword is used to restrict the changing or reassigning of the final variable.

Final methods restrict to provide the different implementations by subclasses.

The final class restrict other classes to inherit it.

If we try to access or modify them will result in compile time error.

GitHub

Java Final api

How to create immutable class in java?

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java Final Keyword in Depth for Beginners
Java Final Keyword in Depth for Beginners
https://blogger.googleusercontent.com/img/a/AVvXsEg4DrrDxHKaF2yb8lC64wymXBX4gvTAk0BHWFwQ866_OtHJnlsDMBts9Qj9xNSr_DuHJ0xRTZ6R4NXMZYsCXb_BI_scqdFURzIfQ2cg4qNUqezAUwcHxI7or_7UjNn-d515Z2bmxtC9jFNPXaHeuNmMnW-Gt2VTJJ5C4RQIq5MblKhl2UQnVK13LBXc=w400-h228
https://blogger.googleusercontent.com/img/a/AVvXsEg4DrrDxHKaF2yb8lC64wymXBX4gvTAk0BHWFwQ866_OtHJnlsDMBts9Qj9xNSr_DuHJ0xRTZ6R4NXMZYsCXb_BI_scqdFURzIfQ2cg4qNUqezAUwcHxI7or_7UjNn-d515Z2bmxtC9jFNPXaHeuNmMnW-Gt2VTJJ5C4RQIq5MblKhl2UQnVK13LBXc=s72-w400-c-h228
JavaProgramTo.com
https://www.javaprogramto.com/2021/12/java-final-keyword.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2021/12/java-final-keyword.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content