Arrays
Arrays
1. Introduction:
An Array is an index collection of homogeneous elements.
Homogeneous elements is nothing similar type elements.
Advantages:
1. The main advantage of arrays is we can store multiple values of
Same type.
Dis-Advantage:
1. Arrays are fixed in size, once we declare an array we cannot
increase or decrease the size of an array.
2. To use arrays we should know the size in advance, which is not
possible every time.
How to resolve this problem?
We can resolve this problem using collections, we will be learning
collections in our future lectures.
What are the different types of array, how we can declare an Arrays?
In Arrays we have multiple dimensions, they are as.
1. Single dimension array
2. Two dimensional array
3. Three dimensional array
Here, the datatype is the type of element that will be stored in the
array, square bracket[] is for the size of the array, and variableName is the
name of the array.
Initializing an Array:
1. Without new operator
2. With new operator
Here
1. datatype represent type of data we are going to store.
2. VariableName represents, what is the variable-name we are going to give to
our array.
3. {value1,value2,value3,value4....value-n} represent the values we are going
to store.
Example:
Creating an Array using new operator isn’t enough we should add some
elements to it, to add elements we have syntax.
Syntax for adding elements/values to an Array index:
VariableName[i] =value;
here ‘i’ represents index position
example: 0,1,2,3,4...n
example for adding elements to an Array index:
numbers[0]=10;
numbers[1]=20;
numbers[2]=30;
numbers[3]=40;
syntax for retrieving/getting the values from Arrays specific index
variableName[i];
here ‘i’ represents index position
example: 0,1,2,3,4...n
numbers[0];
numbers[1];
numbers[2];
numbers[3];
How to add and retrieve the elements or values to/from an Array:
Example program:
Multi-dimensional Arrays
In java multi-dimensional arrays are nothing but arrays of arrays.
Advantages:
The main advantage is it improves the memory utilization.
Multi-dimensional arrays can be any, but in this course we will discussing only
two, they are as follows.
1. Two dimensional Arrays
2. Three Dimensional Arrays
1. Two dimensional Array:
A Two dimension array one which will be having two Square brackets
defined after the datatype.
Here,
1. the datatype represents the type of value we are going to store in the
array, in square bracket[][]’s we will be defining the size of the array.
2. variableName is the objectName of the array.
3. Datatype[size][size] will be taking the size for the multi-dimensional
arrays.
Note:
You shouldn’t declare the size of the array at left hand side, as
shown below.
Example:
example:
int[2][]; //valid
Int[2][2]; // valid
Example for declaring two-dimensional array:
int [][] numbers=new int[2][];
numbers[0]=new int[3];
numbers[1]=new int[2];
Example program:
package com.core.java.examples;
// assigning values
naturalNumbers[0][0] = 10;
naturalNumbers[0][1] = 20;
naturalNumbers[0][2] = 30;
}
}
Output:
Number at naturalNumbers[0] is:[I@15db9742
============================================
Number at naturalNumbers[0][0] is:10
Number at naturalNumbers[0][1] is:20
Number at naturalNumbers[0][2] is:30
....................>>>>>>>>>>>............................
Number at naturalNumbers[1] is:[I@6d06d69c
-------------------------------------------------------------
Number at naturalNumbers[0][1] is:40
Number at naturalNumbers[0][2] is:50
Example:
package com.core.java.examples;
System.out.println("....................>>>>>>>>>>>............................");
System.out.println("Number at naturalNumbers[0][2] is:" + naturalNumbers[0][2]);
System.out.println("-------------------------------------------------------------");
System.out.println("Number at naturalNumbers[0][2][0] is:" + naturalNumbers[0][2][0]);
System.out.println("/////////////////////<<<<<<<<<<<>>>>>>>>>>>>>/////////////////////");
System.out.println("Number at naturalNumbers[0][2] is:" + naturalNumbers[1][0]);
}
}
Output:
Number at naturalNumbers[0][0] is:[I@15db9742
============================================
Number at naturalNumbers[0][0][0] is:40
Number at naturalNumbers[0][0][1] is:50
============================================
Number at naturalNumbers[0][1][0] is:60
Number at naturalNumbers[0][1][1] is:70
Number at naturalNumbers[0][1][2] is:80
....................>>>>>>>>>>>............................
Number at naturalNumbers[0][2] is:[I@6d06d69c
-------------------------------------------------------------
Number at naturalNumbers[0][2][0] is:90
/////////////////////<<<<<<<<<<<>>>>>>>>>>>>>/////////////////////
Number at naturalNumbers[0][2] is:[I@7852e922
Number at naturalNumbers[0][1][0] is:100
Number at naturalNumbers[0][1][1] is:110
-------------------------------------------------------------------
Number at naturalNumbers[1][1] is:[I@4e25154f
Number at naturalNumbers[0][1][2] is:120
Programs to practice
1. write a java program to store the 10,20,30,40,50,60 values in a 3-dimensional
array and display the values stored in array?
2. write a java program to store the 102,200,300,400,500,600 values in a 3-
dimensional array and display the values stored in array?
3. write a java program to store the 1000,2000,3000,4000,5000,6000 values in a
3-dimensional array and display the values stored in array?
1. write a java program to store the 1.2f,2.3f,3.2f,4.5f,5.2f,6.3f values in a
3-dimensional array and display the values stored in array?
5. write a java program to store the 10.5f,20.1f,30.3f,40.5f,50.2f,60.5f values in
a two-dimensional array and display the values stored in array?
6. write a java program to store the 100.2f,200.3f,300.4f,400.500.600.7f values in
a 3-dimensional array and display the values stored in array?
7. write a java program to store the vowles 'a','e','i','o,'u' values in a
3-dimensional array and display the values stored in array?
8. write a java program to store the consonants 'F','L','M','N','Q','R' values in a
3-dimensional array and display the values stored in array?
9. write a java program to store the consonants 'S','V','W','X','Y', values in a
3-dimensional array and display the values stored in array?
10. write a java program to store the vowles "Hello","Java","Developer" values in a
3-dimensional array and display the values stored in array?
11. write a java program to store the months
"JAN","FEB",",MAR","APR","MAY","JUNE","JULY","AUG"
"SEP","OCT","NOV","DEC" values in a 3-dimensional array and display the values
stored in array?
12. write a java program to store the days
"SUN","MON",","TUE","WED","THU","FRI","SAT" values in a 3-dimensional array and
display the values stored in array?
Methods Available in Arrays
Length variable:
1. length()
a. length method is final
b. It is used to identify the size of given string or string[].
c. This method will be applicable only on String
3) This method returns a new array with the values from an old array.
4) Here datatype represents, type of data your’e storing in an existing-array.
You can take any data type
int, long, float, double, char, short, byte, boolean.
LengthOfArrayYouWantToCreate is nothing but length of the new array you want to create from an existing-array.
for example:
int[] existingArray = { 10, 20, 30, 40, 50, 60 };
System.out.println (newArray[j]);
copyOfRange()
Definition 1: if we want to copy array values from the given Range (beginIndex and
endIndex), then we have to use copyOfRange() method.
Syntax:
---------------------------------------------------------
example:
package com.core.java.examples;
import java.util.Arrays;
}
Output:
new Array Elements are=10
new Array Elements are=20
3. asList() Method
asList( ) method is used to convert an array to a list.
Syntax:
o This method receives an array of wrapper class as a parameter and then returns a list
of array elements.
o In a case if we pass an empty array, then it will throws NullPointerException.
o Here ‘datatype[]’ is the type of array (int[], float[], char[], double[], short[],
byte[], boolean[], long[]) you want to convert to List.
Example:
Examples:
package com.core.java.examples;
import java.util.Arrays;
import java.util.List;
Similar to the above example here we used Integer class. In the code given below, we are converting an array of Integer class to a list of integers.
package com.core.java.examples;
import java.util.Arrays;
import java.util.List;
public class StudyTonight
{
public static void main(String[] args)
{
Integer arr[]= new Integer[] { 12, 34, 22, 87, 98 };
List<Integer> list = Arrays.asList(arr);
System.out.println("List of Integers: " + list);
}
}
Output:
List of Integers: [12, 34, 22, 87, 98]
In this example, we have several arrays of type float, byte, short, etc and get list of each
type by using the asList() method of Arrays class.
package com.core.java.examples;
import java.util.Arrays;
import java.util.List;
public class Main
{
public static void main(String[] args)
{
Float arr1[]= new Float[] { 12.5f, 34.2f, 22.22f, 87.1f, 98.3f };
List<Float> list1 = Arrays.asList(arr1);
System.out.println("List of Integers: " + list1);
Conclusion:
o The asList() method is used to convert array to list of elements.
o This method accepts an array and returns a list of that specified array.
o This method can be called without creating an object as this is the static method
we can directly call it over a class name.
4. sort() Method
o sort() method is used to sort, the elements/values of given array in Ascending Order.
o syntax:
public static void sort(datatype[] array)
o List of Overloading Methods of sort() Method
===================================
1. public static void sort(int[] array1)
2. public static void sort(long[] array2)
3. public static void sort(float[] array3)
4. public static void sort(double[] array4)
5. public static void sort(char[] array5)
6. public static void sort(byte[] array6)
7. public static void sort(short[] array7)
8. public static void sort(boolean[] array8)
We can extend the feature of this sort( ) method by providing a range of an array
with startIndex and endIndex.
Let's see its syntax and examples.
o Syntax:
public static void sort(datatype[] array,fromIndex,toIndex)
o List of Overloading Methods of sort() Method
=================================================================
9. public static void sort(int[] array1,fromIndex,toIndex)
10. public static void sort(long[] array2,fromIndex,toIndex)
11. public static void sort(float[] array3,fromIndex,toIndex)
12. public static void sort(double[] array4,fromIndex,toIndex)
13. public static void sort(char[] array5,fromIndex,toIndex)
14. public static void sort(byte[] array6,fromIndex,toIndex)
15. public static void sort(short[] array7,fromIndex,toIndex)
16. public static void sort(boolean[] array8,fromIndex,toIndex)
package com.core.java.examples;
import java.util.Arrays;
class StudyTonight {
public static void main(String args[])
{
int arr[] = {10, 8, 12, 1, 12, 5, 16, 4, 10, 3, 14, 11, 20, 17, 18};
System.out.println("Array Before Sorting ");
for(int num:arr)
{
System.out.print(num+" ");
}
Arrays.sort(arr);
System.out.println("\nArray After Sorting ");
for(int num:arr)
{
System.out.print(num+" ");
}
}
Output:
Array Before Sorting
10 8 12 1 12 5 16 4 10 3 14 11 20 17 18
Array After Sorting
1 3 4 5 8 10 10 11 12 12 14 16 17 18 20
Example of float:
package com.core.java.examples;
import java.util.Arrays;
class StudyTonight {
public static void main(String args[])
{
float arr[] = {10.3f, 8.2f, 12.4f, 1.3f, 12.2f, 5.1f, 16.6f, 4.4f, 10.2f, 3.6f, 14.1f,
11.1f, 20.2f, 17.1f, 18.1f};
System.out.println("Array Before Sorting ");
for(float num:arr)
{
System.out.print(num+" ");
}
Arrays.sort(arr);
System.out.println("\nArray After Sorting ");
for(float num:arr)
{
System.out.print(num+" ");
}
}
Similarly you can write for double, char, long, short, byte and boolean.
Programs:
---------
Questions:
----------------
double[] x={10.22,30.33,2.44,3.66,5.88,12.56};
char[] x={'a','b','A','m','B','D'};
char[] x={770,'b','A','m','B','D'};
5. binarySearch() Method
• This method belongs to the Arrays class in Java, and it is very helpful to search a key in
large arrays.
import java.util.Arrays;
package com.core.java.examples;
import java.util.Arrays;
Questions:
-----------
1. Write a program to sort an array, and find the 40 element, and return the index position of
an element 40?
Answer:
package com.core.java.examples;
import java.util.Arrays;
int[] numbers = { 10, 20, 30, 50, 60, 40, 80, 90, 110 };
System.out.println("Array before Sorting");
for (int i : numbers) {
System.out.print(i + "");
}
System.out.println("");
Arrays.sort(numbers);
System.out.println("After Sorting");
for (int i : numbers) {
System.out.print(i + "");
}
}
}
1. Write a program to sort an array, and find the 50 element, and return the index position
of an element 50?
Int[] a={10,20,30,40,50,80,100,90,120,110,85,65};
2. Write a program to sort an array, and find the 90 element, and return the index position
of an element 90?
Int[] a={10,20,30,40,50,80,100,90,120,110,85,65};
3. Write a program to sort an array, and find the 80 element, and return the index position
of an element 80?
Int[] a={10,20,30,40,50,80,100,90,120,110,85,65};
4. Write a program to sort an array, and find the 90 element, and return the index position
of an element 90?
Int[] a={10,20,30,40,50,80,100,90,120,110,85,65};
5. Write a program to sort an array, and find the 50 element, and return the index position
of an element 50?
Long[] a={10,20,30,40,50,80,100,90,120,110,85,65};
6. Write a program to sort an array, and find the 90 element, and return the index position
of an element 90?
Char[] a={10,20,30,40,50,80,100,90,120,110,85,65};
7. Write a program to sort an array, and find the 80 element, and return the index position
of an element 80?
Int a={10,20,30,40,50,80,100,90,120,110,85,65};
8. Write a program to sort an array, and find the 90 element, and return the index position
of an element 90?
Int a={10,20,30,40,50,80,100,90,120,110,85,65};
o Syntax:
2. Pubic static returntype binarySearch(T[] a, T key, Comparator<? super T> c)
• Here ‘T’ is the type of array (i.e int, float, char, double, long, short, byte) in
which ever array you want perform search operation you have to give that array.
• The second parameter will be the key which we want to search
• The third parameter will be the comparator to set the order in which the array is
sorted.
By default, array is sorted in ascending order.
Examples:
package com.core.java.examples;
import java.util.Arrays;
import java.util.Comparator;
public class StudyTonight
{
public static void main(String[] args)
{
Integer array[]={90, 55, 49, 42, 33, 25, 8, 6, 1};
Integer key = 33;
int index = Arrays.binarySearch(array, key, new Comparator<Integer>(){
public int compare(Integer o1, Integer o2) {
if(o1>o2)
{
return 1;
}
else
{
return 0;
}
}
});
System.out.print(key+" found at index: "+index);
}
Output:
33 found at index: 4
What if we do not want to perform the binary search on the whole array? In that case, we
must pass the beginning index i.e fromIndex and the ending index i.e toIndex,
Syntax:
public binarySearch(T[] a, fromIndex, toIndex, T key)
===========================================================================
import java.util.Arrays;
public class StudyTonight
{
public static void main(String[] args)
{
byte byteArray[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60};
char charArray[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'};
int intArray[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150};
double doubleArray[] = {5.1, 6.2, 7.2, 8.1, 9.4, 10.2, 11.6, 12.96, 13.2, 14.25, 15.6, 16.4, 17.2};
float floatArray[] = {1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f};
short shortArray[] = {2, 4, 6, 8, 10 ,12, 14, 16, 18, 20};
Output:
25 found at index = 4
25 found at index = 4
d found at index = 3
d found at index = 3
130 found at index = 12
130 found at index = -6
15.6 found at index = 10
15.6 found at index = -6
9.0 found at index = 8
9.0 found at index = -6
16 found at index = 7
16 ound at index = 7
parallelSort() Method
This sorting technique is very fast because it works parallelly to sort elements of
the given array.
syntax:
public static void parallelSort(datatype[] array)
this method accepts the array as a parameter and return the sorted array.
List of Overloading Methods of binarySearch() Method
-----------------------------------------------------
import java.util.Arrays;
class StudyTonight {
public static void main(String args[])
{
int arr[] = {1, 46, 165, 6, 78, 6, 65, 955, 4, 5, 323, 256, 5, 99, 22, 33};
//sorting an array
Arrays.parallelSort(arr);
for(int num:arr)
{
System.out.print(num+" ");
}
}
}
Output:
Programs to practice: