Saturday, May 28, 2011

TwoArrays in Java

 Two Arrays in Java:Sample program
        public class TwoArrays {

       public static void main(String[] args) {
       int val[] = {13,-4,82,17};
       int twice[] = new int [4];

Array Sum Activity in Java

//here is an Array Sum sample Activity in Java
public class ArraySum {

       public static void main(String[] args) {
               int[] val = {0, 1, 2, 3};
        int sum = 0;
        sum = val[0] + val[1] + val[2] + val[3];
        System.out.println("Sum of all numbers = " + sum);
    }
}

Array Length in Java

Array Length in Java

         In order to get the number of elements in an array, you can use the length field of an array. The length field of an array returns the size of the array.
Syntax:  
             arrayName.length
Example:
            int[] num = new int [100];
            for (int counter = 0; counter<num.length; counter++)
{
System.out.print(num[counter]);

Initializer Lists in java

Initializer Lists in java

In Java you can declare, construct and initialize an array all in one statemet:

int[] data = {23, 38,13,22,-3,0,-25}; //I honestly prefer Initializing Arrays this way

or

int[] data = new int []{23, 38,13,22,-3,0,-25};

Using a Variable as your index in java

Using a Variable as your index in java

sample code:

int x[] = new int [3];

int index;
index = 0;

Array Bounds Checking

Array Bounds Checking
- The length of an arra is how many slots it has. An array of length Number for example has slots indexed 0- (Number -1).

-All indexes should be of Integer type.
-Every-time your compiler says the error. System Out of Bounds something like that. You should automatically know that the problem is with your array. don't waste your time by reading all-through-out your program.

Declaring Arrays

Declaring Arrays

         Arrays must be declared like variables. When declaring an array, you list the data type, followed by a set of square brackets [], followed by the identifier name.

Arrays Defined

Array Defined
           
          An Array stores multiple data items of the same datatype, in a contiguous block of memory, divided into a number of  slots.

          Array is an object that is used to store lists of values. It is made out of contiguous block of memory that is divided into a number of slots. Each slots holds a value and all slots has the same data type.

         - Arrays have indexes
         - Indexes are used to access  any of the slots.