Why does the NUMBER variable still change although i declared it as final? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why does the NUMBER variable still change although i declared it as final?

public class add { private final int NUMBER; //any constant variables should be in CAPS public add(int x){ NUMBER = x; } } public class Final { public static void main(String[] args) { add addingTen = new add(10); add addingEleven = new add(11); System.out.println(addingTen); System.out.println(addingEleven); System.out.println(addingTen); } } OUTPUT : sum = 10 sum = 11 sum = 10

14th Apr 2016, 11:59 AM
Pavitran
Pavitran - avatar
3 Answers
+ 4
Actually you are not changing final variable you just created three objects of class add so all the members will be encapsulate in all three objects so every object has its own final variable and you are assingning value to those by passing value to arguments. Mark final variable and method as static then you wont be able to change the value because static members are independent of each object and shared by every objects.
30th Jun 2016, 6:06 AM
VISHAL KUMAR
+ 1
it's very simple you actually assign the value from using x variable if assign values directly to NUMBER variable it cont change the value but u use a x variable so if x value change automatically final variable changed
24th Jun 2016, 5:33 PM
chandra kanth
+ 1
use static with final variable so you won't be able to change it again
9th Aug 2016, 3:48 PM
Islam Elzohary
Islam Elzohary - avatar