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

CSE211 Lecture 5

The document discusses arrays in Java, including how to declare, initialize, access elements, and perform common operations on arrays. Arrays allow storing multiple values of the same type and can be one-dimensional or multi-dimensional. Key array concepts covered are indexing, length property, for-each loops, sorting, and copying arrays.

Uploaded by

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

CSE211 Lecture 5

The document discusses arrays in Java, including how to declare, initialize, access elements, and perform common operations on arrays. Arrays allow storing multiple values of the same type and can be one-dimensional or multi-dimensional. Key array concepts covered are indexing, length property, for-each loops, sorting, and copying arrays.

Uploaded by

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

Arrays

Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
double[] myList = new double[10];

myList reference
myList[0] 5.6
myList[1] 4.5
Array reference myList[2] 3.3
variable
myList[3] 13.2

myList[4] 4
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34

myList[7] 45.45

myList[8] 99.993

myList[9] 11123

2
Arrays
 The general form of a one dimensional array declaration is:
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

Example: int month_days[];

 new is a special operator that allocates memory.


 The general form of new as it applies to one-dimensional arrays
appears as follows:
array-var = new type [size];
Example: month_days = new int[12]; 3
Declaring and Creating
in One Step
 It is possible to combine the declaration of the array
variable with the allocation of the array itself, as shown
here:
int month_days[] = new int[12];

 This is the way that you will normally see it done in


professionally written Java programs.
 Let’s review: Obtaining an array is a two-step process.
First, you must declare a variable of the desired array type.
Second, you must allocate the memory that will hold the
array, using new, and assign it to the array variable.
4
The Length of an Array
Once an array is created, its size is fixed. It cannot be
changed. You can find its size using

arrayRefVar.length

For example,

month_days.length returns 12

5
Indexed Variables
The array elements are accessed through the index. The
array indices are 0-based, i.e., it starts from 0 to
arrayRefVar.length-1. In the example month_days
holds twelve int values and the indices are from 0 to
11.

Each element in the array is represented using the


following syntax, known as an indexed variable:

arrayRefVar[index];

6
Using Indexed Variables
After an array is created, an indexed variable can
be used in the same way as a regular variable.
For example, the following code adds the value
in month_days[0] and month_days[1] to
month_days[2].

month_days[2] = month_days[0] + month_days[1];

7
Array Initializers
 Declaring, creating, initializing in one step:
double[] myList = {1.9, 2.9, 3.4, 3.5};

This shorthand syntax must be in one


statement.

8
Declaring, creating, initializing
Using the Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};

This shorthand notation is equivalent to the


following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

9
CAUTION
Using the shorthand notation, you
have to declare, create, and initialize
the array all in one statement.
Splitting it would cause a syntax
error. For example, the following is
wrong:
double[] myList;

myList = {1.9, 2.9, 3.4, 3.5};


10
Array Example
 class Testarray{
 public static void main(String args[]){

 int a[]=new int[5]; //declaration and instantiation
 a[0]=10; //initialization
 a[1]=20;
 a[2]=70;
 a[3]=40;
 a[4]=50;

 //printing array
 for(int i=0;i<a.length;i++){ //length is the property of array
 System.out.println(a[i]);
 }
 }
11
Summing all elements
double total = 0;
for (int i = 0; i < a.length; i++) {
total += a[i];
}

12
Finding the largest element
double max = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] > max) max = a[i];
}

13
Enhanced for Loop (for-each loop)
JDK 1.5 introduced a new for loop that enables you to traverse the complete array
sequentially without using an index variable. For example, the following code
displays all elements in the array myList:

for (double value: myList)


System.out.println(value);

In general, the syntax is

for (elementType value: arrayRefVar) {


// Process the value
}

You still have to use an index variable if you wish to traverse the array in a
different order or change the elements in the array.

14
Copying Arrays
Often, in a program, you need to duplicate an array or a part of an
array. In such cases you could attempt to use the assignment statement
(=), as follows:

list2 = list1;
Before the assignment After the assignment
list2 = list1; list2 = list1;

list1 list1
Contents Contents
of list1 of list1

list2 list2
Contents Contents
of list2 of list2
Garbage

15
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new
int[sourceArray.length];

for (int i = 0; i < sourceArray.length; i++)


targetArray[i] = sourceArray[i];

16
The arraycopy Utility
arraycopy(sourceArray, src_pos,
targetArray, tar_pos, length);

Example:
System.arraycopy(sourceArray, 0,
targetArray, 0, sourceArray.length);

17
public class Array {

public static void main(String[] args) {


int s[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int d[] = { 15, 25, 35, 45, 55, 65, 75, 85, 95, 105};

int source_arr[], sourcePos, dest_arr[], destPos, len;


source_arr = s;
sourcePos = 3;
dest_arr = d;
destPos = 5;
len = 5;

// Print elements of source


System.out.print("source_array : ");
for (int i = 0; i < s.length; i++)
System.out.print(s[i] + " ");
System.out.println("");

System.out.println("sourcePos : " + sourcePos);


18
// Print elements of source
System.out.print("dest_array : ");
for (int i = 0; i < d.length; i++)
System.out.print(d[i] + " ");
System.out.println("");

System.out.println("destPos : " + destPos);

System.out.println("len : " + len);

// Use of arraycopy() method


System.arraycopy(source_arr, sourcePos, dest_arr, destPos, len);

// Print elements of destination after


System.out.print("final dest_array : ");
for (int i = 0; i < d.length; i++)
System.out.print(d[i] + " ");
}
}
19
The Arrays.sort Method
Since sorting is frequently used in programming, Java provides several
overloaded sort methods for sorting an array of int, double, char, short,
long, and float in the java.util.Arrays class. For example, the following
code sorts an array of numbers and an array of characters.

import java.util.Arrays;

double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5};


Arrays.sort(numbers);

char[] chars = {'a', 'A', '4', 'F', 'D', 'P'};


Arrays.sort(chars);

20
Two dimensional Arrays
 Two dimensional Arrays:
 In Java, two dimensional arrays are actually arrays of
arrays.
 To declare a two dimensional array variable, specify each
additional index using another set of square brackets.

 For example, the following declares a two-dimensional


array variable called refVar :
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

21
Declare/Create Two-dimensional Arrays
// Declare array ref var
int[][] refVar;

// Create array and assign its reference to variable


refVar = new int[10][10];

// Combine declaration and creation in one statement


int[][] refVar = new int[10][10];

22
Multidimensional Arrays

23
Two-dimensional Array Illustration
0 1 2 3 4 0 1 2 3 4 0 1 2
0 0 0 1 2 3

1 1 1 4 5 6

2 2 7 2 7 8 9

3 3 3 10 11 12

4 4 int[][] array = {
{1, 2, 3},
matrix = new int[5][5]; matrix[2][1] = 7; {4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};

matrix.length? 5 array.length? 4
matrix[0].length? 5 array[0].length? 3

24
Declaring, Creating, and Initializing Using
Shorthand Notations
You can also use an array initializer to declare, create and
initialize a two-dimensional array. For example,

int[][] array = { int[][] array = new int[4][3];


{1, 2, 3}, array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
{4, 5, 6}, Same as
array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
{7, 8, 9}, array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
{10, 11, 12} array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
};

25
Lengths of Two-dimensional
Arrays
int[][] x = new int[3][4];
x
x[0][0] x[0][1] x[0][2] x[0][3] x[0].length is 4
x[0]
x[1] x[1][0] x[1][1] x[1][2] x[1][3] x[1].length is 4

x[2]
x[2][0] x[2][1] x[2][2] x[2][3] x[2].length is 4
x.length is 3

26
Alternative Array Declaration Syntax
 This alternative declaration form offers convenience when
declaring several arrays at the same time. For example,

int[] arr1, arr2, arr3; // create three arrays

 creates three array variables of type int. It is the same as writing


int arr1[], arr2[], arr3[]; // create three arrays

int[] arr1, arr2, arr3;


arr1 = new int[10];
arr2 = new int[20];
arr3 = new int[30];
27
Ragged Arrays
Each row in a two-dimensional array is itself an array. So,
the rows can have different lengths. Such an array is
known as a ragged array. For example,
int[][] matrix = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5}, matrix.length is 5
matrix[0].length is 5
{3, 4, 5}, matrix[1].length is 4
matrix[2].length is 3
{4, 5}, matrix[3].length is 2
matrix[4].length is 1
{5}
};
28
Ragged Arrays, cont.

int[][] triangleArray = { 1 2 3 4 5
{1, 2, 3, 4, 5},
{2, 3, 4, 5}, 1 2 3 4
{3, 4, 5},
{4, 5}, 1 2 3
{5}
}; 1 2

1 2

29
30
Processing Two-Dimensional Arrays
See the examples in the text.
1. (Initializing arrays with input values)
2. (Printing arrays)
3. (Summing all elements)
4. (Summing all elements by column)
5. (Which row has the largest sum)
6. (Finding the smallest index of the largest element)

31
Initializing arrays with input values
java.util.Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix.length + " rows and " +
matrix[0].length + " columns: ");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = input.nextInt();
}
}

32
Initializing arrays with random values

for (int row = 0; row < matrix.length; row++) {


for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = (int)(Math.random() * 100);
}
}

33
Printing arrays
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}

System.out.println();
}

34
Printing arrays using
Enhanced for loop
for (int row[] : matrix){
for (int column : row) {
System.out.print(column + " ");
}

System.out.println();
}

35
Summing all elements
int total = 0;
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
total += matrix[row][column];
}
}

36
Summing elements by column
for (int column = 0; column < matrix[0].length; column++) {
int total = 0;
for (int row = 0; row < matrix.length; row++)
total += matrix[row][column];
System.out.println("Sum for column " + column + " is "
+ total);
}

37
What is the class name of java array?
 In java, array is an object. In Java, arrays inherit the getClass and getName
methods from the java.lang.Object class, which is the root of the Java class
hierarchy.
 getClass().getName() method on the object.
class Testarray4{
public static void main(String args[]){
int arr[]={4,4,5};

Class c=arr.getClass();
String name=c.getName(); Output: [I
System.out.println(name);
}
}
The class name of arrays of primitive data types in Java uses a shorthand
notation, where each primitive type is represented by a single uppercase
letter. The letter corresponds to the type of the elements in the array.
38
Example 1: How to put a Scanner inpu
t into an array

39
Example 2: How to
put a Scanner inpu
t into an array

40

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy