Arrays of Data 18.0
At present, many automobile manufacturers now employ freight (or cargo) trains to facilitate the transportation of motor vehicles from manufacturing plants to dealership outlets and/or vice versa. This mode of transporting motor vehicles tends to be relatively cheaper, and effective, for automobile manufacturers as many motor vehicles can be loaded into one (1) freight train, and transported in a single railway journey.

Also, considering a course instructor in a university, the instructor prepares a comprehensive list of students in the classroom in a bid to facilitate computation of scores, record keeping of class attendance, performance management, etc.

To this end, in programming, there exist an (abstract) data structure which is known as: array. Thus, arrays may be employed toward aggregating values of a specific data type, so as to facilitate effective and efficient data management with respect to these aggregated values. In other words, an array is simply a collection of several (variable) values possessing the same data type. Therefore, employing arrays in programming usually require the actualization of the following steps, viz:
  1. Declaration of a valid identifier for the array's data structure: <dataType>[] <identifier>; or <dataType> <identifier>[];
  2. Instantiation of the array with respect to a specific data type and content size/length: <identifier> = new <dataType>[length];

With regard to Java programming, after the declaration and the instantiation of an array data structure, each cell/unit within the entire length of the array structure is initialized to a value with respect to the following existent Primitive and Non-Primitive (data) types, namely:
Data Type of Array Structure Initialization Value
byte 0
short
int
long
float 0.0
double
char ' '
boolean false
String null
Object

/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		//Declaration and Instantiation of one-dimensional (1D) arrays - Approach 1
		float[] newFloatArr1;
		newFloatArr1 = new float[10];
		float newFloatArr2[];
		newFloatArr2 = new float[10];
		
		//Declaration and Instantiation of one-dimensional (1D) arrays - Approach 2
		double[] newDoubleArr1 = new double[10];
		double newDoubleArr2[] = new double[10];
		
		//Declaration and Instantiation of one-dimensional (1D) arrays - Approach 3
		int[] newIntArr1 = {1, 2, 3, 4, 5}; //Initialization values for 'newIntArr1[]' array
		int newIntArr2[] = {1, 2, 3, 4, 5}; //Initialization values for 'newIntArr2[]' array
	}
	
}
Code Snippet: Declaration and instantiation of one-dimensional (1D) array data structures

Additionally, some vital points worthy of note with regard to arrays in Java include the following:
  1. An array is a mutable collection of data values.
  2. Each data value occupies a cell/unit position with respect to the array's length/size.
  3. The length/size of an array, after its declaration and instantiation, is final; and it does not dynamically re-adjust itself without a re-declaration and/or re-initialization of the same array.
  4. With respect to an array's data structure, each cell/unit possesses an integer-based index which begins from zero (0) at the top/head of the array structure.
  5. In other words, array indexing begins at zero (0) with reference to the length/size of the array.
  6. With regard to an array's length, valid indexes of an array must lie within the boundaries of 0 ≤ x < length or 0 ≤ x ≤ length-1; such that x is a valid index.
  7. Any element contained within an array structure can be accessed via the following syntax: <identifier>[x]; such that x is a valid index-number of the array.
  8. In Java programming, the array (abstract) data type exposes a public property, length, which returns the length/size of a referenced array.
array structure with its content(s) and index(es)
Caption: Simplified array (data) structure comprising several cells/units labelled with respective indexes

/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		//Declaration and Instantiation of a one-dimensional (1D) array - Approach 1
		float[] newFloatArr;
		newFloatArr = new float[10];
		//Accessing elements of an array via its index-number
		System.out.println("Element at index 0 in 'newFloatArr[]' is " + newFloatArr[0]);	
		System.out.println("Element at index 5 in 'newFloatArr[]' is " + newFloatArr[5]);
		
		
		//Declaration and Instantiation of a one-dimensional (1D) array - Approach 2
		double[] newDoubleArr = new double[10];
		for (int i = 0; i < newDoubleArr.length; i++) {
			newDoubleArr[i] = i * i;
		}
		//Accessing elements of an array via its index-number
		System.out.println("Element at index 0 in 'newDoubleArr[]' is " + newDoubleArr[0]);
		System.out.println("Element at index 9 in 'newDoubleArr[]' is " + newDoubleArr[9]);
		
		
		//Declaration and Instantiation of a one-dimensional (1D) array - Approach 3
		int[] newIntArr = {1, 2, 3, 4, 5}; //Initialization values for 'newIntArr[]' array
		//Accessing elements of an array via its index-number	
		System.out.println("Element at index 0 in 'newIntArr[]' is " + newIntArr[0]);
		System.out.println("Element at index 3 in 'newIntArr[]' is " + newIntArr[3]);
	}
	
}
Code Snippet: Accessing the elements resident in 1D arrays via its respective index(es)



8.1Structure of an Array
An array is an abstract data structure; and as such, it is considered a Non-Primitive (or Derived) data type which can be used to define a mutable collection of elements (of Primitive or Non-Primitive type e.g. byte, char, String, etc.). Therefore, during the declaration and instantiation of an array, as a Non-Primitive data type, its variable-identifier holds an object-reference; and in turn, this object-reference points/links to the data elements or contents stored in the array structure (resident in primary memory).

In other words, Array Identifier —→ Array (Object) Reference —→ Array Elements/Contents.
array as an abstract data structure in memory
Caption: Array as an abstract data structure in memory


Shallow Copy: Since an array's variable-identifier simply holds an object-reference; if we assign the variable-identifier of one array to another array's variable-identifier, then we have only succeeded in copying the same object-reference into both arrays with respect to their variable-identifiers. Thus, this concept is known as Shallow Copy with regard to copying the contents of one array into another array.
Shallow Copy (Step 1): Declaration and instantiation of arrays - newFloatArr1[] and newFloatArr2[].


Shallow Copy (Step 2): Concept of Shallow Copy with regard to arrays. Thus, newFloatArr1[] is a "Shallow Copy" of newFloatArr2[].


/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		float[] newFloatArr1;
		newFloatArr1 = new float[10];
		
		float[] newFloatArr2;
		newFloatArr2 = new float[10];
		for (int i=0; i<10; i++) {
			newFloatArr2[i] = i * i;
		}

		/*
		 * The object-reference of 'newFloatArr2' is now assigned to 'newFloatArr1' variable-identifier.
		 * Thus, 'newFloatArr1' now holds the object-reference of 'newFloatArr2'.
		 * In other words, 'newFloatArr1' and 'newFloatArr2' now contain exactly the same object-reference.
		 * The original object-reference of 'newFloatArr1', which is still linked to its array (data) elements/contents,
		 * will be wiped off by Java's Garbage Collector mechanism.
		 */
		newFloatArr1 = newFloatArr2; //Shallow Copy

		for (int i = 0; i < 10; i++) {
			System.out.print("newFloatArr1["+i+"]=" + newFloatArr1[i]);
			System.out.println("; newFloatArr2["+i+"]=" + newFloatArr2[i]);
		}
	}
	
}
Code Snippet: The concept of Shallow Copy with regard to arrays. Thus, newFloatArr1[] is a "Shallow Copy" of newFloatArr2[].

Exercise 1: Consider the following Java program; "dry-run" this program, via hand tracing, and determine as well as specify the exact screen output(s).
/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		int[] studScores = {2, 4, 6, 8, 10};
		int[] myScores = studScores;
		
		studScores[0] = 100;
		
		for (int i = 0; i < studScores.length; ++i) {
			System.out.println(studScores[i] + " " + myScores[i]);
		}
	}
	
} 


//Dry-run: Hand tracing output (start)
/*
 myScores[] = studScores[] = {2, 4, 6, 8, 10}
 studScores[0] = 100
 myScores[] = studScores[] = {100, 4, 6, 8, 10}
 ---------------------------------------
 |          condition: i < 5
 ---------------------------------------
 | Iteration |  OUTPUT | i
 ---------------------------------------
 | 0 (init.) |         | 0
 | 1         | 100 100 | 1 
 | 2         |   4   4 | 2
 | 3         |   6   6 | 3 
 | 4         |   8   8 | 4 
 | 5         |  10  10 | 5 
 ---------------------------------------
*/		
//Dry-run: Hand tracing output (stop)
Code Snippet: Dry-run task with reference to Exercise 1

