CodesJava

Easy learning with example program codes

final keyword in java


final is a keyword in java which can be used with instance variables, local variables , methods and classes.

 Use of final keyword in java:

1. final variable in java:

A variable declared with final keyword is known as final variable. It may be member variable or local variable. final variables are constants in java and they are generally declared with static keyword. As final variables are treated as constants they can’t reassign. They are initialised at the time of declaration.

Example:

FinalExample1.java

/**
 * This program is used to show that the value of 
 * final variable can't be change. 
 * @author CodesJava
 */
class Test{
	//final variable
	final int num = 100;
 
	//method for try to change the value of final variable.
	public void show(){
		//error because value of final variable can't be change.
		num = 200;
		System.out.println("Num = " + num);
	}
}
public class FinalExample1 {
	public static void main(String args[]){
		//creating object of Test Class
		Test obj = new Test();
		//method call
		obj.show();
	}
}

Output:

Exception in thread "main" java.lang.Error: 
Unresolved compilation problem:
The final field Test.num cannot be assigned
at com.codesjava.business.Test.show(FinalExample1.java:15)
at com.codesjava.business.FinalExample1.main
(FinalExample1.java:24)

Download this example.

Note: Inside Anonymous classes only final variables are accessible.

 2.  final method in java:

A method declared with final keyword is known as final method.

Example:

FinalExample2.java

/**
 * This program is used to show that final method can't be override.
 * @author CodesJava
 */
class Show{
	public final void show(){
		System.out.println("Hello world.");
	}
}
 
class Display extends Show{
	//error because final method can't be override.
	public void show(){
		System.out.println("Hello codesjava.com.");
	}
}
 
public class FinalExample2 {
	public static void main(String args[]){
		//creating object of Display class
		Display obj = new Display();
		//method call
		obj.show();
	}
}

Output:

Exception in thread "main" java.lang.VerifyError: 
class com.codesjava.business.Display overrides final method show.()V
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at com.codesjava.business.FinalExample2.main
(FinalExample2.java:23)

Download this example.

Note: A final method can be inherited but can’t be override.

3.  final class in java:

A class declared with final keyword is known as final class. A final class can’t be inherited.

Example:

FinalExample3.java

/**
 * This program is used to show that final class can't be inherited.
 * @author CodesJava
 */
final class Show{
	public void show(){
		System.out.println("Hello world.");
	}
}
//error because final class can't be inherited.
class Display extends Show{
	public void display(){
		System.out.println("Hello codesjava.com.");
	}
}
 
public class FinalExample3 {
	public static void main(String args[]){
		//creating object of Display class
		Display obj = new Display();
		//method call
		obj.display();
	}
}

Output:

Exception in thread "main" java.lang.Error: 
Unresolved compilation problem:
The type Display cannot subclass the final class Show
at com.codesjava.business.Display.(FinalExample3.java:13)
at com.codesjava.business.FinalExample3.main
(FinalExample3.java:22)

Download this example.

Note: final method can be inherited.

Example:

FinalExample4.java

/**
 * This program is used to show that final method can be inherited.
 * @author CodesJava
 */
class Show{
	public final void show(){
		System.out.println("Hello world.");
	}
}
 
class Display extends Show{
	public void display(){
		System.out.println("Hello codesjava.com.");
	}
}
 
public class FinalExample4 {
	public static void main(String args[]){
		//creating object of Display class
		Display obj = new Display();
		//method call
		obj.show();
	}
}

Output:

Hello world.

Download this example.

Note: Abstract class and constructor can’t be final.

4. Blank final variable in java:

A variable declared with final keyword but not initialised at declaration time is known as blank final variable. They are initialised at the time of object creation in constructor and can’t change after that.

Example:

FinalExample5.java

/**
 * This class is used to show the example of blank final variable.
 * @author codesjava
 */
class Test{
	//blank final variable which can only be 
        //initialize through constructor.
	final int num;
 
	Test(int n){
		num = n;
		System.out.println("Num = " + num);
	}
}
public class FinalExample5 {
	public static void main(String args[]){
		new Test(100);
	}
}

Output:

Num = 100

Download this example.

5. static blank final variable in java:

A static variable declared with final keyword but not initialised at declaration time is known as static blank final variable. It can be initialised in a static block only.

Example:

FinalExample6.java

/**
 * This class is used to show the example of static blank final variable.
 * @author CodesJava
 */
class Test{
	//blank final variable which can only be initialize 
	//through static initializer block.
	static final int num;
 
	static{
		num = 100;
		System.out.println("Num = " + num);
	}
}
public class FinalExample6 {
	public static void main(String args[]){
		new Test();
	}
}

Output:

Num = 100

Download this example.

6.  final parameter in java:

A method parameter declared with final keyword is known as final parameter. Its value can’t be changed.

Example:

FinalExample7.java

/**
 * This program is used to show that value of 
 * final parameter can't be changed.
 * @author CodesJava
 */
class Test{
	public void showDouble(final int num){
		//error because value of final parameter can't be changed.
		num = num * 2;
		System.out.println("Num * 2 = " + num);
	}
}
public class FinalExample7 {
	public static void main(String args[]){
		//creating object of Test class
		Test obj = new Test();
		//method call
		obj.showDouble(10);
	}
}

Output:

Exception in thread "main" java.lang.Error: 
Unresolved compilation problem:
The final local variable num cannot be assigned. 
It must be blank and not using a compound assignment
at com.codesjava.business.Test.showDouble
(FinalExample7.java:11)
at com.codesjava.business.FinalExample7.main
(FinalExample7.java:20)

Download this example.

Advantages/Benefits of final keyword:

  1. Performance: JVM kept in cache if variables, methods and classes are declared final.
  2. Immutable classes: With the help of final keyword we can made immutable classes.

 
Next Topic: String handling in java.
Previous Topic: Static in java with example.

Related Topics:

Package in java with example.
Access modifier in java with example.
Static import in java with example.
Package class in java with example.
this in java with example.
Instance initialize/ Anonymous block in java with example.
super in java with example.
Static in java with example.
final in java with example.

 

Core Java Tutorial

Programming language overview.
Overview of Java.
Java features
JVM architecture details.
JVM, JRE and JDK.
Java Coding Guidelines.
Some important definitions.
Variable and data types.
Hello world java program.
Core java examples programs.
Important Java Programs.
How to set permanent path in java?
OOPs Basics.
Object and Class in Java.
OOPs Principles/Concepts.
Abstraction in java.
Encapsulation in java.
Polymorphism in java.
Method overloading in java.
Method overriding in java.
Dynamic method dispatch.
Runtime polymorphism.
Association in java.
Inheritance in java.
Aggregation in java.
Command line arguments in java.
Command line argument program in eclipse.
Read input from command line using Scanner.
Java array programs
Java star pattern programs
Java number pattern programs
final in java.
Abstract class in java.
Interface in java.
Custom marker Interface in java.
Constructor in java.
Package in java.
Access modifier in java.
Static import in java.
Package class in java.
this in java.
Instance initialize block.
Anonymous block.
super in java.
Static in java.
final in java.
Java cloning deep and shallow
Shallow vs Clone copy
String handling in java.
String handling programs.
StringBuffer in java.
StringBuilder in java.
Exception Handling Tutorial.
Multithreading Tutoial.
Java input output stream tutorial.
Collections framework in java tutorial.
Collections framework programs.
Java Random class
Java annotations.
Java design principles.
Java 7 features
Java 8 features
Java networking tutorial
Java Reflection tutorial
Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki