user10499199
user10499199

Reputation:

My eclipse keep saying "The value of the field is not used"

ı have a (boolean)hasDriverLicence variable in my Person class . I created getter and setter methods and ı used hasDriverLicence in the person constructor but my eclipse saying "The value of the field Person.hasDriverLicence is not used." Here is the code :

public Person(int id, String firstName, String lastName, String gender, Calendar birthDate, String maritalStatus,
        String hasDriverLicence) throws Exception {

    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.birthDate = birthDate;

    setGender(gender);
    setMaritalStatus(maritalStatus);
    setHasDriverLicence(hasDriverLicence);

and here is the getter and setter :

public void setHasDriverLicence(String hasDriverLicence) throws Exception {

    if (!(hasDriverLicence.equalsIgnoreCase("Yes")) && !(hasDriverLicence.equalsIgnoreCase("No")))

        throw new Exception("Wrong input, please type Yes or No");

    if (hasDriverLicence.equalsIgnoreCase("Yes")) {

        this.hasDriverLicence = true;

    }

    else if (hasDriverLicence.equalsIgnoreCase("No")) {

        this.hasDriverLicence = false;

    }
}

public String getHasDriverLicence() {

    if (this.hasDriverLicence = true)

        return "Yes";

    if (this.hasDriverLicence = false)

        return "No";

    else

        return "";
}

Upvotes: 1

Views: 1469

Answers (2)

Mena
Mena

Reputation: 48404

You have a typo in the getter. Your if conditions actually set the value of the instance field, instead of checking for it:

if (this.hasDriverLicence = true)

This should be:

if (this.hasDriverLicence == true)

Or better simply:

if (this.hasDriverLicence) {
    // ...
// no need for a separate if statement for the opposite condition,
// and you can only have two states here
else { 

    // ...
}

The variable is therefore assigned but never used in your code.

Elaboration

The reason why the single = compiles, but the IDE gives you a warning claiming the variable is never used, is because the assignment operator returns the assigned value.

For instance, the statement:

myVariable = 1  

... returns 1.

Therefore, when you are incorrectly checking for an assignment (=) rather than primitive equality (==), you will always check for the value of your assignment (in your case, true in the first condition which will always fulfill, false in the second, which will therefore never fulfill).

Upvotes: 2

nihar kawli
nihar kawli

Reputation: 52

May be you can try rebuilding your workspace. I am not able to see the issue with the above mentioned code.

Upvotes: -1

Related Questions