Showing posts with label Variables. Show all posts
Showing posts with label Variables. Show all posts

Saturday, October 13, 2012

Variables

Variables


Variables store data that your code can use.

There are two fundamental categories of variables, primitive data and references:

  • With primitive data, the compiler names a memory location and uses itto store the actual data - numeric values such as integers, floating point values, and the code values of single individual text characters are stored as primitives.

  • With references, the data is accessed indirectly - the compiler selects a memory location, associates it with the variable name, and stores in it a value that is effectively the memory address of the actual data - in Java, all objects and arrays are stored using references.


In the diagram below, the boxes are areas in memory:

Object storage and reference variable

Declaring Variables


Variables must be declared before they are used.

A declaration informs the compiler that you wish to:

  • Create an identifier that will be accepted by the compiler within a section of code (exactly what that section is depends on how and where the variable is declared; that is the concept of scope, which will be addressed later).

  • Associate that identifier with a specified type of data, and enforce restrictions related to that in the remainder of your code.

  • Create a memory location for the specified type of data.

  • Associate the identifier with that memory location.


Java uses many specific data types; each has different properties in terms of size required and handling by the compiler:

  • The declaration specifies the name and datatype.

  • Generally the declaration also defines the variable, meaning that it causes the compiler to allocate storage space in memory of the requested type's size.

  • A declaration may also assign an initial value (to initialize the variable).

  • Multiple variables of the same type can be declared in a comma-separated list.