- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can a final variable be initialized when an object is created in Java?
Once you declare a variable final, after initializing it, you cannot modify its value further. Moreover, like instance variables, final variables will not be initialized with default values.
Therefore, it is mandatory to initialize final variables once you declare them. If not a compile time error will be generated.
Example
public class FinalExample { final int j; public static void main(String args[]){ FinalExample obj = new FinalExample(); System.out.println(obj.j); } }
Compile time error
FinalExample.java:5: error: non-static variable j cannot be referenced from a static context System.out.println(j); ^ 1 error
Initializing the final variable
You can initialize a final variable in 4 ways −
While declaring it.
public class FinalExample { final int j = 100; public static void main(String args[]){ FinalExample obj = new FinalExample(); System.out.println(obj.j); } }
Output
100
Using the final methods.
import java.util.Scanner; public class FinalExample { final int num = getNum(); public static final int getNum() { System.out.println("Enter the num value"); return new Scanner(System.in).nextInt(); } public static void main(String args[]){ FinalExample obj = new FinalExample(); System.out.println(obj.num); } }
Output
Enter the num value 20 20
Using the Constructors
public class FinalExample { final int num; public FinalExample(int num) { this.num = num; } public static void main(String args[]){ FinalExample obj = new FinalExample(20); System.out.println(obj.num); } }
Output
20
Using the Instance initialization blocks
public class FinalExample { final int num; { num = 500; } public static void main(String args[]){ FinalExample obj = new FinalExample(); System.out.println(obj.num); } }
Output
500
Except in the case of final method, if you initialize the final variable in all the other three ways it will be initialized soon you instantiate its class.
Advertisements