Array:
- Array is referenced data type used to store multiple values.
- we can not change size of array at runtime.
- memory can not be altered Once the memory has been allocated for an array at the run time.
- Arrays are objects
Need of array:
- In real time projects array is used to collect same type of objects to send all values with single method call.
Problem of primitive data types:
- We can not store values in continuous memory locations using primitive data types .
- We have two problems due to this limitation
1.we cant store multiple values:
- If we want to store multiple values , say 1 to 10 , we must create 10 variables .
- All those 10 variables are created at different locations.
2.In single method call we can not pass multiple values :
- we can not pass all values to the remote computer with single network call or method call.Using primitive variables , which increases burden on network and also increase number of lines of code in program.
Solution:
- Values must be stored in continuous memory locations with single variable name. To solve above two problems ,
- This can be possible using array.
- In java array is reference data type . it is used to store fixed number of multiple values of same type in continuous memory locations.
- Like other data types array is not a keyword it is a concept. it creates continuous memory locations using other primitive or reference types.
Array Limitation:
- Array size is fixed , means we can not increase or decrease its size after its creation.
Array Declaration:
- <Accessibility modifier><Modifier><datatype>[] <array variable name>;
For example:
- public static int[] i;
- public static Example[] e;
- Like in C or C++ , in java we can not mention array size in declaration part. It leads Compile time error.
- int[5] i; Compile time Error: illegal start of expression
- int [] i;
Possible declaration:
- After data type : int[] i;
- Before variable name : int []i;
- After variable name : int i[];
Type of arrays:
- Single dimensional : int [] i;
- Two dimensional : int[][] i;
- Three dimensional : int [][][] i;
Array object creation:
- <Accessibility Modifier><Modifier><data type>[]<array name>={<list of values with , separator>};
- int [] ia={10,20,30,40};
No comments