0% found this document useful (0 votes)
17 views

Lecture 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Lecture 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Lecture 4:

Arrays

Object Oriented Programming


1
Introduction
• Java provides a data structure, the array, which stores a fixed-size
sequential collection of elements of the same type. An array is
used to store a collection of data, but it is often more useful to think
of an array as a collection of variables of the same type.

• Instead of declaring individual variables, such as number0,


number1, ..., and number99, you declare one array variable such
as numbers and use numbers[0], numbers[1], and ..., numbers[99]
to represent individual variables.

• This tutorial introduces how to declare array variables, create


arrays, and process arrays using indexed variables.

2
Java Arrays
• Normally, an array is a collection of similar type of elements which
has contiguous memory location.

• Java array is an object which contains elements of a similar data


type. Additionally, The elements of an array are stored in a
contiguous memory location. It is a data structure where we store
similar elements. We can store only a fixed set of elements in a
Java array.

• Array in Java is index-based, the first element of the array is stored


at the 0th index, 2nd element is stored on 1st index and so on.

3
Java Arrays

• Arrays are objects which store multiple variables of the same type.
It can hold primitive types as well as object references. In fact most
of the collection types in Java which are the part of java.util
package use arrays internally in their functioning. Since Arrays are
objects, they are created during runtime .The array length is fixed.

4
Types of Array in java
• There are two types of array.

– Single Dimensional Array


– Multidimensional Array

5
Single Dimensional Array in Java
• Syntax to Declare an Array in Java
• First let us get in to declaration of array which holds primitive types.
The declaration of array states the type of the element that the
array holds followed by the identifier and square braces which
indicates the identifier is array type.

• Example 1: Declaring an array which holds elements of integer


type.
int MyArray[];
• The above statement creates an array reference on the stack.

• Different way of declaring an array –


• Both the below statements are valid and same!!
– int []MyArray;
– int MyArray[]; 6
Creating Arrays
• You can create an array by using the new operator with the
following syntax:
arrayRef = new datatype[arraySize]

• The above statement does two things:


– It creates an array using new dataType[arraySize];
– It assigns the reference of the newly created array to the variable
arrayRefVar.

• Declaring an array variable, creating an array, and assigning the


reference of the array to the variable can be combined in one
statement, as shown below:
datatype[] arrayRef = new datatype[arraySize]

7
Creating Arrays
• Example:
• Following statement declares an array variable, myList, creates an array of
10 elements of double type and assigns its reference to myList:

double[] myList = new double[10];

• Following picture represents array myList. Here, myList holds ten double
values and the indices are from 0 to 9.

8
Declaration, Instantiation and
Initialization of Java Array
• We can declare, instantiate and initialize the java array together by:

• int a[]={33,3,4,5}; //declaration, instantiation and initialization


• Let's see the simple example to print this array.

//Java Program to illustrate the use of declaration, instantiation


//and initialization of Java array in a single line
• Output:
class Testarray1{
public static void main(String args[]){ 33
int a[]={33,3,4,5};//declaration, instantiation and initialization
3
//printing array 4
for(int i=0;i<a.length;i++)//length is the property of array 5
System.out.println(a[i]);
}
} 9
How to know size of an array
• There is no size() method available with the array.
• But there is a length field available in the array that can be used to find the
length or size of the array.

public class Test {


public static void main(String[] args)
{
// Here array is the array name of int type
int[] array = new int[4];

System.out.println("The size of the array is " + array.length);

}
}

• Output:
The size of the array is 4

10
Example of Java Array
public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}

// Summing all elements


double total = 0; • Output:
for (int i = 0; i < myList.length; i++) {
total += myList[i];
} 1.9
System.out.println("Total is " + total); 2.9
// Finding the largest element
3.4
double max = myList[0]; 3.5
for (int i = 1; i < myList.length; i++) { Total is 11.7
if (myList[i] > max) max = myList[i];
} Max is 3.5
System.out.println("Max is " + max);
} 11
}
Assigning and Displaying an array
• The below example initializes the array elements to 1,2,3,4,5,6 and prints
them

class ArrayInitializing{
public static void main(String args[]){
int FirstArray[] = new int[6];
for(int i=0;i<FirstArray.length;i++){
FirstArray[i]=i+1;
}
for(int i=0;i<FirstArray.length;i++){
System.out.println(FirstArray[i]);
}
}
}

• The array elements can be accessed with the help of the index.
FirstArray[0] refers to 1 ,FirstArray[1] refers to 2 etc.

12
Java Program to Accept Array
Elements and Calculate Sum
import java.util.Scanner;
Output:
public class Array_Sum
{
public static void main(String[] args)
Enter no. of elements you want in
{
array:5
int n, sum = 0;
Scanner s = new Scanner(System.in);
Enter all the elements:
System.out.print("Enter no. of elements you want in array:");
1
n = s.nextInt();
2
int a[] = new int[n];
3
System.out.println("Enter all the elements:");
4
for(int i = 0; i < n; i++)
5
{
a[i] = s.nextInt();
sum = sum + a[i];
Sum:15
}
System.out.println("Sum:"+sum);
}
}

13
Multidimensional Array in Java
• In such case, data is stored in row and column based index (also
known as matrix form).

• Syntax to Declare Multidimensional Array in Java

– dataType[][] arrayRefVar; (or)


– dataType [][]arrayRefVar; (or)
– dataType arrayRefVar[][]; (or)
– dataType []arrayRefVar[];

• Example to instantiate Multidimensional Array in Java

– int[][] arr=new int[3][3];//3 row and 3 column

14
Multidimensional Array in Java
• Example to initialize Multidimensional Array in Java

– arr[0][0]=1;
– arr[0][1]=2;
– arr[0][2]=3;
– arr[1][0]=4;
– arr[1][1]=5;
– arr[1][2]=6;
– arr[2][0]=7;
– arr[2][1]=8;
– arr[2][2]=9;

15
Example of Multidimensional Java
Array
• Let's see the simple example to declare, instantiate, initialize and
print the 2Dimensional array.

//Java Program to illustrate the use of multidimensional array


class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; • Output:
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){ 123
System.out.print(arr[i][j]+" "); 245
}
445
System.out.println();
}
}
}
16
Example of Multidimensional Java
Array
• We can multiply two matrices in java using binary * operator and executing
another loop. A matrix is also known as array of arrays. We can add,
subtract and multiply matrices.

• In case of matrix multiplication, one row element of first matrix is multiplied


by all columns of second matrix.

17
Example of Multidimensional Java
Array
public class MatrixMultiplicationExample{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices


for(int i=0;i<3;i++){ Output:
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
666
{ 12 12 12
c[i][j]+=a[i][k]*b[k][j];
18 18 18
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
18
}}

You might also like