Sunday, January 2, 2011

Java Tutorial #16

0
Introduction to Arrays
Array - it is a variable that contains many values. It can store values with the same data type.
-It is a collection of variables of the same type that are referenced by a common name.
Syntax
Type var_name [ ] = new Type[Size];
Where: “var_name” is the name of the array, Type is the data type, and Size is how many elements this array will hold.
-All arrays have 0 as the index of their first element. So, If you declaring
int input[ ] = new int [9];
-You are declaring an integer array that has 10 elements, input[0] through                                input[9].  

Assigning values to each items in the array
The first way of assigning values to each array's item is by writing the values one by one. You can assign a value to each of the elements by writing this.

var_name[index] = some_value;

For example,

input[0] = 67;

This will assign “67 as the value of the first element in the array. (NOTE: THE COMPUTER STARTS COUNTING FROM 0 TO SOME_VALUE.) The subscript “0 is called an index and “input is the name of the array. The index is simply a system of numbering items in the arrays content. So, If you like to assign a value in the second element, you will write 1 as index.

The second way of assigning is called “Array Initializer”. This will initialize a value to each element without typing the array name and the index value. By writing this,

int input[ ] = {2, 7, 8, 93, 83};

You don't have to spend much of your time to declare the array's size and index. This will assign“2 as the 0 element and “83 as the 4 element. Initializers will automatically counts how many element you put in the array and this will also automatically assign an index to each of the element. “2 is input[0], “7 is input[1] and so on.

Dislaying Array’s Element
TO DISPLAY: 
Simply call out the println function and concate it with some string.
Just write the name of the array and the index of the element in the array.
 Consider this Example. These programs will use both of the ways of displaying Array's Element.

By using the first way:


By using the second way:


The output:







No Response to "Java Tutorial #16"

Post a Comment