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

Arrays

The document discusses concepts of arrays in Java including how to declare, initialize, access, process and pass arrays. It also covers copying arrays, returning arrays from methods, and using the Arrays class to sort and search arrays.

Uploaded by

p.monk790
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Arrays

The document discusses concepts of arrays in Java including how to declare, initialize, access, process and pass arrays. It also covers copying arrays, returning arrays from methods, and using the Arrays class to sort and search arrays.

Uploaded by

p.monk790
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Concepts of Arrays in Java

Arrays
• A single array variable can reference a large
collection of data.
• Once an array is created, its size is fixed.
• An array reference variable is used to access the
elements in an array using an index.
Declaring an Array
• To use an array in a program, you must declare a variable
to reference the array and specify the array’s element
type. Here is the syntax for declaring an array variable:
elementType[] arrayRefVar;
• The elementType can be any data type, and all elements
in the array will have the same data type. For example,
the following code declares a variable myList that
references an array of double elements.
double[] myList;
• You can also use elementType arrayRefVar[] to declare
an array variable. The style elementType[] arrayRefVar is
preferred.
Creating Arrays
• Syntax: arrayRefVar = new datatype[arraySize];
• Example:
• myList = new double[10];
• myList[0] references the first element in the array.
• myList[9] references the last element in the array.
• We can combine into one statement:

elementType[] arrayRefVar = new elementType[arraySize];


example: double[] myList = new double[10];
• To assign values to the elements, use the syntax:
arrayRefVar[index] = value;
For example, the following code initializes the array.
myList[0] = 5.6;
myList[1] = 4.5;
myList[2] = 3.3;
myList[3] = 13.2;
myList[4] = 4.0;
myList[5] = 34.33;
myList[6] = 34.0;
myList[7] = 45.45;
myList[8] = 99.993;
myList[9] = 11123;
Array Size and Default Values
• When space for an array is allocated, the array size
must be given, specifying the number of elements
that can be stored in it.
• The size of an array cannot be changed after the
array is created.
• Size can be obtained using arrayRefVar.length. For
example, myList.length is 10.
• When an array is created, its elements are assigned
the default value of 0 for the numeric primitive data
types, \u0000 for char types, and false for boolean
types.
Accessing Array Elements
• The array elements are accessed through the index.
Array indices are 0 based; that is, they range from 0
to arrayRefVar.length-1.
• In the example, myList holds ten double values, and
the indices are from 0 to 9.
• Each element in the array is represented using the
following syntax, known as an indexed variable:
arrayRefVar[index];
• For example, myList[9] represents the last element
in the array myList.
Array Initializers
• Java has a shorthand notation, known as the array initializer,
which combines the declaration, creation, and initialization of
an array in one statement using the following syntax:
elementType[] arrayRefVar = {value0, value1, ..., valuek};
• For example,
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;
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};
Processing Arrays
• Initializing arrays with input values: The following loop
initializes the array myList with user input values.

java.util.Scanner input = new java.util.Scanner(System.in);


System.out.print("Enter " + myList.length + " values: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();
• Initializing arrays with random values: The following
loop initializes the array myList with random values
between 0.0 and 100.0, but less than 100.0.
for (int i = 0; i < myList.length; i++)
{
myList[i] = Math.random() * 100;
}
• Array with user defined size:
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the number of items: ");
int n = input.nextInt();
double [] numbers = new double[n];
double sum = 0;
Exercise on Arrays

Question: Read ten numbers, compute their


average, and find out how many numbers are
above the average.
Copying array
• To copy the contents of one array into another, you
have to copy the array’s individual elements into the
other array.
• For example, list2=list1 then it will
• There are three ways to copy arrays:
• Use a loop to copy individual elements one by
one.
• Use the static arraycopy method in the System
class.
• Use the clone method to copy arrays;
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];
• Use the arraycopy method in the java.lang.System class
to copy arrays instead of using a loop.
• The syntax for arraycopy is:
arraycopy(sourceArray, srcPos, targetArray, tarPos, length);
• The parameters srcPos and tarPos indicate the starting
positions in sourceArray and targetArray, respectively.
The number of elements copied from sourceArray to
targetArray is indicated by length. For instance,

