Basic JAVA 9
Array in Java
An array is a collection of similar type of elements that have contiguous memory location. Array is a container object that hold values of homogenous type. It is also known as static data structure because size of an array must be specified at the time of its declaration.
An array can be either primitive or reference type. It gets memory in heap area. Index of array starts from zero to size-1.
Advantage of Java Array
Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.
Disadvantage of Java Array
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.
Types of Array
Single Dimensional Array
Multidimensional Array
1. Single Dimensional Array
Syntax:
datatype [ ] identifier;
or
datatype identifier [ ];
Both are valid syntax for array declaration. But the former is more readable.
Example :
int[] arr;
char[] arr;
short[] arr;
long[] arr; //one dimensional array
int[][] arr; //two dimensional array.
Initialization of Array
new operator is used to initialize an array.
Example :
int[] arr = new int[10]; //declaration and instantiation
or
int[] arr = {10,20,30,40,50}; //declaration, instantiation and initialization
Accessing array element
As mention ealier array index starts from 0. To access nth element of an array.
Syntax:
arrayname [ n-1 ];
Example : To access 4th element of a given array
int[] arr={10,20,30,40};
System.out.println("Element at 4th place"+arr[3]);
The above code will print the 4th element of array arr on console.
Using foreach or enhanced for loop
JDK 1.5 introduces special type of for loop called foreach loop to access elements of array. Using foreach loop you can access complete array sequentially without using index of array. Let us see an exapmle of foreach loop.
Example:
class Test
{
public static void main(String[] args)
{
int[] arr={10,20,30,40};
for(int x:arr)
{
System.out.println(x);
}
}
}
Output :
10
20
30
40
2. Multidimensional Array
Syntax:
dataType[ ][ ] identifier;
or
dataType identifier[ ][ ];
or
dataType [ ]identifier[ ];
Instantiation of Array
int[ ][ ] arr=new int[3][3]; //3 row and 3 column
Let's see the simple example to declare, initialize and print the 2Dimensional array.
Example:
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3 i="" span="" style="color: #7f0055; font-weight: bold;">for3>
(
int j=0;j<3 j="" span="" style="color: #7f0055; font-weight: bold;">System3>.out.print(arr[i][j]+
" ");
}
System.out.println();
}
}}
Test it Now
Output:1 2 3
2 4 5
4 4 5
No comments:
Post a Comment
Hai , Post your comment . (required, Bugs, Errors )