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;