Arrays

click here for complete presentation on arrays

Declaration of an Array type[] name;

To declare an array of a specified type with a given name:

type[] name;

int[] list; // declaration

list = new int[10]; // instantiation

Data types are String, int, double, boolean, char, Student, Employee or any object etc..

Example making an array with initial values

(data type)[] variable name = {data values};

int[] nums = {34,32,34,56}

Example making an array with no values

(data type)[] variable name = new (data type) [length of array];

int[] nums = new int[10];
or
int[] nums;
nums = new int[10];

Put data into Arrays

variable [index value] = some input;

nums[0] = 50;
nums[4] = 10;
nums[8]=nums[4];

50 0 0 0 10 0 0 0 10 0 value of array
0 1 2 3 4 5 6 7 8 9 index

Going through each element of an array forward

Prints all the elements of the array

for (int i=0; i < nums.length; i++)    //output: 50, 0, 0, 0, 10….etc
{

//array processing goes here

System.out.println(nums[i]);

}

Prints all the elements of the array backwards

for (int i=0; i < nums.length; i++)    //output: 0, 10, 0,0,0,10 etc..
{

System.out.println(nums[i]);
}

Adding 1 to each element in the array

for (int i=0; i < nums.length; i++)    
{

nums[i]++;

}

Use Scanner to put values into an array

String[] sInputs = new String[10];

for (int i=0; i < sInputs.length; i++)
{

System.out.println(“Enter in a String”);
sInputs[i] = scan.nextLine();

}

Printing all the even numbers in the array

for (int i=0; i < sInputs.length; i++)    
{

if (nums[i] % 2 ==0)
     System.out.println(nums[i]);

}

Summing up all the numbers in the array

int sum=0;
for (int i=0; i < nums.length; i++)    
{

sum=sum + nums[i];

}

Setting one array element equal to another array element assuming num.length = num2.length

int [] num2 = {3,4,5,6,400)   
for (int i=0; i < nums.length; i++)    
{

nums[i] = num2[i];

}

Scanner Class

Credit: A Slides are modified with permission from Barry Wittman at Elizabethtown College
This work is licensed under an Attribution-NonCommercial-ShareAlike 3.0 Unported License