0% found this document useful (0 votes)
10 views8 pages

Week 2

This document outlines a laboratory session focused on arrays in Java, covering topics such as declaring, initializing, and manipulating one-dimensional and two-dimensional arrays. It includes examples of creating arrays, accessing elements, passing arrays to methods, and returning arrays from methods. Additionally, it provides lab activities for students to practice their understanding of arrays.

Uploaded by

ho3482529
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)
10 views8 pages

Week 2

This document outlines a laboratory session focused on arrays in Java, covering topics such as declaring, initializing, and manipulating one-dimensional and two-dimensional arrays. It includes examples of creating arrays, accessing elements, passing arrays to methods, and returning arrays from methods. Additionally, it provides lab activities for students to practice their understanding of arrays.

Uploaded by

ho3482529
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

Laboratory #2: Arrays

Lab Objectives:
After performing this lab, the students should be able to:
1. Learn how to use the array data structure to represent a set of related data items.

2. Learn how to declare arrays, initialize arrays and refer to the individual elements of arrays.

3. Learn how to pass arrays to functions.

N
4. Learn how to declare and manipulate Two-dimensional arrays.

LA
Definition:

AB
Array: A collection of individual values, all of the same data type.

Q
One Dimensional Array: An array with a single variable index. The first array element always has the
AL
subscript 0. The second array element has the subscript 1, etc.
Since arrays are objects in Java, we can find their length using member length.
A

Array can contain primitive data types as well as objects of a class depending on the definition of array.
AR
M
TA
r.
D

Creating, Initializing, and Accessing an Array


One-Dimensional Arrays :
The general form of a one-dimensional array declaration is

type var-name[];
OR
type[] var-name;
An array declaration has two components: the type and the name. type declares the element type of the array.
The element type determines the data type of each element that comprises the array. Like array of int type, we
can also create an array of other primitive data types like char, float, double..etc or user defined data
type(objects of a class).Thus, the element type for the array determines what type of data the array will hold.

Example:

// both are valid declarations


12
int intArray[];
or int[] intArray;

byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];

N
LA
// an array of references to objects of

AB
// the class MyClass (a class created by
// user)
MyClass myClassArray[]; Q
AL
Object[] ao, // array of Object
Collection[] ca; // array of Collection
A

// of unknown type
AR

Although the above first declaration establishes the fact that intArray is an array variable, no array actually
M

exists. It simply tells to the compiler that this(intArray) variable will hold an array of the integer type. To link
intArray with an actual, physical array of integers, you must allocate one using new and assign it to intArray.
TA

Instantiating an Array in Java


When an array is declared, only a reference of array is created. The general form of new as it applies to one-
r.

dimensional arrays appears as follows:


var-name = new type [size];
D

Here, type specifies the type of data being allocated, size specifies the number of elements in the array,
and var-name is the name of array variable that is linked to the array. That is, to use new to allocate an
array, you must specify the type and number of elements to allocate.

Example:

int intArray[]; //declaring array


intArray = new int[20]; // allocating memory to array
OR
int[] intArray = new int[20]; // combining both statements in one

Note :
1. The elements in the array allocated by new will automatically be initialized to zero (for numeric
types), false (for boolean), or null (for reference types).
2. 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. Thus, in Java all arrays are dynamically allocated.

13
Array Literal
In a situation, where the size of the array and variables of array are already known, array literals can be used.
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
// Declaring array literal
 The length of this array determines the length of the created array.
 There is no need to write the new int[] part in the latest versions of Java

Accessing Java Array Elements using for Loop


Each element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. All
the elements of array can be accessed using Java for Loop.

N
// accessing the elements of the specified array

LA
for (int i = 0; i < [Link]; i++)

AB
[Link]("Element at index " + i + " : "+ arr[i]);
Implementation:

// Java program to illustrate creating an array


Q
AL
// of integers, puts some values in the array,
// and prints each value to standard output.

class GFG
A

{
AR

public static void main (String[] args)


{
// declares an Array of integers.
M

int[] arr;
TA

// allocating memory for 5 integers.


arr = new int[5];
r.

// initialize the first elements of the array


D

arr[0] = 10;

// initialize the second elements of the array


arr[1] = 20;

//so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

// accessing the elements of the specified array


for (int i = 0; i < [Link]; i++) [Link]("Element at index " + i + " : "+
arr[i]);
}
}
Output:
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
14
Element at index 4 : 50

Note: You can also access java arrays using foreach loops

Arrays of Objects
An array of objects is created just like an array of primitive type data items in the following way.
Student[] arr = new Student[7]; //student is a user-defined class

