• No results found

Scope of Variables

In document JAVA (Page 30-36)

Data Types

3.3 Scope of Variables

A variable's scope is the region of a program within which the variable can be referred to 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.

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

• Instance variables

• Class variables

• Local variable

Instance and class variables are declared inside a class. Instance variable are created when the objects are instantiated and therefore they are associated with the objects. They take different values for each object. On the other hand, class variables are global to a class and belong to the entire set of objects that class creates. Only one memory location is created for each class variable.

Variables declared and used inside methods are called local variables. They are called so because they are not available for use outside the method definition. Local variables can also be declared inside program blocks that are defined between an opening brace { and a closing brace }.These variables are visible to the program only from the beginning of its program block to the end of the program block. When the program control leaves a block, all the variables in the block will cease to exist. The are of the program where the variable is accessible (i.e. usable) is called its scope.

3.4 Array

An array is a group of contiguous or related data items that share a common name.

Or we can say that an array stores multiple variables of

• the same type.

• a specific number of indices ("slots").

• you access an element by using its index.

3.4.1 One-Dimensional Arrays

A list of items can be given one variable name using only one subscript and such a variable is called a single-subscript variable or a one-dimensional array.

Declaration of Arrays:

type arrayname [] = new type[size];

For example we want to represent a set of five numbers, say (35, 40, 20, 57, 19) by an array variable number, then we may create the variable number as follows

int number[]=new int[5];

and computer reserves five storage locations as shown below

35 40 20 57 19

number[0] number[1] number[2] number[3] number[4]

Note that java creates arrays starting with a subscript of 0 and ends with a value one less than the size specified. Unlike C, Java protects arrays from overruns and underruns. Trying to access an array beyond its boundaries will generate an error message.

Initialization of Arrays:

arrayname[subscript]=value;

we can also initialize array automatically in the same way as the ordinary variables when they are declared, as shown below.

type arrayname[ ] = {list of values};

Example :

int number [ ] = {35, 40, 20, 57, 19};

Array Length Array Length

In java, all arrays store the allocated size in a variable named length. We can access the length of the array a using a.length. Example:

int aSize = a.length;

3.4.2 Two-Dimensional Arrays

So far we have discussed the array variables that can store a list of values. There will be situations where a table of values will have to be stored. Consider the following data table, which shows the value of sales of three items by four salesgirls:

Item1 Item2 Item3

Salesgirl #1 310 275 365

Salesgirl #2 210 190 325

Salesgirl #3 405 235 240

Salesgirl #4 260 300 380

The table contains a total of 12 values, there in each line. We can think of this table as a matrix consisting of four rows and three columns. Each row represents the values of sales by a particular salesgirl and each column represents the values of sales of a particular item.

For creating two-dimensional arrays, we must follow the same steps as that of simple arrays, we may create a two-dimensional array like this:

type arrayname[][]=new type[row][col];

int myarray = new int[3][4];

like the one-dimensional array, two-dimensional array may be initialized by following their declaration with a list of initial values enclosed in braces. For example,

int table[2][3] = {2, 2, 2, 4, 4, 4};

initialize the elements of the first row to zero and the second row to one. The initialization is done row by row. The above statement can be equivalently written as

int table[ ] [ ] = { {2, 2, 2}, {4, 4, 4}};

by surrounding the elements of each row by braces.

3.5 Strings

Internally, a String is an array of characters, an array of char. The Java API, however, considers a String to be an object. Therefore, you benefit from built-in methods and property to help you handle strings.

3.6 Operators

3.6.1 Arithmetic Operators

Operator Name Use Description

+ Addition Op1 + op2 Adds op1 and op2 - Subtraction Op1 - op2 Subtracts op2 from op1

* multiplication Op1 * op2 Multiplies op1 by op2 / Division Op1 / op2 Divides op1 by op2

% modulus (or mod) Op1 % op2 Computes the remainder of dividing op1 by op2 The arithmetic operators return a number.

numeric return value = <operand1> <operator> <operand2>;

example: myLongString = myShortString + myOtherString;

• + addition

o adds two numbers

o concatenates two string objects

• - subtraction

o subtract one number from another

• * multiplication

o multiply two numbers

• / division

o divide two numbers

• % modulus

o the remainder of an integer division o 5 % 3 = 2 Because 5/3 = 1 and leaves 2.

o myRemainder = 5 % 3;

3.6.2 Assignment Operator

You use the assignment operator, =, to assign one value to another.

Compound Assignment 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

&= 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

>>>= Op1 >>>= op2 Op1 = op1 >>> op2

3.6.3 Conditional Operator

Operator Use Description

?: Exp1 ? exp2 : exp3 If op1 is true, returns op2. Otherwise, returns op3. (This is the conditional operator.)

3.6.4

3.6.4 Special OperatorsSpecial Operators

[] 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 3.6.5 Relational Operators

Logical operators test a condition by comparing values and return a boolean value (true or false).

• == equal (two adjacent equal signs) if (sum = = 100) { // do something ...

WARNING: Testing for identical values with = = is different from assigning a value with =

• != not equal

if (sum != 100) { // do something ...

• > greater than

if (sum > 100) { // do something ...

• < less than

if (sum < 100) { // do something ...

• >= greater than or equal to

if (sum >= 100) { // do something ...

• <= less than or equal to

if (sum <= 100) { // do something ...

Here's two comparison operators in a sequence:

isBigSum = sum > 100;

The variable isBigSum gets the value true only if the sum is greater than 100.

3.6.6 Boolean Logical Operators

• & - ampersand is the logical and operator

boolean isAllExpensive = (cost1 >= 100) & (cost2 >= 100);

Both cost1 and cost2 must be >= 100 to return true and both cost1 and cost2 are evaluated

• && - double ampersand is the logical and operator that can "shortcircuit" when appropriate

boolean isAllExpensive = (cost1 >= 100) && (cost2 >= 100);

// Both cost1 and cost2 must be >= 100 to return true and if cost1 fails the test, cost2 is NOT evaluated.

• | - the logical or operator is the "pipe" key

boolean hasExpensive = (cost1 >= 100) | (cost2 >= 100);

Either cost1 or cost2 must be >= 100 to return true and both cost1 and cost2 are evaluated

• || or - double "pipe" is the logical or operator that can "shortcircuit" when appropriate

boolean isAllExpensive = (cost1 >= 100) || (cost2 >= 100);

Either cost1 or cost2 must be >= 100 to return true and if cost1 passes the test, cost2 is NOT evaluated.

Note: Do not confuse the two forward slashes of comments (//) with the two "pipes" of one of the logical operators (||).

Truth table

Operand1 Operand2 == != && ||

True true True false true true

true false False true false true

False true False true false true

False false True false false false

3.6.7 Incrementing and Decrementing

These short cut unary 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

Note the difference between prefix versus post-fix.

3.6.8 Bitwise Operators

Bitwise operators are used for testing the bits, or shifting them to right or left. Bitwise operators may not be applied to float or double.

Operator Meaning & bitwise AND ! bitwise OR

^ bitwise exclusive OR ~ one’s complement << shift left

>> shift right

>>> shift right with zero fill

In document JAVA (Page 30-36)