|
Variables and Operators
Topics covered include : * Variables, Data Types and Scope * Literals * Operators * Expressions, Statements and Blocks
Variables Variables are used to store data for later use. Before using a variable you must declare it. A vaiable must have both a type (the type of data that the variable will hold) and a name ('identifier'). A variable declaration looks like:
For example, you saw this variable declaration in the previous section:
In this statement we declare a variable called loop to be of type int (meaning it can hold an integer value). In this particular declaration we set its initial value to be 1 although you do not need to do this during a variable declaration. The variable's type determines what kind of values it can hold and what operations can be performed on it. You use the name of the variable to refer to the data the variable holds. Its name is also called its identifier. Variable names can be any legal identifier as long as they are not Java reserved words. Identifiers can be any number of characters but must start with a letter. They also must not contain spaces or most other non-alphanumeric characters. As with methods, variables should by convention start with a lowercase letter (class names start with a capital letter). The variable's scope is the block of code for which the variable is valid. Scope also controls when the variable is created and destroyed as the program runs. A variable is automatically destroyed (and the memory it used recovered) when it goes out of scope. A block is defined by curly braces at the start and end. Hence a block may be the whole class, a method, a loop or if clause. There are four kinds of variables we must distinguish:
As discussed previously, instance variables hold the state of a given object. Each object has its own memory allocated to hold these values. Instance variables hold data which is unique for each object instance. Each instance has its own variable with the specified name and each object will probably have different values stored in it. A class may have static variables. The name 'static variable' is a bit of a misnomer. It leads you to believe that its value can't change, which is not the case. What is the case is that static variables are shared between all the objects of that class. A static variable is static in the sense that there is only one copy of it. For example, a MP3App class could have a static variable called count to hold the number of MP3App objects that have been created. Note that the keyword static is used in the variable declaration:
Each time a new object is instantiated by calling the class's constructor, this value would be incremented. This value might be stored by each object under a different name as its serial number. However, MP3App.count would always be the total number of objects created. Both static and instance variables are also known as member variables. They are declared within a class, but not within any of the class methods. Their scope is the entire class, including the code in all the class methods. Local variables are temporary variables that can hold a value while a particular block of code is executing. They are declared within the code of a method. Their scope extends from the place they are declared to the closing curly brace '}' of the code block they are declared in. Method parameters serve as another type of variable. Method parameters are how values get passed into a method. They remain in scope throughout the method that they are a paramter of. The method may operate on these vaiables. Aside from method parameters, the declaration of a variable may also include an access modifier. The allowable access modifiers are:
These access modifiers can also be used in method declarations.
For both instance and static variables, you can add the keyword final before the variable name to specify that the variable's value can't be changed after the initial assignment. This effectively makes it a constant. By convention, final variables are named in all uppercase characters. For example:
Data Types In Java, every variable must have a type. If you think of a variable as a cubbyhole, then the data type is the cubbyhole's shape. You cannot put "square" data into a cubbyhole designed for "round" data. Likewise, if you have declared a variable to be of type int as we did above, then you cannot put double (floating point or decimal) data into it. Java has two categories of data types: primitive and object reference. Primitive variables hold numbers, characters or booleans (true/false). The most common primitive types are boolean, char, int and double. Object references hold pointers (or memory addresses) to an object instance. For example, you could declare a variable called myTurtle to be of type Turtle and assign it an initial value like this:
You could later refer to myTurtle and have it move forward 10 pixels with the following code:
Variables declared to hold an object reference may also be assigned the special value null. This value means 'no object'. For example, if you declare an instance variable of type Turtle but never assign it to an object, it will have the value null.
Literals Literals are how specific values of Java primitive data types are represented in the source code. Some examples of literals are:
Besides literals for the primitive types, Java also provides literals for objects of class String that hold sequences of characters.
Operators Operators are things like the plus sign "+". They perform functions like addition or subtraction on one or more values which are called the operands. Operators can be unary, binary, or ternary. A unary operator works on one operand. For example, ++ is a unary operator that increments the value of its operand by one. Binary operators require two operands. For example, + is a binary operator that adds its left and right operands together. Finally, a ternary operator is one that has three operands. The only ternary operator in Java is ?: which is a kind of if/else statement. Operators perform an operation and return a result. The data type of the result will generally depend upon the data type(s) of the operands. Java has many operators. The most commonly used are as follows.
Arithmetic Operators
A relational operator compares two values and returns true or false depending on the relationship between them. They are commonly used in the condition part of if, while and for statements where you are testing the relation and conditionally executing a piece of code depending on the result.
A conditional operator works with true/false operands and returns a true/false value.
The basic assignment operator = is used to assign a value to a variable. A typical usage might be:
which puts the value 33 into the variable called i. New programmers are often confused by this notation since it look like an equality statement such as 2 + 3 = 5.
There are also several shortcut operators that allow you to perform both an operation and an assignment with only one operator.
Expressions, Statements and Blocks of Code Expressions If you consider variables, operators and method calls to be the 'words' of the Java language, then an expression is equivalent to a 'phrase'. An expression is a series of variables, operators and method calls that evaluate to a single value. The expression performs the computation specified as well as returns the value that is the result of the computation. The code 2 + 3 is an example of a simple expression.
Continuing our analogy, statements are somewhat similar to "sentences'. There are three types of statements to consider:
An expression statement can be constructed by combining one or more expressions and terminating them with a semicolon (;). Here are a couple of example expression statements:
The next level up in organization is the block of code. In our analogy, this is roughly equivalent to a 'paragraph'. A block is a grouping of zero or more statements between balanced curly braces. Local variables can be defined within a code block, restricting their scope to within that block. An important point to note about code blocks is that they may be used wherever a single statement would be allowed. The code block is just treated as a somewhat more complex statement. The highest level block is the class body. Then there are method bodies. Then blocks defined for while and for loops and by if/else statements. Hence blocks can reside within blocks (be 'nested').
|