Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Error in return statement

 
Vishnu Sharma
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jijesh T Das
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 40
Android Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.)
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<edit>by the way,</edit>
@OP: Dont use float or double for a precise calculation . read this
 
Rob Spoor
Sheriff
Pie
Posts: 20550
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic