Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

Variables

A Java program manipulates values, represented in source code by literals. Those values are typically stored in memory locations, with each memory location represented by a name and a type at the source code level. The combination of name and type is known as a variable.

Java classifies a variable in three ways. First, that variable is either a primitive variable (based on a primitive type) or a reference variable (based on a reference type). Second, that variable is either a simple variable (capable of storing a single value) or an array variable (capable of storing multiple values). Finally, that variable is either a class variable, an instance variable, an array component variable, a method parameter variable, a constructor parameter variable, an exception handler parameter variable, or a local variable.

With so much to learn, it's easy to feel overwhelmed. Therefore, to make variables easier to understand, this section examines only a few concepts—the declaration and initialization of primitive and reference array and non-array variables, to be exact. Later chapters cover the remaining concepts.

Declaration

Variables must be declared before they can be used. A variable declaration introduces a variable to the compiler as a name and a type. The way the variable is declared depends on whether it is a simple variable or an array variable.

Simple Variable Declaration

A simple variable is declared by using the following syntax:

typeIdentifier variableIdentifier ';'

According to the syntax, typeIdentifier specifies the variable's type using either a primitive type keyword—boolean, byte, char, double, float, int, long, or short—or a reference type identifier (such as String). The name of the variable is specified by variableIdentifier and must not be a reserved word.

The following declarations introduce a few simple variables of primitive and reference types:

int \u3063; \u3063 (Hiragana letter) stores an integer.
double amountOwing; amountOwing stores a double-precision floating-point number.
String lastName; lastName stores a reference to a String object.

Caution

Reserved words cannot be used as variable names. For example, the compiler flags int while; as an error because while is a reserved word.

Multiple simple variables can be specified in a single variable declaration by separating the variable names with commas.

The following declaration introduces a few simple variables of primitive type integer:

int count, total, age;

Array Variable Declaration

An array variable is declared by using the following syntax:

typeIdentifier '[' ']' variableIdentifier ';'

The array variable declaration syntax is similar to the previous simple variable declaration syntax. As with simple variable declarations, variableIdentifier names the array variable and must not be a reserved word. However, typeidentifier is a little different in the context of arrays.

Before continuing, ask yourself the following question: What is an array? The answer is: a block of memory divided into separate storage locations. Each storage location is capable of holding a single value of a specific type. However, the types of all values in all of those storage locations must be the same. And what is that type? The answer is: typeIdentifier.

Java regards an array as an object. variableIdentifier contains a reference to a block of memory. Each of the storage locations in that block is known as an array component variable or element and is identified by an index. typeIdentifier is the type of each element and is represented in source code either by a primitive type keyword—boolean, byte, char, double, float, int, long, or short—or by a reference type identifier (such as String). In contrast, typeIdentifier [] represents the type of variableIdentifier (and is a reference type).

The following declarations introduce a few array variables whose elements are of primitive and reference types:

char [] gradeLetters;

gradeLetters references an array of characters.

float [] temps;

temps references an array of floating- point numbers.

String [] countryNames;

countryNames references an array of references to String objects.


The example declares three array variables. The gradeLetters array is of type character [] (as represented by char []), and the type of each element is character. Similarly, the temps array is of type floating-point [] (as represented by float []), and the type of each element is floating-point. Finally, the countryNames array is of type String [], and the type of each element is String.

Declaration causes memory to be allocated for array variables but not for the storage locations comprising each array. After all, there is no indication of the size of the array (that is, the number of elements composing the array) during declaration. Later, you will learn how to allocate memory for array elements.

As a concession to C/C++, Java allows you to specify the square brackets after the variable name (as in int inventoryTotals [];). However, to improve source code readability, it is customary to specify the square brackets after typeIdentifier.

Cautions

Unlike in C++, you must not specify the size of the array by placing either an integer literal or an integer variable, initialized to some value, between the square brackets. For example, do not specify char [10] gradeLetters; to declare a gradeLetters array capable of storing 10 characters. Also, do not specify int inventoryTotals [i];—where i is an integer variable initialized to some value. Either declaration results in a compiler error message.

Multiple array variables can be specified in a single variable declaration by separating the variable names with commas.

The following declaration introduces a few array variables whose elements are of type String:

String [] names, addresses, cities;

Initialization

During declaration, a variable can be initialized to a value. The way the variable is initialized depends on whether it is a simple variable or an array variable.

Simple Variable Initialization

A simple variable can be initialized when it is declared by using the following syntax:

typeIdentifier variableIdentifier [ '=' expression ] ';'

To initialize a simple variable as part of its declaration, specify assignment operator = followed by an expression whose type matches typeIdentifier.

The following declarations introduce a few initialized simple variables of primitive and reference types:

int age = 65;
double balance = 30000.0;
String name = "Sun Microsystems";

In the example, both age and 65 are of type integer. Therefore, the initialization of age to 65 is legal. The other declarations are also legal because the variable and expression types match.

The following declarations are illegal because the types of the variable and expression (in each declaration) do not match:

short s = 50000;
int i = "abc";

In the first declaration, an attempt is made to assign an integer literal to a short integer variable, which is unacceptable—unless a cast operator is used to implement a narrowing conversion rule. (A corrected version of the first declaration is shown where cast operators are discussed in the Unary Operators section of this chapter.) In the second declaration, an attempt to assign a string literal (of type String) to an integer variable is meaningless, and there is no cast operator to make a correction.

Caution

Attempting to initialize a variable with a literal of a different type is a common source of error. However, Java allows some flexibility in that area: Java supports the assignment of certain integer literals to byte and short integer variables.

The compiler allows only one situation where literals of one type can be assigned to variables of another type: An integer literal can be assigned to either a byte variable, a short integer variable, or a character variable provided that the value of the literal fits within the variable's acceptable range of values.

The following declarations with initialization prove that it is possible to assign integer literals to byte, short integer, or character variables.

byte b = 100;
short s = 1000; 
char c = 60000;

The first declaration is legal because 100 fits within a byte's range of values: -128 to 127 (inclusive). Similarly, the second declaration is legal because 1000 fits within a short integer's -32768 to 32767 (inclusive) range of values. Finally, the third declaration is legal because 60000 fits within a character's range of values: 0 to 65535 (inclusive).

After a simple variable has been initialized, its value can be accessed by specifying the variable's name in source code.

The following code fragment declares and initializes a variable named b1. Then, a variable named b2 is declared and initialized to the value contained in b1.

byte b1 = 100;
byte b2 = b1;

Multiple simple variables can be initialized in a single variable declaration by using commas.

The following declaration introduces a few simple variables of primitive type integer and initializes two of those variables:

int count = 0, total, age = 25;

To put simple variable declaration and initialization concepts into perspective, Figure 3.2 illustrates the parts of a simple variable declaration and initialization, and the resulting memory representation.

Figure 3.2: A simple variable is declared and initialized, and the result is stored in memory.

Array Variable Initialization

An array variable can be initialized when it is declared by using the following syntax:

typeIdentifier '[' ']' variableIdentifier 
        [ '=' '{' expression ',' ... ',' expression '}' ] ';'

To initialize an array variable when it is declared, specify the assignment operator = followed by a comma-delimited sequence of expressions that are placed between brace characters { and }. Each expression's type must match the type represented in source code by typeIdentifier.

The following declarations introduce a few initialized array variables of primitive and reference types:

char [] yesNo = { 'Y', 'y', 'N', 'n' };
float [] percents = { 0.25f, 0.5f, 0.75f };
String [] titles = { "Dr.", "Mr.", "Mrs.", "Ms.", "Rev." };

yesNo is an array of four character elements; percents is an array of three floating-point elements; and titles is an array of five String reference elements. Notice the lowercase letter f appearing to the right of 0.25, 0.5, and 0.75. That letter specifies each literal's type as floating-point.

After an array variable has been initialized, its values can be accessed by specifying the following syntax:

variableIdentifier '[' expression ']'

The syntax shows how to access an array element. expression is an integer expression that indexes (that is, accesses) a specific array element. (A 0 value accesses element 0, a 1 value accesses element 1, and so on.) Like C++, Java's array elements begin at index zero.

The following code fragment declares and initializes an array variable called innerPlanetNames and accesses the second element (at index one—Venus), which subsequently prints:

String [] innerPlanetNames = { 'Mercury', 'Venus', 'Earth', 'Mars' };
System.out.println (innerPlanetNames [1]);

Java provides a convenient mechanism for determining the number of elements in an array—the length property. To return the length of an array, simply attach a period character followed by length to the array variable's name.

The following code fragment returns the length of the previous example's innerPlanetNames array (which is four) and subsequently prints that value:

System.out.println (innerPlanetNames.length);

Multiple array variables can be initialized in a single variable declaration. That is accomplished by using commas to separate variable names from initializations.

The following declaration introduces a few array variables whose elements are of primitive type integer and initializes two of those variables:

int [] num1 = { 1, 2 }, num2, num3 = { 3, 4, 5 };

To put the array variable declaration and initialization concepts into perspective, Figure 3.3 illustrates the parts of an array variable declaration and initialization, and the resulting memory representation.

Figure 3.3: An array variable is declared and initialized, and the result is stored in.

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