Java Reference
In-Depth Information
continued
Actually, because BigDecimal is a class and its value is stored in an instance of the
class, some of the problems with the method return type also disappear. You could
change the recalculate() method so that it updates the value of the BigDecimal
retirementFund instead of returning a BigDecimal .
import java.math.BigDecimal;
public class Errors {
public static void main(String[] args) {
int age = 30;
BigDecimal retirementFund = new BigDecimal("10000.00");
// set the scale to 2 decimal points
// and the rounding to round up when the next digit is >= 5
retirementFund.setScale(2,BigDecimal.ROUND_HALF_UP);
BigDecimal yearsInRetirement = new BigDecimal("20.00");
String name = "David Johnson";
for (int i = age; i <= 65; i++){
recalculate (retirementFund,new BigDecimal("0.10"));
}
BigDecimal monthlyPension = retirementFund.divide
(yearsInRetirement.multiply(new BigDecimal("12")));
System.out.println(name + " will have $" + monthlyPension
+ " per month for retirement.");
}
public static void recalculate(BigDecimal fundAmount,
BigDecimal rate){
// use BigDecimal methods for arithmetic operations
fundAmount.multiply(rate.add(new BigDecimal("1.00")));
}
}
exceptions
In the previous section, three kinds of errors were discussed: syntax errors, runtime errors, and logi-
cal errors. These types have been discussed in a more general way as they occur in many settings
outside of Java programming, though as you saw in the examples, they certainly apply to Java as
well. Exceptions are more specific to programming as they are events that disrupt the execution of a
program. Exceptions can be indications that something went wrong, and they can happen automati-
cally as a result of something Java is unable to complete or can be explicitly thrown when certain
conditions are met. In the following sections, you'll be introduced to some common exceptions, and
you'll get to see how to handle them in your own programs.
 
Search WWH ::




Custom Search