Exercise 2: Given the following Java program; "dry-run" this program, via hand tracing, and determine as well as specify the exact screen output(s).
/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		int[] primes = {2, 3, 5, 7, 11};
		
		for (int i = 0; i < 2; i++) {
			primes[4-i] = primes[i];
		}
		
		for (int i = 0; i < primes.length; i++) {
			System.out.println(primes[i]);
		}
	}
	
} 


//Dry-run: Hand tracing output (start)
/*
 primes[] = {2, 3, 5, 7, 11}
 -----------------------------------------------
 |          condition: i < 2
 -----------------------------------------------
 | Iteration |           OUTPUT          | i 
 -----------------------------------------------
 | 0 (init.) |                           | 0
 | 1         | primes[4] = primes[0] = 2 | 1
 | 2         | primes[3] = primes[1] = 3 | 2
 -----------------------------------------------
 
 primes[] = {2, 3, 5, 3, 2}
 -----------------------------------------------
 |          condition: i < 5
 -----------------------------------------------
 | Iteration | OUTPUT | i
 -----------------------------------------------
 | 0 (init.) |        | 0
 | 1         |    2   | 1
 | 2         |    3   | 2
 | 3         |    5   | 3
 | 4         |    3   | 4
 | 5         |    2   | 5
 -----------------------------------------------
*/		
//Dry-run: Hand tracing output (stop)
Code Snippet: Dry-run task with reference to Exercise 2

Exercise 3: With reference to the following Java program; "dry-run" this program, via hand tracing, and determine as well as specify the exact screen output(s).
/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		int[] primes = {2, 3, 5, 7, 11};
		
		for (int i = 0; i < 5; ++i) {
			primes[i]++;
		}
		
		for (int i = 0; i < primes.length; ++i) {
			System.out.println(primes[i]);
		}
	}
	
} 


//Dry-run: Hand tracing output (start)
/*
 primes[] = {2, 3, 5, 7, 11}
 -----------------------------------------------
 |          condition: i < 5
 -----------------------------------------------
 | Iteration |           OUTPUT        | i 
 -----------------------------------------------
 | 0 (init.) |                         | 0
 | 1         | primes[0] = 2 + 1 = 3   | 1
 | 2         | primes[1] = 3 + 1 = 4   | 2
 | 3         | primes[2] = 5 + 1 = 6   | 3
 | 4         | primes[3] = 7 + 1 = 8   | 4
 | 5         | primes[4] = 11 + 1 = 12 | 5
 -----------------------------------------------
 
 primes[] = {3, 4, 6, 8, 12}
 -----------------------------------------------
 |          condition: i < 5
 -----------------------------------------------
 | Iteration | OUTPUT | i
 -----------------------------------------------
 | 0 (init.) |        | 0
 | 1         |    3   | 1
 | 2         |    4   | 2
 | 3         |    6   | 3
 | 4         |    8   | 4
 | 5         |   12   | 5
 -----------------------------------------------
*/		
//Dry-run: Hand tracing output (stop)
Code Snippet: Dry-run task with reference to Exercise 3

Class Work: Now, consider the following Java program and "dry-run", via hand tracing, in a bid to determine the exact screen output(s).
/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		int[] evens = {2, 4, 6, 8, 10};
		int[] odds = {1, 3, 5, 7, 9};
		
		for (int i = 0; i < odds.length; ++i) {
			evens[i] = odds[i]++ + ++odds[i];
		}
		
		for (int i = 0; i < evens.length; ++i) {
			System.out.println(evens[i]);
		}
	}
	
} 
Code Snippet: Class work task



8.2Enhanced for {} loop construct
With regard to Java programming, the enhanced for {} loop construct is also known as the for-each {} loop construct. The for-each {} loop construct is quite similar to the conventional for {} loop construct; although, this enhanced for-each {} loop construct is best suited for traversing an array as it does not result in "out-of-bound error" during execution/run time.

Hence, the implementation syntax of a for-each {} loop construct is as follows:
for (variable declaration : array identifier) {
	//action: lines of code
}
Pseudocode: for-each {} loop construct

