2

I have a method public int bar(), where i have declared an int total(in the method body ofc). So this should be a simpel local variable, the thing is that eclipse complain about

Description Resource    Path    Location    Type
The local variable total may not have been initialized  Repository.java /proj_individual/src/repo   line 35 Java Problem

general example :

public int foo(){
    int total;
    for(... : ...){
        total += 1; // complains
    }
    return total;// complains
}

and my exact code:

public int getLocatars(){
    int total;
    for ( Map.Entry<Apartment, List<Expense>> entry : dic.entrySet() ) {
        if(entry.getKey().isDebt()){
            total += entry.getKey().getNrProple();
        }
    }
    return total;
}

I have no idea what I may have done wrong, so any idea is helpful, thank you.

Bogdan M.
  • 2,161
  • 6
  • 31
  • 53

2 Answers2

6

Your variable isn't definitely assigned a value, so you can't read it.

Imagine if your entry set is empty, or has no debt entries... what value would you want to return?

More than that, even if it does get into the inner-most part of your loop, what initial value would you expect to be added to?

Unlike static and instance fields, local variables don't have default values: you have to assign values to them before you read them. I suspect you just want:

int total = 0;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • yeah, sadly this is non intuitive design. it works on fields but not on local variables. – Fabian Lange Nov 26 '12 at 17:46
  • thanks. >.> cna't belive it didn't ring a bell, somehow iw as sure java inits ints to 0.... – Bogdan M. Nov 26 '12 at 17:46
  • @FabianLange: I don't think it's unintuitive myself. For local variables, the compiler *knows* the valid execution flows. It can't know whether a setter will be called before a getter for instant/static fields. – Jon Skeet Nov 26 '12 at 17:48
4

Change it from:

int total;

to:

int total = 0;

For better understanding, see: differences between declaration and initialization.

Community
  • 1
  • 1
sampson-chen
  • 45,805
  • 12
  • 84
  • 81