Lesson 2 Flashcards
(12 cards)
Are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
Arrays
Advantages of Array
•Code Optimization
•Random access
Disadvantages of Array
Size Limit
Types of Array in java
•Single Dimensional Array
•Multidimensional Array
Array Declaration
dataType[] arrayRefVar;
//preferredway.
or
dataType arrayRefVar[];
// works but not preferred way.
Example of Declaration of array
double[] myList; // preferred way.
or
double myList[]; // works but not preferred way.
Array Initialization example
// declare an array
int[] age = new int[5];
// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
Example: Access Array Elements
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5, 2, 5};
// access each array elements
System.out.println(“Accessing Elements of Array:”);
System.out.println(“First Element: “ + age[0]);
System.out.println(“Second Element: “ + age[1]);
System.out.println(“Third Element: “ + age[2]);
System.out.println(“Fourth Element: “ + age[3]);
System.out.println(“Fifth Element: “ + age[4]);
}
}
Example: Using For Loop
Output:
12
4
5
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
// loop through the array
// using for loop
System.out.println(“Using for Loop:”);
for(int i = 0; i < age.length; i++) {
System.out.println(age[i]);
} } }
Example: Using the for-each Loop
Output:
12
4
5
Output class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
// loop through the array
// using for loop
System.out.println(“Using for-each Loop:”);
for(int a : age) {
System.out.println(a);
} } }
Creating Array
Syntax
arrayRefVar = new dataType[arraySize];
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, …, valuek};
Processing Arrays
The foreach Loops
Example:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
} } }