You are on page 1of 55

 Now suppose your program requirement is such that you need 10

variables of type int.


 In this case, you will have to declare 10 variables of type int as follows:
 int a1;
int a2;
int a3;
int a4;
int a5;
int a6;
int a7;
int a8;
int a9;
int a10;
 The above declarations will put the unnecessary burden of maintenance on
the programmer. Instead of declaring so many variables, how about
declaring a single variable and then have all these 10 values assigned to
this variable? This is what we are going to do when we define an array and
assign values to it.
 Let’s begin with arrays in Java.
WHAT IS ARRAY?
 Arrays are nothing but a data structure that is used to hold the data
elements of the same type in a sequential fashion. From the above
example, you can change the definition of ten variables into a single
variable and store all the ten values using subscripts.
 Let us do it in the below given way:
 A[0] = 1;
A[1] = 2;
A[2] = 3;
A[3] = 4;
A[4] = 5;
A[5] = 6;
A[6] = 7;
A[7] = 8;
A[8] = 9;
A[9] = 10;
 We have stored all ten values in index-based variable. The first index
starts from 0. So the first value is at 0th index and the last value is at
9th index. These indices are also called Subscripts.
 In the computer memory, the above Array A will be represented as:

 Now we can define an array as a variable that is a collection of elements of the same data
type and stored at contiguous memory locations. The size of an array is specified at the time
of declaration and hence the size is fixed.

The arrays that we are going to discuss in this tutorial are Fixed-size or Static arrays. 
Java also supports dynamic arrays called “ArrayList” whose size can be altered on the fly. We
will discuss ArrayList in detail later.

Some of the characteristic of Arrays in Java are listed below:


 In Java, an Array is an object instantiated from a dynamically generated class.
 Internally, Java array implements Serializable and Cloneable interfaces.
 Java array also has object class as its parent class.
 You can store built-in and derived type values in Java arrays.
 You can get the length of an array using length member and not sizeof like in C/C++.
 Java allows single as well as multi-dimensional arrays.
THE VALID SYNTAX OF DECLARATION CAN BE
HOW TO DECLARE AN ARRAY IN
JAVA
Java Array – Creation & Initialization
 Arrays need to be created to use them in the program. Creating arrays
includes specifying the data type of elements that the array is going to hold
as well as the number of elements the array is going to contain.
 We will discuss creating arrays in various ways and also in different
methods using which we can initialize arrays.

In this program, we have declared an int array and then instantiated it using new. Then
we have initialized elements at indices 0 and 1 with values 1 and 3 respectively.
Finally, we print all the elements of the array. Note that the elements we did not
initialize are having default values as 0 since the type of array is int.
JAVA PROGRAM TO ILLUSTRATE STORE AND
PRINT MARKS OF 5 STUDENTS
JAVA ARRAYSINDEXOUTOFBOUNDSEXCEPTION
 A common mistake of all programmers while using arrays is they try to
access indexes which are outside the limit. For example, if an array is of
length 6 then the program can use any index of the array in between 0 and
5. But sometimes the program tries to access elements outside this range.
That is when the compiler throws a ArraysIndexOutOfBoundsException
error.


 The ArrayIndexOutOfBounds e
xception is thrown if a program
tries to access an array index that
is negative, greater than, or equal
to the length of the array.
JAVA PROGRAM TO ILLUSTRATE THE USE OF ARRAYS IN A
PROGRAM: 
As you can see, we are
converting the int value
into double. This is called
type casting in Java.
PASSING AN ARRAY TO A METHOD OR FUNCTION
 We can also pass the Java array to methods or functions, just like normal
variables. Passing an array to method helps us to reuse the same logic on any
array.
 When we pass an array as an argument to a method, it is actually the address of
the first element of the array (base address) which is passed as a reference.
Therefore, if we make any changes to this array in the method, it will affect the
array.
Syntax:
 When we pass an array to a method, we specify the name of the array without
any square brackets within the method call.
MULTI-DIMENSIONAL ARRAYS
 Multi-dimensional arrays are arrays of arrays in which each element of the
array holds the reference of other arrays. We can also call them Jagged Arrays.
The most commonly used multi-dimensional array is a two-dimensional
array.
 A two-dimensional array is an array in which each element is a one-
dimensional array.
 For example, a two-dimensional array myArray [ M ][ N ] is an M by N table
with M rows and N columns containing M N elements.
 By multiplying the number of rows with the number of columns we can
determine the number of elements in a two-dimensional array. For example,
the number of elements in an array arr [7][9] is calculated as 7 9 = 63.
SYNTAX OF DECLARING TWO-DIMENSIONAL
ARRAYS IS:
PROGRAM TO UNDERSTAND THE TWO
DIMENSIONAL ARRAY
ARRAY OF OBJECTS IN JAVA
 Java is an object-oriented programming language. Most of the work done
with the help of objects. We know that an array is a collection of the same
data type that dynamically creates objects and can have elements of primitive
types. Java allows us to store objects in an array. In Java, the class is also a
user-defined data type. An array that conations class type elements are
known as an array of objects. It stores the reference variable of the object.

Creating an Array of Objects


 Before creating an array of objects, we must create an instance of the class by
using the new keyword. We can use any of the following statements to create
an array of objects.
 
 Syntax
 In the following program, we have created a class named Product and initialized
an array of objects using the constructor. We have created a constructor of the
class Product that contains product id and product name. In the main function,
we have created individual objects of the class Product. After that, we have
passed initial values to each of the objects using the constructor.
Cloning of arrays
There are 2 different types of cloning of arrays, they are as follows –
1. Cloning single-dimensional arrays
 Cloning a single-dimensional array, such as Object[ ], means performing a “deep