Additionally, it is important to mention that if a semicolon (;) is appended after the "variable declaration : array identifier" segment of a for-each {} loop construct; then this abruptly truncates the entire logic of the for-each {} loop construct. Hence, the lines of code within the curly parantheses, {...}, of the for-each {} loop construct get executed independent of the "variable declaration : array identifier" segment.
for (variable declaration : array identifier); //<-- Semicolon here truncates a "for-each {}" loop construct
{
	//action: This gets executed irrespective of the above "variable declaration : array identifier" segment 
}
Pseudocode: for-each {} loop construct with truncated "variable declaration : array identifier" segment

Exercise 1: Consider the following Java program with respect to the for-each {} loop construct; "dry-run" this program, via hand tracing, and determine as well as specify the exact screen output(s).
/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		int studScores[] = {2, 4, 6, 8, 10};
		
		for (int element : studScores) {
			//'element' is a locally declared variable with regard to this "for-each" loop
			//'element' represents a value at each index of the array
			//'studScores[]' denotes the array to be traversed
		
			System.out.println(element + " " + studScores);
		}
	}
	
}


//Dry-run: Hand tracing output (start)
/*
 studScores[] = {2, 4, 6, 8, 10}
 ---------------------------------------------------
 | Iteration |           OUTPUT        
 ---------------------------------------------------
 | 1         | 2 <object-reference of 'studScores'>
 | 2         | 4 <object-reference of 'studScores'>
 | 3         | 6 <object-reference of 'studScores'>
 | 4         | 8 <object-reference of 'studScores'>
 | 5         | 10 <object-reference of 'studScores'>
 ---------------------------------------------------
*/		
//Dry-run: Hand tracing output (stop)
Code Snippet: Dry-run task with reference to Exercise 1

Exercise 2: Given the following Java program with respect to the for-each {} loop construct; "dry-run" the program, via hand tracing, and determine as well as specify the exact screen output(s).
/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		int studScores[] = {2, 4, 6, 8, 10}, i = 0;
		
		for (int element : studScores) {
			//'element' is a locally declared variable with regard to this "for-each" loop
			//'element' represents a value at each index of the array
			//'studScores[]' denotes the array to be traversed
		
			System.out.println(element + " " + studScores[i++]);
		}
	}
	
}


//Dry-run: Hand tracing output (start)
/*
 studScores[] = {2, 4, 6, 8, 10}
 i = 0
 --------------------------
 | Iteration | OUTPUT | i       
 --------------------------
 | 0 (init.) |        | 0
 | 1         | 2 2    | 1
 | 2         | 4 4    | 2
 | 3         | 6 6    | 3
 | 4         | 8 8    | 4
 | 5         | 10 10  | 5
 --------------------------
*/		
//Dry-run: Hand tracing output (stop)
Code Snippet: Dry-run task with reference to Exercise 2

Exercise 3: Consider the following Java program with regard to the for-each {} loop construct. Thus, "dry-run" the program, via hand tracing, in a bid to determine as well as specify the exact screen output(s).
/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		int[] studScores = {2, 4, 6, 8, 10};
		
		for (int element : studScores) {
			element = 10; //This is only a localized assignment to 'element'
			System.out.println(element + " " + studScores);
		}
		
		for (int element : studScores) {
			//'studScores[]' was never updated by the above localized assignment to 'element'
			System.out.println(element + " " + studScores);
		}
	}
	
}


//Dry-run: Hand tracing output (start)
/*
 studScores[] = {2, 4, 6, 8, 10}
 ---------------------------------------------------------------
 | Iteration | element | OUTPUT      
 ---------------------------------------------------------------
 | 1         |    10   | 10 <object-reference of 'studScores'>    
 | 2         |    10   | 10 <object-reference of 'studScores'> 
 | 3         |    10   | 10 <object-reference of 'studScores'> 
 | 4         |    10   | 10 <object-reference of 'studScores'> 
 | 5         |    10   | 10 <object-reference of 'studScores'>
 ---------------------------------------------------------------
 
 studScores[] = {2, 4, 6, 8, 10}
 ---------------------------------------------------
 | Iteration | OUTPUT      
 ---------------------------------------------------
 | 1         | 2 <object-reference of 'studScores'>    
 | 2         | 4 <object-reference of 'studScores'> 
 | 3         | 6 <object-reference of 'studScores'> 
 | 4         | 8 <object-reference of 'studScores'> 
 | 5         | 10 <object-reference of 'studScores'>
 ---------------------------------------------------
*/		
//Dry-run: Hand tracing output (stop)
Code Snippet: Dry-run task with reference to Exercise 3