System.arraycopy(sourceArray, 0, targetArray, 0,
sourceArray.length);
Passing Arrays to Methods
• When passing an array to a method, the reference of
the array is passed to the method.
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}}
• Invoke the method: int[] list = {3, 1, 2, 6, 4, 2};
printArray(list);
Or printArray(new int[]{3, 1, 2, 6, 4, 2});

Anonymous Array
Note
• Java uses pass-by-value to pass arguments to a method.
There are important differences between passing the values
of variables of primitive data types and passing arrays.
• For an argument of a primitive type, the argument’s value is
passed.
• For an argument of an array type, the value of the argument
is a reference to an array; this reference value is passed to the
method. Semantically, it can be best described as
pass-by-sharing, that is, the array in the method is the same
as the array being passed.
• Thus, if you change the array in the method, you will see the
change outside the method.
Foreach loop
• Java supports a convenient for loop, known as a foreach loop. It
Enables array traversal sequentially without using an index
variable
• Syntax:
for (elementType element: arrayRefVar) {
// Process the element
}
• “for each element e in myList, do the following.”
for (double e: myList) {
System.out.println(e);
}
– Variable, e, must be declared as the same type as the
elements in myList.
– 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.
Returning array from method
• When a method returns an array, the reference of the array is returned
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}

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


int[] list2 = reverse(list1);
Variable-Length Argument Lists
• A variable number of arguments of the same type can be passed
to a method and treated as an array.
• The parameter in the method is declared as follows:
typeName... parameterName

• In the method declaration, you specify the type followed by an


ellipsis (...).

• Only one variable-length parameter may be specified in a


method, and this parameter must be the last parameter.
• Any regular parameters must precede it.
public class VarArgsDemo {
public static void main(String[] args) {
printMax(34, 3, 3, 2, 56.5);
printMax(new double[]{1, 2, 3});
}
public static void printMax(double... numbers) {
if (numbers.length == 0) {
System.out.println("No argument passed");
return;
}
double result = numbers[0];
for (int i = 1; i < numbers.length; i++)
if (numbers[i] > result)
result = numbers[i];
System.out.println("The max value is " + result);
}
}
The Arrays Class
• The java.util.Arrays class contains useful methods for
common array operations such as sorting and
searching.
• The java.util.Arrays class contains various static
methods for sorting and searching arrays, comparing
arrays, filling array elements, and returning a string
representation of the array.
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.
double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5};
java.util.Arrays.sort(numbers);
java.util.Arrays.parallelSort(numbers);

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


java.util.Arrays.sort(chars);
Command-Line Arguments
• The main method can receive string arguments from the
command line.
public class A { public class TestMain {
public static void main(String[] public static void main(String[]
args) { args) {
String[] strings = {"New York", for (int i = 0; i < args.length; i++)
"Boston", "Atlanta"}; System.out.println(args[i]);
TestMain.main(strings); }
} }
}
Cont’d
• We can pass strings to a main method from the command line
when run the program. The following command line, for example,
starts the program TestMain with three strings:
java TestMain arg0 arg1 arg2
• Where, arg0, arg1, and arg2 are strings.
• When the main method is invoked, the Java interpreter creates an
array to hold the command- line arguments and pass the array
reference to args. For example, if you invoke a program with n
arguments, the Java interpreter creates an array like this one:
args = new String[n];
• If you run the program with no strings passed, the array is created
with new String[0]. In this case, the array is empty with length 0.
args references to this empty array. Therefore, args is not null, but
args.length is 0.
Declaring /Creating Variables of 2d
Arrays
• Syntax is:
int[][] matrix = new int[10][10];
or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;

• Declaration is: double[][] x;


Two-dimensional Array Illustration

matrix.length? 5 array.length? 4
matrix[0].length? 5 array[0].length? 3
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 = {
{1, 2, 3}, int[][] array = new int[4][3];
{4, 5, 6}, array[0][0] = 1; array[0][1] = 2;
Same as array[0][2] = 3;
{7, 8, 9},
array[1][0] = 4; array[1][1] = 5;
{10, 11, 12}
array[1][2] = 6;
};
array[2][0] = 7; array[2][1] = 8;
array[2][2] = 9;
array[3][0] = 10;array[3][1] = 11;
array[3][2] = 12;
Lengths of Two-dimensional Arrays

