Search code examples
javaconstantsfinal

Should these parameters be constants or a regular integer?


I have these 3 finals and I am not sure if they should be finals or not, below there is an example of their use, please assume that userNum was scanned, thank you.

final int HUNDREDS_DIGIT = 100;
final int TENS_DIGIT = 10;
final int SINGLES_DIGIT = 10;

//Calculates and prints the difference between user number and its reverse.
System.out.println("User number is: " + userNum); 
int firstDigit = userNum / HUNDREDS_DIGIT;
int secondDigit = userNum / TENS_DIGIT % TENS_DIGIT;
int thirdDigit = userNum % SINGLES_DIGIT;
int reversedNum = thirdDigit * HUNDREDS_DIGIT + secondDigit * TENS_DIGIT + firstDigit;
int difference = Math.abs(userNum - reversedNum);

Solution

  • To determine if these values should be final you should ask yourself if you want their value to change during program execution or not.

    To me it looks like if these values changed it would yield incorrect results, so final is a good choice.

    That said these may not have to be even constants, userNum /100 is fairly clear in its intention.