Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java variable not initialized in loops?

I’m doing a course management system using java, and I want to check if a course if already enrolled.

Here is my code

boolean duplicateCheck;

for (int i=0; i<enrolledCourses.size(); i++) {
    if (enrolledCourses.get(i) == searchResult.get(Integer.parseInt(userInput)-1)) {
        duplicateCheck = true;
        break;
    } else {
        duplicateCheck = false;
}

if (duplicateCheck) {
    System.out.println("You've already enrolled in this course!");
} else {
...
}

But in the second if statement it says

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The local variable duplicateCheck may not have been initialized

What’s wrong with my code? What should I do to fix it?

>Solution :

Variables must be initialized before use!

Definite Assignment

Do you think that when statement if (duplicateCheck) is executed, duplicateCheck is already assigned?

But you overlooked one point, enrolledCourses.size() may be equal to zero, in this case, the for loop will not be entered, and duplicateCheck will not be assigned

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading