Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

3.5 Account Class with a Balance; Floating-Point Numbers

We now declare an Account class that maintains the balance of a bank account in addition to the name. Most account balances are not integers. So, class Account represents the account balance as a floating-point number—a number with a decimal point, such as 43.95, 0.0, -129.8873. [In Chapter 8, we’ll begin representing monetary amounts precisely with class BigDecimal as you should do when writing industrial-strength monetary applications.]

Java provides two primitive types for storing floating-point numbers in memory—float and double. Variables of type float represent single-precision floating-point numbers and can hold up to seven significant digits. Variables of type double represent double-precision floating-point numbers. These require twice as much memory as float variables and can hold up to 15 significant digits—about double the precision of float variables.

Most programmers represent floating-point numbers with type double. In fact, Java treats all floating-point numbers you type in a program’s source code (such as 7.33 and 0.0975) as double values by default. Such values in the source code are known as floating-point literals. See Appendix D, Primitive Types, for the precise ranges of values for floats and doubles.

3.5.1 Account Class with a balance Instance Variable of Type double

Our next app contains a version of class Account (Fig. 3.8) that maintains as instance variables the name and the balance of a bank account. A typical bank services many accounts, each with its own balance, so line 8 declares an instance variable balance of type double. Every instance (i.e., object) of class Account contains its own copies of both the name and the balance.

Fig. 3.8 | Account class with a double instance variable balance and a constructor and deposit method that perform validation.

 1   // Fig. 3.8: Account.java
 2   // Account class with a double instance variable balance and a constructor
 3   // and deposit method that perform validation.
 5   public class Account
 6   {
 7      private String name; // instance variable
 8      private double balance; // instance variable
10      // Account constructor that receives two parameters
11      public Account(String name, double balance)
12      {
13         this.name = name; // assign name to instance variable name
15         // validate that the balance is greater than 0.0; if it's not,
16         // instance variable balance keeps its default initial value of 0.0
17         if (balance > 0.0) // if the balance is valid                       
18            this.balance = balance; // assign it to instance variable balance
19      }
21      // method that deposits (adds) only a valid amount to the balance
22      public void deposit(double depositAmount)                        
23      {                                                                
24         if (depositAmount > 0.0) // if the depositAmount is valid     
25            balance = balance + depositAmount; // add it to the balance
26      }                                                                
28      // method returns the account balance
29      public double getBalance()           
30      {                                    
31         return balance;                   
32      }                                    
34      // method that sets the name
35      public void setName(String name)
36      {
37         this.name = name;
38      }
40      // method that returns the name
41      public String getName()
42      {
43         return name; // give value of name back to caller
44      } // end method getName
45   } // end class Account

Account Class Two-Parameter Constructor

The class has a constructor and four methods. It’s common for someone opening an account to deposit money immediately, so the constructor (lines 11–19) now receives a second parameter—initialBalance of type double that represents the starting balance. Lines 17–18 ensure that initialBalance is greater than 0.0. If so, initialBalance’s value is assigned to instance variable balance. Otherwise, balance remains at 0.0—its default initial value.

Account Class deposit Method

Method deposit (lines 22–26) does not return any data when it completes its task, so its return type is void. The method receives one parameter named depositAmount—a double value that’s added to the balance only if the parameter value is valid (i.e., greater than zero). Line 25 first adds the current balance and depositAmount, forming a temporary sum which is then assigned to balance, replacing its prior value (recall that addition has a higher precedence than assignment). It’s important to understand that the calculation on the right side of the assignment operator in line 25 does not modify the balance—that’s why the assignment is necessary.

Account Class getBalance Method

Method getBalance (lines 29–32) allows clients of the class (i.e., other classes whose methods call the methods of this class) to obtain the value of a particular Account object’s balance. The method specifies return type double and an empty parameter list.

Account’s Methods Can All Use balance

Once again, the statements in lines 18, 25 and 31 use the variable balance even though it was not declared in any of the methods. We can use balance in these methods because it’s an instance variable of the class.

3.5.2 AccountTest Class to Use Class Account

Class AccountTest (Fig. 3.9) creates two Account objects (lines 9–10) and initializes them with a valid balance of 50.00 and an invalid balance of -7.53, respectively—for the purpose of our examples, we assume that balances must be greater than or equal to zero. The calls to method System.out.printf in lines 13–16 output the account names and balances, which are obtained by calling each Account’s getName and getBalance methods.

