Computing1 Unit4 ArrayConcept
Computing1 Unit4 ArrayConcept
Introducing Arrays
Declaring Array Variables, Creating Arrays,
and Initializing Arrays
Passing Arrays to Methods
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
The entire array Each value has a numeric index
has a single name
0 1 2 3 4 5 6 7 8 9
scores 79 87 94 82 67 98 87 81 74 91
scores[2]
Example:
double[] myList;
or
double myList[];
Creating Arrays
Using new operator to create an array
arrayName = new dataType[arraySize];
It creates an array using new dataType[arraySize]
Example:
double[] myList = new double[10];
arrayVariable.length
For example,
myList.length returns 10
Example: The Length of
Arrays
public class ArrayLength{
public static void main(String[] args){
double[ ] myList=new double[10];
System.out.println(myList.length);
System.out.println(myList[9]);
}
}
Initializing Arrays
Using a loop:
for (int i = 0; i < myList.length; i++)
myList[i] = i;
}
}
}
Declaring, creating, initializing
Using the Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
}
}
}
Passing Arrays to Methods
Java uses pass by value to pass parameters
to a method. There are important
differences between passing a value of
variables of primitive data types and
passing arrays.
For a parameter of a primitive type
value, the actual value is passed.
Changing the value of the local parameter
inside the method does not affect the
value of the variable outside the method.
For a parameter of an array type, the
value of the parameter contains a
reference to an array; this reference is
passed to the method. Any changes to the
array that occur inside the method body
Example: Passing Arrays to
Methods
public class ArrayLength{
public static void main(String[ ] args){
double[ ] myList=new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
printArray(myList);
}
public static void printArray(double[ ] myList){
for(int i=0; i < myList.length; i++){
System.out.println(myList[i]);
}
}
}
Example: Pass by Value
public class Test{
public static void main(String[] args){
int x =1; // x repersents an int values
int[] y = new int[10]; // y represents an array of int values
}
}