What is an Array?
When you need to store same ‘type’ of data that can be logically grouped together, then you can go for java array.
For example, if you want to store the list of countries in single object then arrays are useful.
Array: An array stores a sequence of values that are all of the same type.
Syntax to declare array: dataType[] arrayRefVar; or dataType arrayRefVar[];
Example: String countries[];
Array Instantiation: dataType[] arrayRefVar = new dataType[arraySize];
Example: countires = new String [5];
or countries = {"country1", "country2", "country3", "country4", "country5"};
5 inside the [] bracket says size of array means you are going to store 5 country names into countries array.
Note: Once Array is defined , the size of an array is fixed and cannot increase to accommodate more elements.Size of an array can be accessed by using length field like ".length". It is java final instance field.
How to retrieve elements from an array?
The array elements are accessed through the index. Array indices are 0-based; that is, they start from "0 to arraylength-1".
In our example index starts from 0 to 4 (because index starts from 0 to sizeofarray-1).
Though we view the array as cells of values, internally they are cells of variables. A java array is a group of variables referenced by a common name. Those variables are just references to a address and will not have a name. These are called the ‘components’ of a java array. All the components must be of same type and that is called as ‘component type’ of that java array.
Example:
************************************************
public class ArrayExample {
/**
* Passing Arrays to Methods: Following method specifies that we can
* pass arrays as input parametres for method
* @param measures
*/
public void getArrayElements(float[] measures) {
int i = 0;// declared just for index value.
for (float f : measures) {
++i;
System.out.println("Values at index " + i + " is " + f);
}
}
/**
* Returning an Array from a Method: In following method we are
* returning array.
* @return
*/
public double[] getArray() {
double[] values = new double[] { 1.2, 2.2, 3.2 };
return values;
}
/**
* @param args
*/
public static void main(String[] args) {
/**
* Following lines of code explains about array of strings and
* retrieving using for loop
*/
String countries[] = new String[] { "country1", "country2",
"country3", "country4", "country5" };
for (int i = 0; i < countries.length; i++) {
System.out.println("index of an array is " + i
+ " and values at index " + i + " is " + countries[i]);
}
/**
* Following lines of code explains about array of integeres and
* retrieving using for each loop
*/
int numbers[] = new int[] { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.length; i++) {
System.out.println("index of an array is " + i
+ " and values at index " + i + " is " + numbers[i]);
}
float[] units = new float[] { 100f, 200f, 300f, 400f, 500f };
ArrayExample arrayExample = new ArrayExample();
// Passing Arrays to Methods:
arrayExample.getArrayElements(units);
// Returning an Array from a Method:
double[] values = arrayExample.getArray();
for (double d : values) {
System.out.println("values of double array are " + d);
}
}
}
************************************************
Java Array Default Values: After you instantiate an array, default values are automatically assigned to it in the following manner.
byte --------------– default value is zero
short --------------– default value is zero
int --------------– default value is zero
long --------------– default value is zero, 0L.
float --------------– default value is zero, 0.0f.
double --------------– default value is zero, 0.0d.
char --------------– default value is null, ‘\u0000′.
boolean --------------– default value is false.
reference types --------------– default value is null.
Notice in the above list, the primitives and reference types are treated differently.
Programming with arrays: Before considering more examples, we consider a number of important characteristics of programming with arrays.
If arrays are not there in programming language, imagine if you want to store list of countries in individual java variables and manipulate them. You will have more than hundred variables to manage.So Array is the most important thing in any programming language.
When you need to store same ‘type’ of data that can be logically grouped together, then you can go for java array.
For example, if you want to store the list of countries in single object then arrays are useful.
Array: An array stores a sequence of values that are all of the same type.
Syntax to declare array: dataType[] arrayRefVar; or dataType arrayRefVar[];
Example: String countries[];
Array Instantiation: dataType[] arrayRefVar = new dataType[arraySize];
Example: countires = new String [5];
or countries = {"country1", "country2", "country3", "country4", "country5"};
5 inside the [] bracket says size of array means you are going to store 5 country names into countries array.
Note: Once Array is defined , the size of an array is fixed and cannot increase to accommodate more elements.Size of an array can be accessed by using length field like ".length". It is java final instance field.
How to retrieve elements from an array?
The array elements are accessed through the index. Array indices are 0-based; that is, they start from "0 to arraylength-1".
In our example index starts from 0 to 4 (because index starts from 0 to sizeofarray-1).
Example:
************************************************
public class ArrayExample {
/**
* Passing Arrays to Methods: Following method specifies that we can
* pass arrays as input parametres for method
* @param measures
*/
public void getArrayElements(float[] measures) {
int i = 0;// declared just for index value.
for (float f : measures) {
++i;
System.out.println("Values at index " + i + " is " + f);
}
}
/**
* Returning an Array from a Method: In following method we are
* returning array.
* @return
*/
public double[] getArray() {
double[] values = new double[] { 1.2, 2.2, 3.2 };
return values;
}
/**
* @param args
*/
public static void main(String[] args) {
/**
* Following lines of code explains about array of strings and
* retrieving using for loop
*/
String countries[] = new String[] { "country1", "country2",
"country3", "country4", "country5" };
for (int i = 0; i < countries.length; i++) {
System.out.println("index of an array is " + i
+ " and values at index " + i + " is " + countries[i]);
}
/**
* Following lines of code explains about array of integeres and
* retrieving using for each loop
*/
int numbers[] = new int[] { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.length; i++) {
System.out.println("index of an array is " + i
+ " and values at index " + i + " is " + numbers[i]);
}
float[] units = new float[] { 100f, 200f, 300f, 400f, 500f };
ArrayExample arrayExample = new ArrayExample();
// Passing Arrays to Methods:
arrayExample.getArrayElements(units);
// Returning an Array from a Method:
double[] values = arrayExample.getArray();
for (double d : values) {
System.out.println("values of double array are " + d);
}
}
}
************************************************
Java Array Default Values: After you instantiate an array, default values are automatically assigned to it in the following manner.
byte --------------– default value is zero
short --------------– default value is zero
int --------------– default value is zero
long --------------– default value is zero, 0L.
float --------------– default value is zero, 0.0f.
double --------------– default value is zero, 0.0d.
char --------------– default value is null, ‘\u0000′.
boolean --------------– default value is false.
reference types --------------– default value is null.
Notice in the above list, the primitives and reference types are treated differently.
Programming with arrays: Before considering more examples, we consider a number of important characteristics of programming with arrays.
- Zero-based indexing: We always refer to the first element of an array a[] as a[0], the second as a[1], and so forth.
- Array length: Once we create an array, its size is fixed. You can refer to the length of an a[] in your program with the code a.length.
- Memory representation: When you use new to create an array, Java reserves space in memory for it (and initializes the values). This process is called memory allocation.
- Bounds checking: When programming with arrays, you must be careful. It is your responsibility to use legal indices when accessing an array element. Like if you have array of size 5 and if you try to access element at position 6, it throws exception(Array Out of bounds). So be careful with index value when you are retrieving elements from an array.
Some other useful operations provided by methods in the java.util.Arrays class, are:
import java.util.Arrays;
public class ArraySortExample {
public static void main(String a[]) {
/**
* Following lines of code is related to sort() method to sort an
* array in ascending numerical order.
*/
int[] values = new int[] { 58, 60, 56, 90, 98, 40 };
System.out.println("Before sorting an array" + "\t"
+ Arrays.toString(values));
Arrays.sort(values); // to sort an array
System.out.println("After sorting an array" + "\t"
+ Arrays.toString(values));
/**
* binarySearch method searchs an array for key which we hve
* entered. If it found in an array then it returns the index of value
* otherwise returns -1.So following line prints the index of 98
* which is 4.
* Note:To perform binarySearch array must be an sorted
* array.
*/
int[] values1 = new int[] { 58, 60, 61, 90, 98, 100 };
System.out.println(Arrays.binarySearch(values1, 98));
/**
* Following lines of code explains the fill() method. Fill method
* fills the values of an array to specified value. Below lines of
* code fill the values2 array values as 10 specified in fill method.
*/
int[] values2 = new int[4];
Arrays.fill(values2, 10);
System.out.println(Arrays.toString(values2));
/**
* Following lines of specifies how arrays can be compared. By
* using equals() method we can do this as follows.
* Here we got both arrays are equal statement
*/
int values3[] = new int[] { 100, 200, 300, 400 };
int values4[] = new int[] { 100, 200, 300, 400 };
if (Arrays.equals(values3, values4)) {
System.out.println("Two arrays are equal");
} else {
System.out.println("Two arrays are Unequal");
}
}
}
Output of above example:
Before sorting an array [58, 60, 56, 90, 98, 40]
After sorting an array [40, 56, 58, 60, 90, 98]
4
[10, 10, 10, 10]
Two arrays are equal
- Searching an array for a specific value to get the index at which it is placed (the binarySearch() method).
- Comparing two arrays to determine if they are equal or not (the equals() method).
- Filling an array to place a specific value at each index (the fill() method).
- Sorting an array into ascending order. This can be done either sequentially, using the sort() method, or concurrently, using the parallelSort() method introduced in Java SE 8. Parallel sorting of large arrays on multi-processor systems is faster than sequential array sorting.
Example:**********************************
import java.util.Arrays;
public class ArraySortExample {
public static void main(String a[]) {
/**
* Following lines of code is related to sort() method to sort an
* array in ascending numerical order.
*/
int[] values = new int[] { 58, 60, 56, 90, 98, 40 };
System.out.println("Before sorting an array" + "\t"
+ Arrays.toString(values));
Arrays.sort(values); // to sort an array
System.out.println("After sorting an array" + "\t"
+ Arrays.toString(values));
/**
* binarySearch method searchs an array for key which we hve
* entered. If it found in an array then it returns the index of value
* otherwise returns -1.So following line prints the index of 98
* which is 4.
* Note:To perform binarySearch array must be an sorted
* array.
*/
int[] values1 = new int[] { 58, 60, 61, 90, 98, 100 };
System.out.println(Arrays.binarySearch(values1, 98));
/**
* Following lines of code explains the fill() method. Fill method
* fills the values of an array to specified value. Below lines of
* code fill the values2 array values as 10 specified in fill method.
*/
int[] values2 = new int[4];
Arrays.fill(values2, 10);
System.out.println(Arrays.toString(values2));
/**
* Following lines of specifies how arrays can be compared. By
* using equals() method we can do this as follows.
* Here we got both arrays are equal statement
*/
int values3[] = new int[] { 100, 200, 300, 400 };
int values4[] = new int[] { 100, 200, 300, 400 };
if (Arrays.equals(values3, values4)) {
System.out.println("Two arrays are equal");
} else {
System.out.println("Two arrays are Unequal");
}
}
}
Output of above example:
Before sorting an array [58, 60, 56, 90, 98, 40]
After sorting an array [40, 56, 58, 60, 90, 98]
4
[10, 10, 10, 10]
Two arrays are equal
*********************************************
No comments:
Post a Comment