Fig. 3.9 | Inputting and outputting floating-point numbers with Account objects.

 1   // Fig. 3.9: AccountTest.java
 2   // Inputting and outputting floating-point numbers with Account objects.
 3   import java.util.Scanner;
 5   public class AccountTest
 6   {
 7      public static void main(String[] args)
 8      {
 9         Account account1 = new Account("Jane Green", 50.00); 
10         Account account2 = new Account("John Blue", -7.53);  
12         // display initial balance of each object
13         System.out.printf("%s balance: $%.2f%n",
14            account1.getName(), account1.getBalance());
15         System.out.printf("%s balance: $%.2f%n%n",
16            account2.getName(), account2.getBalance());
18         // create a Scanner to obtain input from the command window
19         Scanner input = new Scanner(System.in);
21         System.out.print("Enter deposit amount for account1: "); // prompt
22         double depositAmount = input.nextDouble(); // obtain user input
23         System.out.printf("%nadding %.2f to account1 balance%n%n",
24            depositAmount);
25         account1.deposit(depositAmount); // add to account1's balance  
27         // display balances
28         System.out.printf("%s balance: $%.2f%n",
29            account1.getName(), account1.getBalance());
30         System.out.printf("%s balance: $%.2f%n%n",
31            account2.getName(), account2.getBalance());
33         System.out.print("Enter deposit amount for account2: "); // prompt
34         depositAmount = input.nextDouble(); // obtain user input
35         System.out.printf("%nadding %.2f to account2 balance%n%n",
36            depositAmount);
37         account2.deposit(depositAmount); // add to account2 balance 
39         // display balances
40         System.out.printf("%s balance: $%.2f%n",
41            account1.getName(), account1.getBalance());
42         System.out.printf("%s balance: $%.2f%n%n",
43            account2.getName(), account2.getBalance());
44      } // end main
45   } // end class AccountTest
Jane Green balance: $50.00
John Blue balance: $0.00

Enter deposit amount for account1: 25.53

adding 25.53 to account1 balance

Jane Green balance: $75.53
John Blue balance: $0.00

Enter deposit amount for account2: 123.45

adding 123.45 to account2 balance

Jane Green balance: $75.53
John Blue balance: $123.45

Displaying the Account Objects’ Initial Balances

When method getBalance is called for account1 from line 14, the value of account1’s balance is returned from line 31 of Fig. 3.8 and displayed by the System.out.printf statement (Fig. 3.9, lines 13–14). Similarly, when method getBalance is called for account2 from line 16, the value of the account2’s balance is returned from line 31 of Fig. 3.8 and displayed by the System.out.printf statement (Fig. 3.9, lines 15–16). The balance of account2 is initially 0.00, because the constructor rejected the attempt to start account2 with a negative balance, so the balance retains its default initial value.

Formatting Floating-Point Numbers for Display

Each of the balances is output by printf with the format specifier %.2f. The %f format specifier is used to output values of type float or double. The .2 between % and f represents the number of decimal places (2) that should be output to the right of the decimal point in the floating-point number—also known as the number’s precision. Any floating-point value output with %.2f will be rounded to the hundredths position—for example, 123.457 would be rounded to 123.46 and 27.33379 would be rounded to 27.33.

Reading a Floating-Point Value from the User and Making a Deposit

Line 21 (Fig. 3.9) prompts the user to enter a deposit amount for account1. Line 22 declares local variable depositAmount to store each deposit amount entered by the user. Unlike instance variables (such as name and balance in class Account), local variables (like depositAmount in main) are not initialized by default, so they normally must be initialized explicitly. As you’ll learn momentarily, variable depositAmount’s initial value will be determined by the user’s input.

Line 22 obtains the input from the user by calling Scanner object input’s nextDouble method, which returns a double value entered by the user. Lines 23–24 display the depositAmount. Line 25 calls object account1’s deposit method with the depositAmount as the method’s argument. When the method is called, the argument’s value is assigned to the parameter depositAmount of method deposit (line 22 of Fig. 3.8); then method deposit adds that value to the balance. Lines 28–31 (Fig. 3.9) output the names and balances of both Accounts again to show that only account1’s balance has changed.

Line 33 prompts the user to enter a deposit amount for account2. Line 34 obtains the input from the user by calling Scanner object input’s nextDouble method. Lines 35–36 display the depositAmount. Line 37 calls object account2’s deposit method with depositAmount as the method’s argument; then method deposit adds that value to the balance. Finally, lines 40–43 output the names and balances of both Accounts again to show that only account2’s balance has changed.

UML Class Diagram for Class Account

The UML class diagram in Fig. 3.10 concisely models class Account of Fig. 3.8. The diagram models in its second compartment the private attributes name of type String and balance of type double.

Fig. 3.10

Fig. 3.10 | UML class diagram for Account class of Fig. 3.8.

Class Account’s constructor is modeled in the third compartment with parameters name of type String and initialBalance of type double. The class’s four public methods also are modeled in the third compartment—operation deposit with a depositAmount parameter of type double, operation getBalance with a return type of double, operation setName with a name parameter of type String and operation getName with a return type of String.

  • + Share This
  • 🔖 Save To Your Account