Wednesday, 25 April 2018

Core Java: Variables, Identifiers (or Names), Constants (final Variables)

Variables

·        A variable is used to store a piece of data for processing. It is called variable because you can change the value stored.

·        More precisely, a variable is a named storage location, that stores a value of a particular data type. In other words, a variable has a name, a type and stores a value.

·        A variable has a name (aka identifier), e.g., radius, area, age, and height. The name is needed to uniquely identify each variable, so as to assign a value to the variable (e.g., radius=1.2), as well as to retrieve the value stored (e.g., radius*radius*3.1419265).

·        A variable has a type. Examples of Java type are:

Ø      int: meant for integers (whole numbers) such as 123 and -456.

Ø      double: meant for floating-point (real numbers), such as 3.1416, -55.66, 1.2e3, -4.5E-6, having a optional decimal point and fractional part.

Ø      String: meant for texts such as "Hello", "Good Morning!". Strings are enclosed within a pair of double quotes.

Ø      char: meant for a single character, such as 'a', '8'. A char is enclosed by a pair of single quotes.

·        A variable can store a value of that particular data type. It is important to take note that a variable in most programming languages is associated with a type, and can only store value of the particular type. For example, a int variable can store an integer value such as 123, but NOT real number such as 12.34, nor string such as "Hello".

·        The concept of type was introduced in the early programming languages to simplify interpretation of data made up of binary numbers (0's and 1's). The type determines the size and layout of the data, the range of its values, and the set of operations that can be applied.

Identifiers (or Names)
·        An identifier is needed to name a variable (or any other entity such as a method or a class). Java imposes the following rules on identifiers:
·        An identifier is a sequence of characters, of any length, comprising uppercase and lowercase letters (a-z, A-Z), digits (0-9), underscore "_", and dollar sign "$".
·        White space (blank, tab, newline) and other special characters (such as +, -, *, /, @, &, commas, etc.) are not allowed. Take note that blank and dash (-) are not allowed, i.e., "max value" and "max-value" are not valid names. (This is because blank creates two tokens and dash crashes with minus sign!)
·        An identifier must begin with a letter (a-z, A-Z) or underscore (_). It cannot begin with a digit (0-9) (because that could confuse with a number). Identifiers begin with dollar sign ($) are reserved for system-generated entities.
·        An identifier cannot be a reserved keyword or a reserved literal (e.g., class, int, double, if, else, for, true, false, null).
·        Identifiers are case-sensitive. A rose is NOT a Rose, and is NOT a ROSE.

Variable Naming Convention
A variable name is a noun, or a noun phrase made up of several words with no spaces between words. The first word is in lowercase, while the remaining words are initial-capitalized. For example, thefontSize, roomNumber, xMax, yMin, xTopLeft and thisIsAVeryLongVariableName. This convention is also known as camel-case.
Recommendations
·        It is important to choose a name that is self-descriptive and closely reflects the meaning of the variable, e.g., numberOfStudents or numStudents, but not n or x, to store the number of students. It is okay to use long names!
·        Do not use meaningless names like a, b, c, d, i, j, k, i1, j99.
·        Avoid single-letter names like i, j, k, a, b, c, which is easier to type but often meaningless. Exception are common names like x, y, z for coordinates, i for index. Long names are harder to type, but self-document your program. (I suggest you spend sometimes practicing your typing.)
·        Use singular and plural nouns prudently to differentiate between singular and plural variables.  For example, you may use the variable row to refer to a single row number and the variable rows to refer to many rows (such as an array of rows - to be discussed later).

Variable Declaration
To use a variable in your program, you need to first "introduce" it by declaring its name and type, in one of the following syntaxes. The act of declaring a variable allocates a storage (of size capable of holding a value of the type).
Syntax
Example
// Declare a variable of a specified type
type identifier;

// Declare multiple variables of the same type, separated by commas
type identifier1, identifier2, ..., identifierN;

// Declare a variable and assign an initial value
type identifier = initialValue;

// Declare multiple variables with initial values
type identifier1 = initValue1, ..., identifierN = initValueN;
 int option;


double sum, difference, product, quotient;


int magicNumber = 88;


String greetingMsg = "Hi!", quitMsg = "Bye!";

Constants (final Variables)
Constants are non-modifiable variables, declared with keyword final. Their values cannot be changed during program execution. Also, constants must be initialized during declaration. For examples:

final double PI = 3.1415926;  // Need to initialize
Constant Naming Convention: Use uppercase words, joined with underscore. For example, MIN_VALUE, MAX_SIZE.
Expressions
An expression is a combination of operators (such as addition '+', subtraction '-', multiplication '*', division '/') and operands (variables or literals), that can be evaluated to yield a single value of a certain type. For example,
1 + 2 * 3           // evaluated to int 7

int sum, number;
sum + number        // evaluated to an int value

double principal, interestRate;
principal * (1 + interestRate)  // Evaluated to a double value
Assignment
Ø    the equal symbol '=' is known as the assignment operator
Ø      assigns a literal value (of the RHS) to a variable (of the LHS), e.g., x = 1; or
Ø      evaluates an expression (of the RHS) and assign the resultant value to a variable (of the LHS), e.g.,
x = (y + z) / 2.
The syntax for assignment statement is:
Syntax
Example
// Assign the literal value (of the RHS) to the variable (of the LHS)
variable = literalValue;

// Evaluate the expression (RHS) and assign the result to the variable (LHS)
variable = expression;
 number = 88;


sum = sum + number;
The assignment statement should be interpreted this way: The expression on the right-hand-side (RHS) is first evaluated to produce a resultant value (called r-value or right-value). The r-value is then assigned to the variable on the left-hand-side (LHS) or l-value. Take note that you have to first evaluate the RHS, before assigning the resultant value to the LHS. For examples,
number = 8;           // Assign literal value of 8 to the variable number
number = number + 1;  // Evaluate the expression of number + 1,
                      //  and assign the resultant value back to the variable number
8 = number;           // INVALID
number + 1 = sum;     // INVALID

No comments:

Post a Comment

Please write your view and suggestion....