What is the advantage of declaring an array using a constant in Java? For example,
private static final int CAPACITY = 2;
private int[] items = new int[CAPACITY];
What is difference between the above code and:
private int[] items = new int[2];
Note: An array's length cannot be changed once it is declared. Why should I use constant then?
Because if the CAPACITY
is used somewhere else, and in the future you decide that the CAPACITY
should be 4, you don't need to change it everywhere.
Compare:
for(int i=0;i<2;i++)
to
for(int i=0;i<CAPACITY;i++)
Avoid magic numbers in the code when you can.
Many Java classes uses constants, Integer
, Character
and more classes.
STUDENTS_MAX_SIZE = 1000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With