- 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
What are the rules to be followed while making a variable static and final?
Static variables − Static variables are also known as class variables. You can declare a variable static using the keyword. Once you declare a variable static there would only be one copy of it in the class, regardless of how many objects are created from it.
public static int num = 39;
final − Once you declare a variable final you cannot reassign value to it. When you declare a variable of a class static and final we are making it constant.
Rules to be followed
- Initialization is mandatory − It is not mandatory to initialize the instance variables of a class in java. if you do not initialize them at the time of compilation Java compiler initializes them in default constructor.
But if you declare an instance variable static and final Java compiler will not initialize it in the default constructor therefore, it is mandatory to initialize static and final variables. If you don’t a compile time error is generated.
Example
class Data{ static final int num; } public class ConstantsExample { public static void main(String args[]) { System.out.println("value of the constant: "+Data.num); } }
Compile time error
ConstantsExample.java:2: error: variable num not initialized in the default constructor static final int num; ^ 1 error
- Initialization should be done only in static blocks − When a variable is declared both static and final you can initialize it only in a static block, if you try to initialize it elsewhere, the compiler assumes that you are trying to reassign value to it and generates a compile time error −
class Data{ static final int num; Data(int i){ num = i; } } public class ConstantsExample { public static void main(String args[]) { System.out.println("value of the constant: "+Data.num); } }
Compile time error
ConstantsExample.java:4: error: cannot assign a value to final variable num num = i; ^ 1 error
To make this program work you need to initialize the final static variable in a static block as −
class Data{ static final int num; static{ num = 1000; } } public class ConstantsExample { public static void main(String args[]) { System.out.println("value of the constant: "+Data.num); } }
Output
value of the constant: 1000