The studentArray contains seven memory spaces each of size of student class in which the address of seven
Student objects can be stored. The Student objects have to be instantiated using the constructor of the Student

N
class and their references should be assigned to the array elements in the following way.

LA
Student[] arr = new Student[5];
// Java program to illustrate creating an array of

AB
// objects

class Student
{
Q
AL
public int roll_no;
public String name;
Student(int roll_no, String name)
{
A

this.roll_no = roll_no;
AR

[Link] = name;
}
}
M

// Elements of array are objects of a class Student.


TA

public class GFG


{
public static void main (String[] args)
r.

{
// declares an Array of integers.
D

Student[] arr;

// allocating memory for 5 objects of type Student.


arr = new Student[5];

// initialize the first elements of the array


arr[0] = new Student(1,"aman");

// initialize the second elements of the array


arr[1] = new Student(2,"reem");

// so on...
arr[2] = new Student(3,"shikar");
arr[3] = new Student(4,"rami");
arr[4] = new Student(5,"sara");

// accessing the elements of the specified array


for (int i = 0; i < [Link]; i++)
[Link]("Element at " + i + " : " +
arr[i].roll_no +" "+ arr[i].name);
}
15
}
Output:
Element at 0 : 1 aman
Element at 1 : 2 reem
Element at 2 : 3 shikar
Element at 3 : 4 rami
Element at 4 : 5 sara

What happens if we try to access element outside the array size?

N
LA
JVM throws ArrayIndexOutOfBoundsException to indicate that array has been accessed with an illegal index.
The index is either negative or greater than or equal to size of array.

AB
Example:
class GFG
{
public static void main (String[] args)
{
Q
AL
int[] arr = new int[2];
arr[0] = 10;
arr[1] = 20;
A
AR

for (int i = 0; i <= [Link]; i++)


[Link](arr[i]);
}
M

}
Runtime error
TA

Exception in thread "main" [Link]: 2


at [Link]([Link])
r.
D

Output:
10
20

Multidimensional Arrays
Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other array.
These are also known as Jagged Arrays. A multidimensional array is created by appending
one set of square brackets ([]) per dimension.
Examples:
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
class multiDimensional
{
public static void main(String args[])
{
16
// declaring and initializing 2D array
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };

// printing 2D array
for (int i=0; i< 3 ; i++)
{
for (int j=0; j < 3 ; j++)
[Link](arr[i][j] + " ");

[Link]();
}
}
}
Output:

N
LA
279
361

AB
742

Q
AL
Passing Arrays to Methods
Like variables, we can also pass arrays to methods. For example, below program pass array
to method sum for calculating sum of array’s values.
A

// Java program to demonstrate


// passing of array to method
AR

class Test
{
M

// Driver method
TA

public static void main(String args[])


{
int arr[] = {3, 1, 2, 5, 4};
r.

// passing array to method m1


D

sum(arr);

public static void sum(int[] arr)


{
// getting sum of array values
int sum = 0;

for (int i = 0; i < [Link]; i++)


sum+=arr[i];

[Link]("sum of array values : " + sum);


}
}
Output :
sum of array values : 15

17
Returning Arrays from Methods

As usual, a method can also return an array. For example, below program returns an array
from method m1.
// Java program to demonstrate
// return of array from method

class Test
{
// Driver method
public static void main(String args[])
{
int arr[] = m1();

N
LA
for (int i = 0; i < [Link]; i++)
[Link](arr[i]+" ");

AB
}

public static int[] m1() Q


{
AL
// returning array
return new int[]{1,2,3};
}
}
A

Output:
AR

123
M

Passing Arrays Size to Constructor


TA

class arr
{
r.

int size;
D

int[] b;
public arr(int s)
{
size = s;
b = new int[size];
}
public void input()
{ Scanner obj = new Scanner([Link]);
for (int i = 0; i < [Link]; i++)
b[i] = [Link]();
}
public double avg()
{
int sum = 0;
for (int i = 0; i < [Link]; i++)
sum=sum+b[i];
return sum/[Link]; } }

18
public class JavaApplication1 {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
arr class1 = new arr(3);
arr class2= new arr(4);
[Link]();
[Link]([Link]());
[Link]();

N
[Link]([Link]());
} }

LA
AB
Lab activities
Q
Lab assignment 1: Write a program that allows a user to enter 6 quiz scores to calculate and print the
average for these quizzes.
AL

Lab assignment 2: using array to CountDigit


A

Write a function CountDigit which receives two arguments: a char array and the size of the array (of type
AR

int). This function counts the number of digit letters in the char array, and returns the count (of type int)
M
TA
r.
D

19

You might also like