Home > Articles > Programming > Java

Like this article? We recommend

Like this article? We recommend

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.
 4
 5   public class Account
 6   {
 7      private String name; // instance variable
 8      private double balance; // instance variable
 9
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
14
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      }
20
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      }                                                                
27
28      // method returns the account balance
29      public double getBalance()           
30      {                                    
31         return balance;                   
32      }                                    
33
34      // method that sets the name
35      public void setName(String name)
36      {
37         this.name = name;
38      }
39
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;
 4
 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);  
11
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());
17
18         // create a Scanner to obtain input from the command window
19         Scanner input = new Scanner(System.in);
20
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  
26
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());
32
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 
38
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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020