| Author |
Error in return statement
|
Vishnu Sharma
Ranch Hand
Joined: Feb 03, 2010
Posts: 55
|
|
I am getting the error as:
InstanceofExam.java:15: variable taxrate might not have been initialized
return taxrate;
the code containing return statement is :
public float Tax(Object e){
float taxrate;
if( e instanceof manager){
taxrate=salary-(salary*30/100);
}
if( e instanceof engineer){
taxrate=salary-(salary*20/100);
}
return taxrate;
}
Please suggest any solution.
|
Regards,
Vishnu
|
 |
Jijesh T Das
Greenhorn
Joined: Sep 27, 2007
Posts: 10
|
|
You need to initialize the variable taxrate. Java compiler checks for this and hence the error.
Modify like float taxrate = 0;
|
 |
Parambir Singh
Ranch Hand
Joined: Sep 05, 2004
Posts: 40
|
|
You always need to set some value for a variable before using it in any statement. If you are not sure what value to assign, you can initialize a variable to null:
However, you can't set the primitive types (int, float, boolean etc.) to null. So you'll have to initialize them to some value as per your program's logic (0 for int, false for boolean etc.)
|
SCJP, SCMAD
http://parambir.me
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
<edit>by the way,</edit>
@OP: Dont use float or double for a precise calculation . read this
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
As for why, ask yourself this question: what will the value of taxrate be when e is neither a manager nor an engineer? Unlike static and instance fields, local variables do not get default values.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: Error in return statement
|
|
|