object - Handling uninitialized Strings in Java -


here's part of small program i'm doing homework assignment:

public exam maxgrade() {     node p = firstnode;     int max = 0;     string name;     while (p!=null) {         if (p.info.getgrade()>max) {             max = p.info.getgrade();             name = p.info.getname();         }         p = p.next;     }      if (name==null)         return null;     else         return searchbyname(name); } 

so when go ahead , compile, compiler outputs message:

student.java:127: error: variable name might not have been initialized if (name==null)

the problem solved substituting fourth line with:

string name = null; 

now, can see logic in this. i'd grasp workings behind problem. mean, seems reasonable compiler checks whether variable initialized if sees you're doing in code, don't think i'm doing needs variable initialized.

according sources this when declare string (or other object) variable "name", points null. why considered anomaly check if value null? compiler consider error uninitialized variable other assignments?

fields of object type initialized null default. array members initialized null default.

local variables not - must initialized explicitly.

this thing. uninitialized variables indication of error.

from "initial values of variables" in chapter 4 of java language specification:

a local variable (§14.4, §14.14) must explicitly given value before used, either initialization (§14.4) or assignment (§15.26), in way can verified using rules definite assignment (§16).


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -