Return to index

Java Basics 4
Variables and Operators

 

Topics covered include :

  • Data Types
  • Variable Names (Identifiers)
  • Scope
  • Variable Initialization
  • Final Variables
  • Operators

 

Introduction

The BasicsDemo program that follows adds the numbers from 1 to 10 and displays the result.

public class BasicsDemo {
      public static void main(String[] args) {
            int sum = 0;
            for (int current = 1; current <= 10; current++) {
                  sum += current;    // same as : sum = sum + current
            }
            System.out.println("Sum = " + sum);
      }
} 

The output from this program is:

Sum = 55 

Even a small program such as this uses many features of the Java programming language, including variables, operators and control flow statements.

 

Variables

You use variables in your program to hold data. This section discusses data types, how to initialize variables, and how to refer to variables within blocks of code.

An object stores its state in variables.

Definition:  A 'variable' is an item of data named by an identifier.

You must explicitly provide a name and a type for each variable you want to use in your program. The variable's name must be a legal 'identifier' - an unlimited series of Unicode characters that begins with a letter or underscore character. You use the variable name (identifier) to refer to the data that the variable contains. The variable's type determines what values it can hold and thus what operations can be performed on it. To give a variable a type and an identifier, you write a variable 'declaration', which generally looks like this:

type name; 

In addition to the name and type that you explicitly give a variable, a variable has 'scope' - the section or range of code where the variable's simple name can be used. The variable's scope is determined implicitly by the location of the variable declaration - that is, where the declaration appears in relation to other code elements.

Local variables and member variables can be initialized with an assignment statement when they are declared. The data type of the variable must match the data type of the value assigned to it. For example,

int i = 0;

String s = "hello";

Vector v = new Vector();

 

Final Variables

You can declare a variable in any scope to be 'final'. The value of a final variable cannot change after it has been initialized. Such variables are similar to constants in other programming languages.

To declare a final variable, use the final keyword in the variable declaration before the type:

final int A_FINAL_VAR = 0; 

The previous statement declares a final variable and initializes it, all at once. Subsequent attempts to assign a value to A_FINAL_VAR will result in a compiler error. However, you may, if necessary, defer initialization of a final local variable. Simply declare the local variable and initialize it later, like this:

final int A_FINAL_VAR;
. . .
A_FINAL_VAR = 0; 

A final local variable that has been declared but not yet initialized is called a 'blank final'. Again, once a final local variable has been initialized, it cannot be changed, and any later attempts to assign a value will result in a compile-time error.

By convention, final variables are written in all uppercase characters.

 

Data Types

Every variable must have a data type. A variable's data type determines the values that the variable can contain and the operations that can be performed on it.

The Java programming language has two categories of data types:

  • primitive
  • object reference

A variable of primitive type contains a single value of the appropriate size and format for its type: a number, a character, or a boolean value. For example, an integer value is 32 bits of data in a format known as 'two's complement', the value of a char is 16 bits of data formatted as a Unicode character, and so on.

The following table lists, by keyword, all of the primitive data types supported by Java, their sizes and formats, and a brief description of each.


Primitive Data Types

Keyword Description Size/Format
(integers)
byte Byte-length integer 8-bit two's complement
short Short integer 16-bit two's complement
int Integer 32-bit two's complement
long Long integer 64-bit two's complement
(real numbers)
float Single-precision floating point 32-bit IEEE 754
double Double-precision floating point 64-bit IEEE 754
(other types)
char A single character 16-bit Unicode character
boolean A boolean value (true or false) true or false

In other languages, the format and size of primitive data types may depend on the platform on which a program is running. In contrast, the Java programming language specifies the size and format of its primitive data types. Hence, you don't have to worry about system-dependencies.

You can put a literal primitive value directly in your code. For example, if you need to assign the value 4 to an integer variable you can write this:

int anInt = 4; 

The digit 4 is a literal integer value.

Examples of Literal Values of various Data Types

Literal Data Type
178 int
8864L long
37.266 double
37.266D double
87.363F float
26.77e3 double
' c ' char
true boolean
false boolean


Generally speaking, a series of digits with no decimal point is of type
int (integer). You can specify a long integer by putting an 'L' or 'l' after the number. 'L' is preferred as it cannot be confused with the digit '1'.

A series of digits with a decimal point is of type double. You can specify a float by putting an 'f' or 'F' after the number.

A literal character value is any single Unicode character between single quote marks.

The two boolean literals are simply true and false.

 

Object Reference Data Types

Arrays, classes, and interfaces are all object reference types. The value of a reference type variable, in contrast to that of a primitive type, is a reference to (a pointer to or the memory address of) the value or set of values represented by the variable.

A reference is called a pointer or a memory address in other languages. However, the Java programming language does not support the explicit use of addresses like other languages do. You simply use the variable's name.

 

 

Variable Names - Identifiers

A program refers to a variable's value by the variable's name (identifier).

A name, such as total, that is composed of a single identifier, is called a 'simple name'. Simple names are in contrast to 'qualified' names, which a class uses to refer to a member variable (not a local variable) that's in another object or class; for example, stats.total. In this example, variable total is an instance variable in class instance stats.

In the Java programming language, the following must hold true for a simple name:

  1. It must be a legal identifier. An identifier is an unlimited series of Unicode characters that begins with a letter (or underscore character).
  2. It must not be a keyword, a boolean literal (true or false), or the reserved word 'null'.
  3. It must be unique within its scope. However, a variable may have the same name as a variable whose declaration appears in a different scope. In some situations, a variable may share the same name as another variable if it is declared within a nested block of code. (We will cover this in the next section, Scope.)


By convention, variable names (except final variables) begin with a lowercase letter, and class names begin with an uppercase letter. If a variable name consists of more than one word, the words are joined together, and each word after the first begins with an uppercase letter, like this:
isVisible. The underscore character (_) is acceptable anywhere in a name, but by convention is mostly used to separate words in final variables (constants) - because constants are ALL_CAPS by convention and thus cannot be case-delimited.

 

Scope

The location of a variable declaration implicitly sets the variable's scope, which determines what section of code may refer to the variable by its simple name. Secondarily, scope also determines when the system creates and destroys memory for the variable.

Scope is distinct from visibility, which applies only to member variables and determines whether the variable can be used from outside of the class within which it is declared. Visibility is set with an 'access modifier' (such as 'public' and 'private').

The location of the variable declaration within your program establishes its scope and places it into one of these four categories:

  • member variable (also called 'instance variable')
  • local variable
  • method parameter
  • exception-handler parameter

 

Member Variables

A member variable is a member of a class or object. It is declared within a class but outside of any method or constructor. A member variable's scope is the entire declaration of the class.

However, the declaration of a member needs to appear before it is used when the use is in a member initialization expression. This simply means you cannot do this:

v=new Vector();

Vector v;

but smust do this:

Vector v;

v=new Vector();

 

Parameter Variables

Parameters are formal arguments to methods or constructors and are used to pass values into methods and constructors. The scope of a parameter is the entire method or constructor for which it is a parameter.

 

Local Variables

You declare local variables within a block of code. In general, the scope of a local variable extends from its declaration to the end of the code block in which it was declared.

Consider the following code sample:

if (...) {
      int i = 17;
      ...
}
System.out.println("The value of i = " + i);    // error ! 

The final line will not compile because the local variable i is out of scope. The scope of i is the block of code between int i=17 and }. The variable i no longer exists after the closing }. Either the variable declaration needs to be moved outside of the if statement block, or the println method call needs to be moved into the if statement block.

 

Operators

This section details how you can perform various operations, such as arithmetic and assignment operations.

An operator performs a function on one, two or three operands.

An operator that requires only one operand is called a 'unary operator'. For example, ++ is a unary operator that increments the value of its operand by 1.

An operator that requires two operands is a 'binary operator'. For example, = is a binary operator that assigns the value from its right-hand operand to its left-hand operand.

And finally, a 'ternary operator' is one that requires three operands. The Java programming language only has one ternary operator:

condition ? if_statement : else_statement


The unary operators support either 'prefix' or 'postfix' notation. Prefix notation means that the operator appears
before its operand:

operator op             // prefix notation

For example:

++i 


Postfix notation means that the operator appears
after its operand:

op operator             // postfix notation

For example:

i++ 

All of the binary operators use 'infix' notation, which means that the operator appears between its operands:

op1 operator op2        // infix notation 

For example:

a + b

The ternary operator is also infix; each component of the operator appears between operands:

op1 ? op2 : op3         // infix notation

In addition to performing the operation, an operator returns a value. The return value and its type depend on the operator and the type of its operands.

For example, the arithmetic operators, which perform basic arithmetic operations such as addition and subtraction, return numbers - the result of the arithmetic operation. The data type returned by an arithmetic operator depends on the type of its operands: if you add two integers, you get an integer back. An operation is said to 'evaluate to' its result.

The following table lists the basic arithmetic operators provided by the Java programming language. Except for +, which is also used to concatenate (join) Strings, these operators can be used only on numeric values.

Operator Use Description
+ op1 + op2 Adds op1 and op2
- op1 - op2 Subtracts op2 from op1
* op1 * op2 Multiplies op1 by op2
/ op1 / op2 Divides op1 by op2
% op1 % op2 Computes the remainder of dividing op1 by op2


The following short cut operators increment or decrement a number by one.

Operator Use Description
++ op++ Increments op by 1; evaluates to the value of op before it was incremented
++ ++op Increments op by 1; evaluates to the value of op after it was incremented
-- op-- Decrements op by 1; evaluates to the value of op before it was decremented
-- --op Decrements op by 1; evaluates to the value of op after it was decremented


Here are the Java programming language's other arithmetic operators.

Operator Use Description
+ +op Promotes op to int if it's a byte, short, or char
- -op Arithmetically negates op

 

Summary of Relational and Conditional Operators

Use these relational operators to determine the relationship between two values.

Operator Use Returns true if ...
> op1 > op2 op1 is greater than op2
>= op1 >= op2 op1 is greater than or equal to op2
< op1 < op2 op1 is less than op2
<= op1 <= op2 op1 is less than or equal to op2
== op1 == op2 op1 and op2 are equal
!= op1 != op2 op1 and op2 are not equal


You can use the following conditional operators to form multi-part decisions.

Operator Use Returns true if ...
&& op1 && op2 op1 and op2 are both true, conditionally evaluates op2
|| op1 || op2 either op1 or op2 is true, conditionally evaluates op2
! ! op op is false


Summary of Assignment Operators

The basic assignment operator looks as follows and assigns the value of op2 to op1.

op1 = op2; 

In addition to the basic assignment operation, the Java programming language defines these short cut assigment operators that perform an operation and an assignment using one operator.

Operator Use Equivalent to
+= op1 += op2 op1 = op1 + op2
-= op1 -= op2 op1 = op1 - op2
*= op1 *= op2 op1 = op1 * op2
/= op1 /= op2 op1 = op1 / op2
%= op1 %= op2 op1 = op1 % op2

 

Summary of Other Operators

The Java programming language also supports these operators.

Operator Use Description
?: op1 ? op2 : op3 If op1 is true, returns op2. Otherwise, returns op3.
[] type [] Declares an array of unknown length, which contains type elements.
[] type[ op1 ] Creates and array with op1 elements. Must be used with the new operator.
[] op1[ op2 ] Accesses the element at op2 index within the array op1. Indices begin at 0 and extend through the length of the array minus one.
. op1.op2 Is a reference to the op2 member of op1.
() op1(params) Declares or calls the method named op1 with the specified parameters. The list of parameters can be an empty list. The list is comma-separated.
(type) (type) op1 Casts (converts) op1 to type. An exception will be thrown if the type of op1 is incompatible with type.
new new op1 Creates a new object or array. op1 is either a call to a constructor, or an array specification.
instanceof op1 instanceof op2 Returns true if op1 is an instance of op2

 

Download and run ...

You can download the source code for the example programs as a TJI project from the 'Resources' page of our website.

 

NOTE : This document was based on parts of the excellent book 'The Java Tutorial' by Mary Campione, Kathy Walrath and Alison Huml; also on-line at Sun's Java site.


Return to index