int[][] x = new int[3][4];


Lengths of Two-dimensional Arrays,
cont.
int[][] array = { array.length
{1, 2, 3}, array[0].length
{4, 5, 6}, array[1].length
array[2].length
{7, 8, 9},
array[3].length
{10, 11, 12}
};

array[4].length ArrayIndexOutOfBoundsException
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},
matrix.length is 5
{2, 3, 4, 5},
{3, 4, 5}, matrix[0].length is 5
matrix[1].length is 4
{4, 5}, matrix[2].length is 3
{5} matrix[3].length is 2
}; matrix[4].length is 1
Ragged Arrays, cont.
• If we don’t know the values in a ragged array in
advance, but do know the sizes—we can create a
ragged array using the following syntax:
• int[][] triangleArray = new int[5][];
• triangleArray[0] = new int[5];
• triangleArray[1] = new int[4];
• triangleArray[2] = new int[3];
• triangleArray[3] = new int[2];
• triangleArray[4] = new int[1];
• we can now assign values to the array. For example,
• triangleArray[0][3] = 50;
• triangleArray[4][0] = 45;
The ArrayList Class
• we can create an array to store objects. But the array’s size is
fixed once the array is created. Java provides the ArrayList class
that can be used to store an unlimited number of objects.
• ArrayList is known as a generic class with a generic type E.
You can specify a concrete type to replace E when creating
an ArrayList. For example, the following statement
creates an ArrayList and assigns its reference to variable
cities. This ArrayList object can be used to store strings.
ArrayList<String> cities = new ArrayList<String>();
• The following statement creates an ArrayList and assigns
its reference to variable dates. This ArrayList object can
be used to store dates.
ArrayList<java.util.Date> dates = new ArrayList<java.util.Date> ();
ArrayList<AConcreteType> list = new ArrayList<AConcreteType>();
can be simplified by
ArrayList<AConcreteType> list = new ArrayList<>();
Important Fact
• A generic class is shared by all its instances regardless of its actual
concrete type.
• Suppose list1 and list2 are created as follows:
ArrayList<String> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
• Although ArrayList<String> and ArrayList<Integer> are two types at
compile time, only one ArrayList class is loaded into the JVM at
runtime.
• list1 and list2 are both instances of ArrayList, so the following
statements display true:
System.out.println(list1 instanceof ArrayList);
System.out.println(list2 instanceof ArrayList);
• However, list1 instanceof ArrayList<String> is wrong
• Since ArrayList<String> is not stored as a separate class in the JVM,
using it at runtime makes no sense.
Differences and Similarities between Arrays and
ArrayList
ArrayList …
• Suppose you want to create an ArrayList for storing
integers. Can you use the following code to create a list?
ArrayList<int> listOfIntegers = new ArrayList<>();
• No.
• This will not work because the elements stored in an
ArrayList must be of an object type.
• You cannot use a primitive data type such as int to
replace a generic type.
• However, you can create an ArrayList for storing
Integer objects as follows:

ArrayList<Integer> listOfIntegers = new


ArrayList<>();
Prompt user to enter a sequence of numbers & display distinct
numbers in sequence
import java.util.ArrayList;
import java.util.Scanner;
public class DistinctNumbers {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
Scanner input = new Scanner(System.in);
System.out.println("Enter integers (input ends with 0): ");
int value;
do { value = input.nextInt(); // Read a value
if (!list.contains(value) && value != 0)
list.add(value); // Add the value if it not in list
Enter
} numbers (input ends with 0): 1 2 3 2 1 6 3 4 5 4 5 1 2 3
0
while (value != 0);
The distinct numbers are:
System.out.print("The 1 2 3 6 integers
distinct 45 are: ");
for (int i = 0; i < list.size(); i++)
System.out.print(list.get(i) + " "); }}

You might also like