copy” operation in which a new array is created, which contains copies of the
elements of the original arrays. We can perform cloning of arrays in Java with
the help of the clone() method:
 Cloning is necessary when we want to create an object with a similar state as the
original object. In short, with the help of Cloning single-dimension, we can
create the copy of the original object.
2. Cloning of multi-dimensional arrays
 Cloning a multi-dimensional array, such as Object[ ][ ], means performing a
“shallow copy”. It creates only a single new array with each element of the array
as a reference to an element of the original array.
 In the cloning of multi-dimensional arrays, sub arrays are shared, that is, they are
not cloned.
THE ARRAY CLASS IN JAVA
 The package java.util.Arrays contain the Array class to perform operations on
Arrays. It provides many static methods which are helpful in manipulating and
analyzing arrays and getting useful results out of them.
 With these methods, we can do the searching, sorting on arrays’ elements, filling an
array with a particular value, comparing arrays, etc. We will discuss some
important methods of Java Arrays class:
1. int compare(array1, array2)
This method compares two arrays in lexicographic order. We pass two arrays as
parameters to its methods. It returns 1 if array1 is greater than array2, -1 if array1 is
smaller than array2, and a 0 if both arrays are equal to each other.
2. void fill(originalArray, value)
This method is used to fill the specific value to each element of the specified
array with a specific type. This method can also be used with all the other
primitive data types (byte, short, int, etc.).
3. boolean equals(array1, array2)
This method checks whether both the arrays are equal or not and gives the result
either as true or false.
4. int binarySearch(array [], value)
With the help of this method, we can find or search a specified value inside an
array which is given as the first argument. As a result, this method returns the
index of the element in the array. The array must be sorted for this search. If the
element is not found, it returns a negative value.
5. copyOf(originalArray, newLength)
We can copy the specified array to a new array with a specified length. The left
spaces are assigned to default values in the new array.
 Sorting Array In Java
Sorting array elements or ordering them in ascending or descending order is one of
the important operations. Most of the applications need their data to be sorted. Java
provides a filter sort for arrays. We will discuss this in detail under sorting.
Following is a simple example of sorting an array in Jave using Arrays.sort ()
method.
JAGGED ARRAYS IN JAVA
Jagged arrays are multidimensional arrays with each member array of different
sizes. A Jagged array is also an example of an array of arrays.
RESIZING OF ARRAYS
As we Know, Arrays are created on the heap dynamically during execution of the
program. As a result, we can do two things with an array:
• We can decide the number of elements in the array at run-time and do not have to
make any commitment about it while writing the program.
• Once the array is created we can increase or decrease its size during execution.
JAVA PROGRAM TO SORT AN ARRAY IN DESCENDING ORDER
JAVA PROGRAM TO SORT AN ARRAY IN
ASCENDING ORDER
Write the Program to print the minimum element
in array
//-Write a method called readIntegers() with a parameter called count that represents
how many integers the user needs// to enter.
//-The method needs to read from the console until all the numbers are entered, and
then return an array containing the
// numbers entered.
//-Write a method findMin() with the array as a parameter. The method needs to
return the minimum value in the array.
//-In the main() method read the count from the console and call the method
readIntegers() with the count parameter.
//-Then call the findMin() method passing the array returned from the call to the
readIntegers() method.
//-Finally, print the minimum element in the array.
WRITE A PROGRAM TO REVERSE AN ARRAY
 Write a method called reverse() with an int array as a parameter.
 The method should not return any value. In other words, the method is
allowed to modify the array parameter.
 To reverse the array, you have to swap the elements, so that the first
element is swapped with the last element and so on.
 For example, if the array is [1, 2, 3, 4, 5], then the reversed array is [5, 4,
3, 2, 1].
 The method should first print out the newly passed in array as Array = [1,
2, 3, 4, 5]and then once it's been reversed, print it out as Reversed array =
[5, 4, 3, 2, 1]
 TIP: When swapping the elements, use a variable to temporarily hold the
current element.
 In the Below program, we've two integer arrays array1 and array2.
 In order to combine (concatenate) two arrays, we find its length stored
in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen.
 Now, in order to combine both, we copy each element in both arrays to result by
using arraycopy() function.
 The arraycopy(array1, 0, result, 0, aLen) function, in simple terms, tells the program to
copy array1 starting from index 0 to result from index 0 to aLen.
 Likewise, for arraycopy(array2, 0, result, aLen, bLen) tells the program to copy array2 starting from
index 0 to result from index aLen to bLen.
 In the below program, instead of using arraycopy, we manually copy each element of both
arrays array1 and array2 to result.
 We store the total length required for result, i.e. array1.length + array2. length. Then, we create a
new array result of the length.
 Now, we use the for-each loop to iterate through each element of array1 and store it in the result.
After assigning it, we increase the position pos by 1, pos++.
 Likewise, we do the same for array2 and store each element in result starting from the position
after array1.
 Program to Find Transpose of a Matrix
PROGRAM TO MULTIPLY TWO MATRICES USING A
FUNCTION
In the above program, the two matrices are stored in 2d array,
namely firstMatrix and secondMatrix.
We've also defined the number of rows and columns and stored them in
variables rows and columns respectively.
Then, we initialize a new array of the given rows and columns called sum. This
matrix array stores the addition of the given matrices.
We loop through each index of both arrays to add and store the result.
Finally, we loop through each element in the sum array using the for-each loop
 to print the elements.

You might also like