Differences between the for {} and the for-each {} loop constructs:
for {} loop for-each {} loop
Best suited for an explicitly stated and finite number of repetitions. Best suited for traversing arrays, ArrayLists, etc.
Can result to "out-of-bound" runtime error when used for traversing arrays, ArrayLists, etc. Never results to "out-of-bound" runtime error when used for traversing arrays, ArrayLists, etc.
Can access, modify, update, etc., elements of an array, ArrayList, etc. Traditionally designed only for accessing elements of an array, ArrayList, etc. However, using an iterator, modifications and updates can be applied to elements of the array, ArrayList, etc.

Similarities between the for {} and the for-each {} loop constructs:
  1. The for {} and the for-each {} loop constructs can almost be used interchangeably with respect to a repetition task and/or traversal task. In other words, every for-each {} loop construct can equally be implemented using a for {} loop construct, and vice versa.

Class Work 1: With regard to the concept of for-each {} loop, consider the following Java program and "dry-run" via hand tracing. Also, specify the exact screen output(s).
/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		String trackerVar = "";
		String[] arr = new String[5];
		for (String element : arr) {
			if (!trackerVar.equals("bbbbb")) {
				System.out.println("trackerVar = " + trackerVar);
				trackerVar = trackerVar + "b";
			}
		}
	}
	
}
Code Snippet: Class Work 1

Class Work 2: With reference to the for {} loop construct within the Java program below; generate the for-each {} loop equivalent for this block of code.
/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		for (int i = 0; i > 0; i = i+1) {
			System.out.println("i = " + i);
		}
	}
	
}
Code Snippet: Class Work 2



8.3Common Array-based Algorithms
/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		int[] dataArr = new int[11];
		for (int i = 0; i < dataArr.length; i++) {
			dataArr[i] = (i * i) + i; //Array's cell/unit update value
			System.out.println("Element at dataArr[" + i + "] is " + dataArr[i]);
		}
	}
	
}
Algorithm 1: Initialization of each cell/unit in an array to some value

/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		int dataArr[] = {52, 0, 100, 5, 1, 4, 10},  index = 0, largest = dataArr[index];
		for (int i = 1; i < dataArr.length; i++) {
			if (dataArr[i] > largest) { //Comparison to check for largest value
				index = i;
				largest = dataArr[index];
			}
		}
		System.out.println("Largest value in dataArr[] is " + largest + " existing at index " + index);
	}
	
}


public class ArraysofData1 {
	
	public static void main(String[] args) {
		int dataArr[] = {52, 0, 100, 5, 1, 4, 10},  i = 0, largest = dataArr[i], index = i;
		for (int element : dataArr) {
			if (element > largest) { //Comparison to check for largest value
				index = i;
				largest = element;
			}
			++i;
		}
		System.out.println("Largest value in dataArr[] is " + largest + " existing at index " + index);
	}
	
}
Algorithm 2: Finding the maximum (numeric) value existing within an array

/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		int dataArr[] = {52, 0, 100, 5, 1, 4, 10},  index = 0, smallest = dataArr[index];
		for (int i = 1; i < dataArr.length; i++) {
			if (dataArr[i] < smallest) { //Comparison to check for smallest value
				index = i;
				smallest = dataArr[index];
			}
		}
		System.out.println("Smallest value in dataArr[] is " + smallest + " existing at index " + index);
	}
	
}


public class ArraysofData1 {
	
	public static void main(String[] args) {
		int dataArr[] = {52, 0, 100, 5, 1, 4, 10},  i = 0, smallest = dataArr[i], index = i;
		for (int element : dataArr) {
			if (element < smallest) { //Comparison to check for smallest value
				index = i;
				smallest = element;
			}
			++i;
		}
		System.out.println("Smallest value in dataArr[] is " + smallest + " existing at index " + index);
	}
	
}
Algorithm 3: Finding the minimum (numeric) value existing within an array

/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		int dataArr[] = {52, 0, 100, -5, 1, 4, 10};
		double total = 0, average = 0;
		
		for (double item : dataArr) {
			total = total + item; //Computing sum of all (numeric) values in the array
		}
		System.out.println("Total of all values in dataArr[] is " + total);
		
		if (dataArr.length > 0) {
			average = total / dataArr.length;
		}
		System.out.println("Average with respect to all values in dataArr[] is " + average);
	}
	
}
Algorithm 4: Computing the sum, average, etc., of numeric values within an array

/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		int dataArr[] = {52, 0, 100, -5, 1, 4, 10, 8, 9, 5, 41};
		boolean found = false;
		int searchVal = 100, pos = 0;
		
		while ((pos < dataArr.length) && !found) {
			if (dataArr[pos] == searchVal) {
				found = true;
			}
			else {
				pos++;
			}			
		}
		
		if (found) {
			System.out.println(searchVal + " has been found at index " + pos);
		}
		else {
			System.out.println(searchVal + " was not found");
		}
	}
	
}
Algorithm 5: Linear search algorithm


Herein, earlier on at the beginning of this lesson or chapter, we introduced the concept of Shallow Copy.
Shallow Copy: This technique copies the object-reference of one array into another array.
Deep Copy: Alternatively, this technique copies the actual data content of one array into another array. There exist several approaches in Java programming for implementing the concept of Deep Copy with regard to arrays; and these are showcased in the following algorithms 6, 7, and 8.
Deep Copy (Step 1): Declaration and instantiation of arrays - dataArr[] and studScores2[].


Deep Copy (Step 2): Concept of Deep Copy with regard to arrays. Thus, studScores2[] is an actual (data) copy or "Deep Copy" of dataArr[].


/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		int dataArr[] = {0, 100, -5, 1, 4, 10, 8, 9, 5, 41};
		
		//Shallow Copy (object-reference copied)
		int[] studScores1 = dataArr;
		
		//Deep Copy (actual data-content copied)
		int[] studScores2 = new int[dataArr.length];
		for (int i = 0; i < dataArr.length; i++) {
			studScores2[i] = dataArr[i];
		}

		dataArr[3] = 678; //Update to only 'dataArr[3]'
		dataArr[9] = 8580; //Update to only 'dataArr[9]'

		for (int i = 0; i < dataArr.length; i++) {
			System.out.println(dataArr[i] + "  " + studScores1[i] + "  " + studScores2[i]);
		}
	}
	
}
Algorithm 6: Deep Copy (and Shallow Copy) with regard to one-dimensional arrays (Approach 1)

/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData1 {
	
	public static void main(String[] args) {
		int dataArr[] = {0, 100, -5, 1, 4, 10, 8, 9, 5, 41};
		
		//Shallow Copy (object-reference copied)
		int[] studScores1 = dataArr;
		
		//Deep Copy (actual data-content copied)
		int[] studScores2 = dataArr.clone();

		dataArr[3] = 678; //Update to only 'dataArr[3]'
		dataArr[9] = 8580; //Update to only 'dataArr[9]'

		for (int i = 0; i < dataArr.length; i++) {
			System.out.println(dataArr[i] + "  " + studScores1[i] + "  " + studScores2[i]);
		}
	}
	
}
Algorithm 7: Deep Copy (and Shallow Copy) with regard to one-dimensional arrays (Approach 2)

/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 1.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

import java.util.Arrays; //package required for the copyOf() method

public class ArraysofData1 {
	
	public static void main(String[] args) {
		int dataArr[] = {0, 100, -5, 1, 4, 10, 8, 9, 5, 41};
		
		//Shallow Copy (object-reference copied)
		int[] studScores1 = dataArr;
		
		//Deep Copy (actual data-content copied)
		int[] studScores2 = Arrays.copyOf(dataArr, dataArr.length);

		dataArr[3] = 678; //Update to only 'dataArr[3]'
		dataArr[9] = 8580; //Update to only 'dataArr[9]'

		for (int i = 0; i < dataArr.length; i++) {
			System.out.println(dataArr[i] + "  " + studScores1[i] + "  " + studScores2[i]);
		}
	}
	
}
Algorithm 8: Deep Copy (and Shallow Copy) with regard to one-dimensional arrays (Approach 3)



