1.9 Arrays in Java.
Array : Array can hold only homogeneous data elements.
0 1 2 n-1
0 1 2 2 3
Example :
student[] s = new student[100];
s[0] = new student(); //correct
s[1] = ne customer(); //wrong
-> but we can resolve this proble using object array.
object[] o = new object[100];
o[0] = new student(); //correct
o[1] = new customer(); //correct
1. Array are fixed in soze.
2. Array are hold homogeneous datatype.
3. underlying data structure not accepted.
10 | 25 | 46 | ----- | 89 |
array size : n elements
index range : 0 to n-1
arrayNmae[2] : 3rd element
Array Declaration:
int[] arr1; //array of int type.
float[] array1; //array of float type.
char[] array1; //array of char type.
ArrayNmae = new arrayType[size];
arr1 = new int[5];
arr2 = new float[10];
arr3 = new char[20];
int arr1;
arr1 = new int[5];
25 | 40 | 56 | 98 | 120 |
Strore Varues :
arr1[0] = 25;
arr1[1] = 40;
arr1[2] = 56;
arr1[3] = 98;
arr1[4] = 120;
System.out.println(arr1[3]);
for(int i =0 ; i<5; i++)
{
System.out.println(arr1[i])
}
Example Program1 :
class Program1
{
public static void main(String args[])
{
System.out.println("progrm started");
int arr1; //declaration
arr1 = new int[5]; //initialization
//Store Values.
arr1[0] = 25;
arr1[1] = 40;
arr1[2] = 56;
arr1[3] = 98;
arr1[4] = 120;
System.out.println("4th element"+arr1[3]);
System.out.println("Array elements");
for(int i =0 ; i<5; i++)
{
System.out.println(arr1[i])
}
}
}
for more details follow video given below.
Comments
Post a Comment