Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Final Keyword in Java

    The "final" keyword is a modifier used in programming to indicate that something cannot be changed or modified. It can be applied to classes, variables and methods.When final keyword is added to a class, it means that the class cannot be extended or subclassed. In other words, we can say cannot create a new class that inherits from a final class.The value of variable can't be changed if a variable is declared as final.

    For example If you declare a variable as final and assign it a value of 10, its value cannot be changed later in the programme.The final keyword is used when you want to make sure that specific varibale remain constant throughout the program.

    The final keyword is useful when you want a variable, such as PI, to always store the same value (3.14).If a method has the final keyword then it cannot be overridden by a subclass. A method defined in a superclass can be implemented by a subclass, but if the method in the superclass is marked as final then subclass cannot change or override it.It helps in maintaining the integrity and stability of your code by preventing accidental modifications.

Table Of Content

  • Final Keyword in Java
  • How to initialized final Variable
  • Use of final keyword with variables
  • Use of final keyword with methods
  • Use of final keyword with class
  • Question related to Final keyword







Usage of final Keyword

  • Use of final keyword with variables to stop value change
  • Use of final keyword with methods to stop method overriding
  • Use of final keyword with class to stop inheritance

How to initialized final Variable


It is necessary to initialize a final variable. otherwise, the compiler will raise a compile-time error. An initializer or assignment statement may only be used once to initialize a final variable.

  • When a final variable is declared, it can be initialized. The most typical strategy is this one. If a final variable is not initialized during declaration, it is referred to as a blank final variable. The two methods for initializing a blank final variable are listed below.
  • An instance-initializer block or the constructor can both initialize a blank final variable. If your class has multiple constructors, it must be initialized in each one in order to avoid a compile-time error.
  • A static block can initialize a final static variable that is empty.





1. Use of final keyword with variables


When a variable is declared with the final keyword, its value is unchangeable; it is effectively a constant. This also implies that a final variable must be initialized.
If a final variable is a reference type (such as an object or an array), it cannot be rebound to point to a different object. However, you can still modify the internal state of the object that the final variable references. This means you can add or remove elements from an array or collection that is declared as final.
It is best to represent final variables in all uppercase, with underscores used to separate words.


Above concept is explained in below program

final int num = 5; // Declaring a final variable of type int
final String message = "Hello"; // Declaring a final variable of type String

final int[] numbers = {1, 2, 3}; // Declaring a final array
final List<String> names = new ArrayList<>(); // Declaring a final collection

names.add("Ram"); // Modifying the internal state of the final collection
numbers[0] = 10; // Modifying the first element of the final array
System.out.println(num); // Output: 5
System.out.println(message); // Output: Hello
System.out.println(Arrays.toString(numbers)); // Output: [10, 2, 3]
System.out.println(names); 

Output:

5
Hello
[10, 2, 3]
[Ram] 

Java program uses of final keyword with variables
class Nano{  
	final int speedlimit=90;// it is final variable  
	void run(){  
	  speedlimit=400;  // can't reassign value
	}  
	public static void main(String args[]){  
		Nano obj=new  Nano();  
	    obj.run();  
	}  
}



Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
                                            The final field Nano.speedlimit cannot be assigned 

2. Use of final keyword with methods


A method is referred to as a final method if the keyword final is used in its declaration. An ultimate method cannot be changed. This is done by the Object class, which has a few final methods. Methods that must have the same implementation across all derived classes must be declared with the final keyword.


class vehicles{
	final void run(){
		System.out.println("Running");
	}
}

class Nano extends vehicles{  
	void run(){   // Cannot override the final method from vehicles
	  System.out.println("Running");
	}  
	public static void main(String args[]){  
		Nano obj=new  Nano();  
	    obj.run();  
	}  
}



Output:

Compile Time Error 

3. Use of final keyword with class


A class is referred to as a final class if the keyword final is used in its declaration. There is no way to extend a final class (inherited).


final class vehicles{}

    class Nano extends vehicles{   // The Nano class cannot be subclass the final class vehicles
	void run(){   
	  System.out.println("Running");
	}  
	public static void main(String args[]){  
		Nano obj=new  Nano();  
	    obj.run();  
	}  
}



Output:

Compile Time Error 

Question related to Final keyword

  • It is not possible to declare a constructor as final because constructors cannot be inherited.
  • Any parameter that has been declared final cannot have its value changed.

  • class Vehicles{   
    	String vehiclesName(final String name){   
            return "nano";
          }  
          public static void main(String args[]){  
              Vehicles vehicles=new  Vehicles();  
              System.out.println(vehicles.vehiclesName("Alto")); //value not updated 
          }  
      }
      



    Output:

    nano 



  • Static blank final variables are static final variables that are not initialized at the time of declaration. Just a static block can initialize it.

  • class Vehicles{   
    	static final int speed; // it is static blank final variable  
    	static{
    		speed=50;
    	}  
    	public static void main(String args[]){  
    		System.out.println(Vehicles.speed);  
    	}  
    }
    



    Output:

    50 

  • Although the final method is inherited, it cannot be modified.

  • class nano{
    	final void run() {
    		System.out.println("Nano");
    	}
    }
    class Vehicles extends nano{    
    	public static void main(String args[]){  
    		Vehicles vehicles=new Vehicles();
    		vehicles.run();
    	}  
    }
    



    Output:

    50 
Difference Between method overloading and method overriding Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Difference between Early and Late Binding in Java
Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.