8.4Practice Exercise
  1. Given the program below, kindly explain what this program does as well as its expected output(s)?
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Arrays of Data 1.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
      
    public class ArraysofData1 {
    	
    	public static void main(String[] args) {
    		int counter = 0;
    		double cscScores[] = {20.0, 15.0, 0.0, 8, 0};
    		
    		for (double item : cscScores) {
    			if (item == 0.0) {
    				counter++;
    			}
    		}
    		
    		System.out.println("Value of 'counter' is = " + counter);
    	}
    	
    } 
    

  2. With reference to the for-each {} loop construct in the Java program below, generate the traditional for {} loop equivalent for this block of code.
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Arrays of Data 1.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
      
    public class ArraysofData1 {
    	
    	public static void main(String[] args) {
    		int counter = 0;
    		double[] studScores = {20.0, 15.0, 0.0, 8, 0};
    		
    		for (double element : studScores) {
    			if (element == 0.0) {
    				counter++;
    			}
    		}
    		
    		System.out.println("Value of 'counter' is = " + counter);
    	}
    	
    } 
    

  3. Dry-run the following block of code, via hand tracing, and determine as well as specify the exact screen output(s).
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Arrays of Data 1.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
      
    public class ArraysofData1 {
    	
    	public static void main(String[] args) {
    		int twoLetterWords = 0;
    		String myStr = "I do love programming in Java.";
    		myStr += " Someday, I hope to work in a top IT company.";
    		String[] myArr = myStr.split(" "); //Splits text on white-space
    
    		for (String word : myArr) {
    			if (word.length() == 2) {
    				++twoLetterWords;
    			}
    		}
    
    		System.out.print("There are exactly " + myArr.length + " words in the input text; ");
    		System.out.println("and exactly " + twoLetterWords + " of them are two-letter words.");
    	}
    	
    } 
    

  4. TRUE or FALSE: The for-each {} loop construct can never result to an "out-of-bound" runtime error when used for traversing a collection of items/elements?

  5. Dry-run the following Java program and explain what the program does as well as state its exact screen output(s).
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Arrays of Data 1.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
      
    public class ArraysofData1 {
    	
    	public static void main(String[] args) {
    		int counter = 0;
    		double cscScores[] = {17.5, 20.0, 15.0, 0.0, 8, 0, 19, 10.5, 13};
    		
    		for (double item : cscScores) {
    			if (!((item % 2.0) == 0.0)) {
    				counter += 1;
    			}
    		}
    		
    		System.out.println("Value of 'counter' is = " + counter);
    	}
    	
    } 
    

  6. Consider the Java program below, if the code compiles then what is the expected output; otherwise, state the expected error.
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Arrays of Data 1.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
    
    import java.util.Arrays;
      
    public class ArraysofData1 {
    	
    	public static void main(String[] args) {
    		int studScores1[] = {100, 82, 91, 45, 56, 78};
            
            int newLength = studScores1.length + 4;
            int[] studScores2 = new int[newLength];
            
            for (int i = 0; i < studScores1.length; i++) {
            	if (i % 2 == 0) {
            		studScores2[i] = studScores1[i];
            	}
            }
    
            studScores1 = studScores2;
    
            System.out.println(Arrays.toString(studScores1));
    	}
    	
    } 
    

  7. Consider the Java program below, dry-run via hand tracing and determine the expected output with respect to every line of code contained herein.
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Arrays of Data 1.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
    
    import java.util.Arrays;
    
    public class ArraysofData1 {
    	
    	public static void main(String[] args) {
    		int[] studScores = {1, 2, 3, 5, 7, 11, 13, 17};
    		
    		for (int item : studScores) {
    			item = 10;
    		}
    		
    		System.out.println(Arrays.toString(studScores));
    	}
    	
    }
    

  8. Dry-run the following Java program, via hand tracing, and determine the expected output with respect to every line of code contained herein.
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Arrays of Data 1.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
    
    import java.util.Arrays;
    
    public class ArraysofData1 {
    	
    	public static void main(String[] args) {
    		String[] studNames = {"John", "Jane", "Doe", "Alpha", "Bravo", "Charlie", "X-ray", "Yankee", "Zulu"};
    		
    		for (String item : studNames) {
    			item = "Delta";
    		}
    		
    		System.out.println(Arrays.toString(studNames));
    	}
    	
    }
    

Sponsored Ads