Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of declaring an array size using a constant

Tags:

java

arrays

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?

like image 931
kindle11 Avatar asked Nov 28 '22 23:11

kindle11


2 Answers

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.

  • improves readability of the code
  • easier to maintain

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.

like image 187
Maroun Avatar answered Dec 04 '22 14:12

Maroun


  1. you can use this constant for some other array
  2. to make clear of why is this length like: STUDENTS_MAX_SIZE = 1000
like image 36
roeygol Avatar answered Dec 04 '22 14:12

roeygol