3. Objectives :
Arrays in Java.
Advantages and Disadvantages of array.
Types of array (1D and 2D) :
Declaring an Array.
Creating an Array.
Processing Arrays(Show,sort,max,min) .
The foreach Loops.
Jump in java(break,continue,return).
Stars output. 3
4. Array
*Array is used to store a collection of variables of the same type. By declaring
an array, memory space is allocated for values of a particular type.
*Array in java is index-based, the first element of the array is stored at the 0
index. An index must be a non-negative integer.
4
5. Array Advantages :
Code Optimization: It makes the code optimized, we can retrieve or sort the
data efficiently.
Random access: We can get any data located at an index position easily.
Array Disadvantages :
Size Limit: We can store only the fixed size of elements in the array. It doesn't
grow its size at runtime.
5
6. Types of Array in java :
There are two types of array:
* Single Dimensional Array.
* Multidimensional Array.
6
7. 1.One-Dimensional Array in Java (1-D) :
One-dimensional array(1-D): It is a single array that holds multiple values of the
same type.
Declaring 1D Array :
To use an array in a program, you must declare a variable to reference the array,
and you must specify the type of array.
Syntax to declare an array in java will be like one of them :
dataType[ ] arr ; // preferred way.
dataType [ ]arr ;
dataType arr[ ] ;
7
8. Creating Arrays:
You can create an array by using the new operator with the following syntax:
dataType[ ] arr = new dataType[arraySize];
Or alternatively you can create arrays as :
dataType[ ] arr = {value0, value1, ..., valuek};
8
9. Processing Arrays :
Arrays and Loops: When processing array elements, we often use either for
loop or foreach loop because all of the elements in an array are of the same type
and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and showing the
array elements using for:
9
11. The foreach Loops:
A new for loop known as foreach loop, enables you to traverse the complete
array sequentially without using an index variable.
Example:
The following code displays all the elements in the array myList using foreach:
11
12. 12
Jump: Java supports three jump statement: break, continue and return.
These three statements transfer control to other part of the program.
Example for break and continue statement in an array :
17. Multidimensional Array in Java (2D):
In such case, data is stored in row and column based index (matrix form).
Syntax to Declare 2D Array in Java :
dataType[ ][ ] arr ; (or)
dataType [ ][ ]arr ; (or)
dataType arr[ ][ ]; (or)
dataType [ ]arr[ ];
Example to instantiate Multidimensional Array in Java:
int[ ][ ] arr=new int[3][3]; //3 row and 3 column
Example to initialize Multidimensional Array in Java :
arr[0][0]=1; arr[0][1]=2; arr[0][2]=3;
arr[1][0]=4; arr[1][1]=5; arr[1][2]=6;
arr[2][0]=7; arr[2][1]=8; arr[2][2]=9; 17