+ 3

Variables inside Java classes

How am I able to "assign" a value to a final variable here? In C++, I only can "initialize" it. Or does Java has the count of the number of times a final variable is assigned and not allow more than one assignment? That's not a very efficient way though... https://code.sololearn.com/cw5Y4KHi4DV0/?ref=app

7th Sep 2021, 2:02 PM
Rishi
Rishi - avatar
5 Answers
+ 5
Rishi, I don't see that much of a difference. In C++, const members can be initialized where and as they are defined, or in a class constructor, through member initializer. And here it's pretty much the same, cause we are only assigning value to the uninitialized const (final in Java) member in the constructor. I guess there's no way it can be done in other methods.
7th Sep 2021, 2:24 PM
Ipang
+ 4
Rishi Just do this in your code and see the difference private final int a = 4; Initially final variable doens't have any value so you are able to assign new value but in the case when you have declared variable with value, it will not allow to assign you new value.
7th Sep 2021, 2:10 PM
A͢J
A͢J - avatar
8th Sep 2021, 12:31 AM
Rishi
Rishi - avatar
+ 1
be careful with final variables those are final u cant change them anymore
30th Sep 2021, 3:15 PM
magic real
magic real - avatar
+ 1
magic real yeah, I was aware of that. I was just playing around with that to understand it well =)
30th Sep 2021, 3:51 PM
Rishi
Rishi - avatar