Search code examples
javafinal

Java Method for generating final variable NOT updating the value used for it


Hi I'm working with JAVA by blueJ and I'm having problem with the code below:

public class License {

    private String lastName = "Null";
    private final String ID_NUM = generateIDNumber();
    private static int ID_GEN = 33333;

    public License(String lastName) {
        this.lastName = lastName;
    }

    public String getLastName() {
        return lastName; 
    } 

    private String generateIDNumber() {
        String firstLetter = getLastName().substring(0,1);
        String idNumber = String.format("%d", ID_GEN) + "-" + firstLetter;                       firstLetter;
        ID_GEN += 1;
        return idNumber;
    }
}

So when I put my last name as an input, the program needs to generate the id number
which is composed of 5 digit number and first letter of the input last name.

However, the value of lastName used for generateIDNumber()is not getting updated with the newly entered input,
although when I execute getLastName(), it gets the updated input.


In other words, even if I input the lastName as "James", the value of firstLetter in generateIDNumber() is still "33333-N" for "Null", not "33333-J" for "James".

Why is this? Thank you in advance.


Solution

  • You're setting ID_NUM before the constructor runs, so lastName is still "Null". The solution is to set it within the constructor:

    private final String ID_NUM;
    
    public License(String lastName) {
        this.lastName = lastName;
        this.ID_NUM = generateIDNumber();
    }
    

    As a side note, CONSTANT_CASE should be reserved for static final variables. None of your variables fall into that category.