Arrays of Data 29.0
9.1Common Array-based Algorithms

public class ArraysofData2 {
	
	public static void main(String[] args) {
		/* Rectangular Array: 2D-array with strictly consistent column sizes */
		int[][] myArr = { {1,2,3,4,5},
						  {6,7,8,9,10},
						  {11,12,13,14,15},
						  {16,17,18,19,20} };
		
		/* Ragged (or Jagged) Array: 2D-array with inconsistent column sizes */
		int[][] raggedArr = { {1,2,3},
							  {6},
							  {11,12,13,14},
							  {16,17},
							  {21,22,23,24,25,26,27},
							  {30,33} };
		
		//Traverse data rows (horizontally)
		for (int i = 0; i < raggedArr.length; i++) {
			//Traverse data columns (vertically)
			for (int j = 0; j < raggedArr[i].length; j++) {
				System.out.print(" | " + raggedArr[i][j]);
			}
			System.out.println(" |");
		}
	}
	
}
Algorithm 9: Ragged (or Jagged) arrays with respect to two-dimensional (2D) arrays

So far, from the previous lesson and/or chapter, we have examined the concepts of Shallow Copy and Deep Copy on one-dimensional (1D) arrays. Thus, let us examine both concepts with reference to two-dimensional (2D) arrays.
/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 2.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int[][] dataArr = { {1, 2, 3, 4, 5},
						    {6, 7, 8, 9, 10},
						    {11, 12, 13, 14, 15},
						    {16, 17, 18, 19, 20} };
		
		//Shallow Copy (object-reference copied)
		int[][] studScores1 = dataArr;
		
		dataArr[1][3] = 678; //Update to only 'dataArr[1][3]'
		dataArr[3][0] = 858; //Update to only 'dataArr[3][0]'

		//Traverse data-array rows (horizontally)
		for (int i = 0; i < dataArr.length; i++) {
			//Traverse data-array columns (vertically)
			for (int j = 0; j < dataArr[i].length; j++) {
				System.out.print(" | " + dataArr[i][j] + "  " + studScores1[i][j]);
			}
			System.out.println(" |");
		}
	}
	
}
Algorithm 10: Shallow Copy with regard to two-dimensional arrays (Approach 1)

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

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

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int[][] dataArr = { {1, 2, 3, 4, 5},
						    {6, 7, 8, 9, 10},
						    {11, 12, 13, 14, 15},
						    {16, 17, 18, 19, 20} };
		
		//Shallow Copy (object-reference copied)
		int[][] studScores1 = dataArr.clone(); //Approach 2
		int[][] studScores2 = Arrays.copyOf(dataArr, dataArr.length); //Approach 3
		
		dataArr[1][3] = 678; //Update to only 'dataArr[1][3]'
		dataArr[3][0] = 858; //Update to only 'dataArr[3][0]'

		//Traverse data-array rows (horizontally)
		for (int i = 0; i < dataArr.length; i++) {
			//Traverse data-array columns (vertically)
			for (int j = 0; j < dataArr[i].length; j++) {
				System.out.print(" | " + dataArr[i][j] + "  " + studScores1[i][j] + "  " + studScores2[i][j]);
			}
			System.out.println(" |");
		}
	}
	
}
Algorithm 11: Shallow Copy with regard to two-dimensional arrays (Approaches 2 and 3)

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

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int[][] dataArr = { {1, 3, 5},
						    {6, 7, 8, 9},
						    {13, 15},
						    {16, 17, 18, 19, 20} };
				
		//Deep Copy (actual data-content copied)
		int[][] studScores1 = new int[dataArr.length][]; //Instantiate rows of 'studScores1'
		int[][] studScores2 = new int[dataArr.length][]; //Instantiate rows of 'studScores2'
		//Traverse data-array rows (horizontally)
		for (int i = 0; i < dataArr.length; i++) {
			studScores1[i] = new int[dataArr[i].length]; //Instantiate columns of 'studScores1'
			studScores2[i] = new int[dataArr[i].length]; //Instantiate columns of 'studScores2'
			//Traverse data-array columns (vertically)
			for (int j = 0; j < dataArr[i].length; j++) {
				studScores1[i][j] = dataArr[i][j];
				studScores2[i][j] = dataArr[i][j];
			}
		}
		
		dataArr[1][3] = 678; //Update to only 'dataArr[1][3]'
		dataArr[3][0] = 858; //Update to only 'dataArr[3][0]'

		//Traverse data-array rows (horizontally)
		for (int i = 0; i < dataArr.length; i++) {
			//Traverse data-array columns (vertically)
			for (int j = 0; j < dataArr[i].length; j++) {
				System.out.print(" | " + dataArr[i][j] + "  " + studScores1[i][j] + "  " + studScores2[i][j]);
			}
			System.out.println(" |");
		}
	}
	
}
Algorithm 12: Deep Copy with regard to two-dimensional arrays (Approach 1)

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

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

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int[][] dataArr = { {1, 3, 5},
						    {6, 7, 8, 9},
						    {13, 15},
						    {16, 17, 18, 19, 20} };
				
		//Deep Copy (actual data-content copied)
		int[][] studScores1 = new int[dataArr.length][];
		int[][] studScores2 = new int[dataArr.length][];
		for (int i = 0; i < dataArr.length; i++) {
			studScores1[i] = dataArr[i].clone(); //Approach 2
			studScores2[i] = Arrays.copyOf(dataArr[i], dataArr[i].length); //Approach 3
		}
		
		dataArr[1][3] = 678; //Update to only 'dataArr[1][3]'
		dataArr[3][0] = 858; //Update to only 'dataArr[3][0]'

		//Traverse data-array rows (horizontally)
		for (int i = 0; i < dataArr.length; i++) {
			//Traverse data-array columns (vertically)
			for (int j = 0; j < dataArr[i].length; j++) {
				System.out.print(" | " + dataArr[i][j] + "  " + studScores1[i][j] + "  " + studScores2[i][j]);
			}
			System.out.println(" |");
		}
	}
	
}
Algorithm 13: Deep Copy with regard to two-dimensional arrays (Approaches 2 and 3)


Irrespective of the fact that the length/size of an array is final after its declaration and instantiation; we can smartly employ the joint techniques of Deep Copy and Shallow Copy, so as to dynamically adjust the length/size of an already declared and instantiated array. In this regard, we can either expand or compress the length/size of an array. The following figure, which is directly following by an algorithm, depicts the necessary steps taken toward adjusting (expansion) the size of studScores1[] array.
Dynamic Adjustment of Array (Step 1): Declaration and instantiation of arrays - studScores1[] and studScores2[].


Dynamic Adjustment of Array (Step 2): Making studScores2[] an actual (data) copy or "Deep Copy" of studScores1[].


Dynamic Adjustment of Array (Step 3): Pointing, via Shallow Copy, studScores1[] to the Deep Copy array (studScores2[]).


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

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

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int studScores1[] = {100, 82, 91, 45, 56, 78};
		
		//Array-Size Adjustment
		int newLength = studScores1.length + 4; //Expansion: by 4 cells/units
		//int newLength = studScores1.length - 4; //Compression: by -4 cells/units
		int[] studScores2 = new int[newLength];

		//Deep Copy (into Expanded Array): Approach 1
		for (int i = 0; i < studScores1.length; i++) {
		//Deep Copy (into Compressed Array): Approach 1
		//for (int i = 0; i < studScores2.length; i++) {
			studScores2[i] = studScores1[i];
		}
		//Deep Copy (into Expanded/Compressed Array): Approach 2
		//int[] studScores2 = Arrays.copyOf(studScores1, newLength);

		//Shallow Copy: Point onto Adjusted Array
		studScores1 = studScores2;

		//Display arrays
		for (int i = 0; i < studScores1.length; i++) {
			System.out.println(studScores1[i] + " | " + studScores2[i]);
        }
	}
	
}
Algorithm 14: Dynamically adjusting (expansion and/or compression) the length/size of an already declared and instantiated array

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

import java.util.Arrays; //package required for the toString() and deepToString() methods

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int dataArr1[] = {100, 82, 91, 45, 56, 78};
		
		int dataArr2[][] = { {1, 3, 5},
						    {6, 7, 8, 9},
						    {13, 15},
						    {16, 17, 18, 19, 20} };
							
		int[][] dataArr3 = { {1, 2, 3, 4, 5},
						    {6, 7, 8, 9, 10},
						    {11, 12, 13, 14, 15},
						    {16, 17, 18, 19, 20} };
				
		//toString(): Returns (data) contents of a 1D array in human-friendly format
		System.out.println(Arrays.toString(dataArr1));
		
		//deepToString(): Returns (data) contents of a multi-dimensional array in human-friendly format
		System.out.println(Arrays.deepToString(dataArr2));
		System.out.println(Arrays.deepToString(dataArr3));
	}
	
}
Algorithm 15: Displaying contents of an array in human-friendly format

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

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

public class ArraysofData2 {
	
	public static void main(String[] args) {
		final int NUMBER_OF_INPUTS = 3;
        double[] inVals = new double[NUMBER_OF_INPUTS];
        Scanner usrInput = new Scanner(System.in);
        
        for (int i = 0; i < NUMBER_OF_INPUTS; i++) {
        	System.out.print("Please enter a value for number " + (i + 1) + ": ");
        	inVals[i] = usrInput.nextDouble();
        	System.out.println();
        }

		//toString(): Returns (data) contents of a 1D array in human-friendly format
		System.out.println(Arrays.toString(inVals));
		
		//Flushes and closes the "Scanner" buffer so as to prevent resource leakage/wastage.
        usrInput.close();
	}
	
}
Algorithm 16: Prompting and storing user input(s) into an array

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

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

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int iterator = 0;
        final int NUMBER_OF_INPUTS = 3;
        double[] inVals = new double[NUMBER_OF_INPUTS];
        Scanner usrInput = new Scanner(System.in);
        
        while (iterator < NUMBER_OF_INPUTS) {
            System.out.print("Please enter a value for number " + ++iterator + ": ");
            inVals[iterator-1] = usrInput.nextDouble();
            System.out.println();
        }

        //toString(): Returns (data) contents of a 1D array in human-friendly format
        System.out.println(Arrays.toString(inVals));
        
        //Flushes and closes the "Scanner" buffer so as to prevent resource leakage/wastage.
        usrInput.close();
	}
	
}
Algorithm 17: Prompting and storing user input(s) into an array



9.2Sorting the (Data) Contents of Arrays
As humans, we usually employ sorting techniques in several real-world scenarios. For example, when preparing our bags for school, we usually sort (or arrange) our books according to their respective sizes in a bid to maximize storage space. Also, houses in residential areas are usually ordered (or arranged) numerically or alphanumerically, either in ascending on descending order, so as to improve the delivery of services such as mail dispatch, garbage collection, etc. Moreover, when we queue either in hospitals, restaurants, banks, etc.; we usually do so in an order that respects our individual time of arrival. In summary, sorting is an ordering technique that aims at improving effeciency and effectiveness.

In generic programming, there exist several categories of sorting algorithms such as linear (sorting) algorithms, divide-and-conquer (sorting) algorithms, etc. However, we shall quickly review the program implementations for a couple of these sorting algorithms with respect to Java programming.

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

import java.util.Arrays;

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int dataArr[] = {0, 100, -5, 1, 4, 10, 8, 9, 5, 41};
		
		for (int i = 1; i < dataArr.length; i++) {
			int searchVal = dataArr[i];
			int j = i - 1;

			//Compare the 'searchVal' with every element to its left-hand-side
			//until an element smaller than the 'searchVal' is found.
			while (j >= 0 && searchVal < dataArr[j]) { //Ascending-Order sorting
			//while (j >= 0 && searchVal > dataArr[j]) { //Descending-Order sorting
				dataArr[j + 1] = dataArr[j];
				--j;
			}

			// Place the 'searchVal' just before the element that is bigger than it.
			dataArr[j + 1] = searchVal;			
		}
		
		//Display array
		System.out.println(Arrays.toString(dataArr));
	}
	
}
Sorting Alogrithm: Insertion Sort

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

import java.util.Arrays;

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int dataArr[] = {0, 100, -5, 1, 4, 10, 8, 9, 5, 41};
		int arrLen = dataArr.length, temp = 0;
		
		for (int i = 0; i < arrLen; i++) {
			for (int j = 1; j < (arrLen - i); j++) {
				if (dataArr[j - 1] > dataArr[j]) { //Ascending-Order sorting
				//if (dataArr[j - 1] < dataArr[j]) { //Descending-Order sorting
					//Swap elements
					temp = dataArr[j - 1];
					dataArr[j - 1] = dataArr[j];
					dataArr[j] = temp;
				}
			}
		}
		
		//Display array
		System.out.println(Arrays.toString(dataArr));
	}
	
}
Sorting Alogrithm: Bubble Sort

Additionally, in Java programming, the Arrays class block implements a sort() method which can be used to sort the elements of an array. Technically, the Arrays.sort() method implicitly implements the Quick Sort algorithm which is essentially a divide-and-conquer algorithm.
/**
 * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
 * @course ProgrammingLessons (proglessons).
 * @title Arrays of Data 2.
 * @author Dr. Bonaventure Chidube Molokwu.
 */

import java.util.Arrays;

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int dataArr[] = {0, 100, -5, 1, 4, 10, 8, 9, 5, 41};
		
		//Quick Sort (Implementation Algorithm) 
		Arrays.sort(dataArr); //Ascending-Order sorting
		
		//Display array
		System.out.println(Arrays.toString(dataArr));
	}
	
}
Code Snippet: sort() method of the Arrays class block (Sorting an entire array)

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

import java.util.Arrays;

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int dataArr[] = {0, 100, -5, 1, 4, 10, 8, 9, 5, 41};
		
		//Quick Sort (Implementation Algorithm)
		//Partial contents beginning at index 0 and ending at index (5 - 1 = 4)
		Arrays.sort(dataArr, 0, 5); //Ascending-Order sorting (partial contents of the array)
		
		//Display array
		System.out.println(Arrays.toString(dataArr));
	}
	
}
Code Snippet: sort() method of the Arrays class block (Sorting partial contents of an array)



9.3Searching the (Data) Contents of Arrays
Similar to the sorting algorithms in generic programming; there also exist different categories of searching algorithms such as linear (searching) algorithms, divide-and-conquer (searching) algorithms, etc.

In addition, searching algorithms are quite popular in our day-to-day activities as humans. For example, searching for an item to purchase on AmazonTM, eBayTM, WalmartTM, etc. Also, when searching the World Wide Web (WWW) using engines like Google SearchTM, Yahoo! SearchTM, etc.; we are technically employing a searching algorithm.

To this end, we shall be examining quite a couple of these popular searching algorithms with respect to generic programming domain.

Linear Search Algorithm:
  1. Given a search value and a collection of items/elements in an array; thus, from the start index of the array, visit each element (at every index).
  2. At every index, compare its resident item/element with the given search value.
  3. Repeat step (2.) above until a match is found for the search value or the end index of the array is reached (not found).

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

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int dataArr[] = {0, 100, -5, 1, 4, 10, 8, 9, 5, 41};
		
		boolean found = false;
		int idx = 0, high = (dataArr.length -1), searchValue = 8;
		
		while ((idx <= high) && !found) {
			if (dataArr[idx++] == searchValue) {
				found = true; //Found a match
			}
		}
		
		if (found) {
			System.out.println(searchValue + " has been found at index " + (idx - 1) + " of the array.");
		}
		else {
			System.out.println(searchValue + " was not found in the entire array. ");
		}
	}
	
}
Searching Alogrithm: Linear Search

Binary Search Algorithm:
  1. Given a search value and a sorted collection of items/elements in an array; thus, compute the following parameters, viz:
    • low = Lowest index in the array of elements
    • high = Highest index in the array of elements
    • mid = floor((low + high)/2)
  2. At the mid index, compare its resident element with the given search value. If the element at the mid index is equal to the given search value; then return true. If the element at the mid index is lower than the given search value; then exclude the lower halve of the array. If the element at the mid index is higher than the given search value; then exclude the higher halve of the array.
  3. Repeat steps (1.) and (2.) above until a match is found for the search value; or when low = high = mid ≠ search value (not found).
  4. Note: Using an already sorted collection of elements is a prerequisite for employing the Binary Search algorithm.
Binary Search Algorithm
Binary Search: Search value = 8; and the algorithm returns true at index 5 during the 3rd iteration


Binary Search Algorithm
Binary Search: Search value = 2; and the algorithm returns false after the 4th iteration

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

import java.util.Arrays;

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int dataArr[] = {0, 100, -5, 1, 4, 10, 8, 9, 5, 41};		
		
		boolean found = false;
		int low = 0, high = (dataArr.length -1), mid = 0, searchValue = 8;
		
		Arrays.sort(dataArr); //Ascending-Order sorting
		
		while ((low <= high) && !found) {
			mid = (low + high) / 2; //Division of integers returns a truncated (or floored) result
			if (dataArr[mid] == searchValue) {
				found = true; //Found a match
			}
			else if (dataArr[mid] < searchValue) {
				low = mid + 1; //Exclude the lower halve of the array
			}
			else {
				high = mid - 1; //Exclude the upper halve of the array
			}
		}
		
		if (found) {
			System.out.println(searchValue + " found at index " + mid + " of the sorted array.");
		}
		else {
			System.out.print(searchValue + " not found in the entire sorted array. ");
			System.out.println("You may wish to insert if before index " + mid + " of the sorted array.");
		}
	}
	
}
Searching Alogrithm: Binary Search



9.4Implementation of Methods (or Functions) in Java
Generally, with respect to the domain of computer programming, a method (or function) is simply a block of code that encapsulates a sequence of steps taken toward the actualization of a specific task. Additionally, a method (or function) is usually identified by a valid identifier known as the name of the method/function; such that whenever a call is made to the name of the method/function, this results in the execution of the sequence of steps encapsulated within the body of the method (or function) definition.

In fact, the concept of methods (or functions) is quite common with reference to our daily activities and/or routines as humans. For example, when we want to take a bath or shower, we are implicitly calling a method/function which may be identified as bath or shower. Thus, upon execution of the aforementioned method, it essentially accomplishes the task of a bath or shower.
Bath or Shower method definition:
  1. Take off clothes.
  2. Get bath sponge and bathing soap.
  3. Rub the soap against the sponge until a desirable amount of lather is generated.
  4. Gently scrub body with sponge and lather.
  5. Rinse body (and sponge) with warm water.
  6. Dry body with a bath towel.

Also, another real-world (daily) task that employs the concept of methods (or functions) is the task of brushing our teeth.
Teeth-Brushing method definition:
  1. Get toothbrush and toothpaste.
  2. Apply pea-size amount of toothpaste onto the toothbrush.
  3. Thoroughly (and with care) brush teeth and tongue with toothbrush.
  4. Spit out or rinse mouth with water.
  5. Rinse toothbrush with warm water.

Consequently, with regard to computer programming, implementation of methods (or functions) helps in avoiding unnecessary repetitions of a given block of code with respect to the execution of a specific task. In Java programming, there can exist two (2) broad types of methods (or functions), namely:
  1. Instance Method:
    • This is a function defined within a class block.
    • To make a call to this type of methods; an instance or object of the (host) class block must be declared and initialized using the new keyword. Actually, this instance or object is like a virtual copy of the (host) class block; and it serves as a "gateway" to accessing all the instance-type methods defined within the class block.
    • Calls to this type of methods are usually with reference to the instance or object of the (host) class block.
    • The following code snippet showcases the definition of an instance method in Java.
    • public <returnDataType||void> <methodName> (<parameter_1Declaration>, ..., <parameter_nDeclaration>) {
      	 //action: lines of code (method body)
      	 return <taskResult>
      }
      
      //Example:
      public double circleArea (double radius) {
      	 double localVar = 3.142 * radius * radius;
      	 return localVar;
      }
      
      Pseudocode: Syntax of an instance method
    • The following code snippet represents the syntax for calling an instance method in Java.
    • <classBlockName> <objectIdentifier> = new <classBlockName>();
      <objectIdentifier>.<methodName>(<parameters>);
      
      //Example:
      ArraysofData2 obj1 = new ArraysofData2();
      obj1.circleArea(5.65);
      
      Pseudocode: Syntax for calling an instance method

  2. Static Method:
    • This is a function that explicitly specifies the static keyword (or modifier) in the header of the method's definition within a class block.
    • To make a call to this type of methods; an instance/object of the (host) class block is never required. The (host) class block permits direct access to all static-type methods defined within it.
    • Calls to this type of methods are usually with direct reference to the (host) class block.
    • The following code snippet showcases the definition of a static method in Java.
    • public static <returnDataType||void> <methodName> (<parameter_1Declaration>, ..., <parameter_nDeclaration>) {
      	 //action: lines of code (method body)
      	 return <taskResult>
      }
      
      //Example:
      public static double circleCircumference (double radius) {
      	 double localVar = 3.142 * radius * 2;
      	 return localVar;
      }
      
      Pseudocode: Syntax of a static method
    • The following code snippet represents the syntax for calling a static method in Java.
    • <classBlockName>.<methodName>(<parameters>);
      
      //Example:
      ArraysofData2.circleCircumference(10.25);
      
      Pseudocode: Syntax for calling a static method


Parameter (or Formal Parameter): This is a variable declaration, within the header of a method (or function) definition, and it serves as a placeholder for the expected (data) value into the method/function.
Argument (or Actual Parameter): This is the actual (data) value that is passed to a Parameter (or Formal Parameter) during a call to the method/function.
public static double circleCircumference (double radius) { //Parameter = "radius"
	 double localVar = 3.142 * radius * 2;
	 return localVar;
}

double argVal = 10.25;
ArraysofData2.circleCircumference(argVal); //Argument = "argVal"
Code Snippet: Argument vs. Parameter

Pass by Value → method(Arguments)
  1. This involves passing a copy of the argument (e.g. variables, constants, etc.), as a parameter, into the body of the method.
  2. This means that only a true copy of the argument is used for the computation of result(s) and/or task(s) within the body of the method.
  3. Any update and/or modification made to the parameter, within the body of the method, only applies to the parameter itself which is a true copy (and it does not alter the actual or original argument).
  4. In Java programming, Pass by Value only applies to all Primitive (data) types with the inclusion of the String (data) type.

Pass by Reference → method(Arguments)
  1. Also known as Pass by Address.
  2. This involves passing the object-reference of the argument (e.g. variables, constants, etc.), as a parameter, into the body of the method.
  3. This means that the true value of the argument, which is directly accessed via its object-reference, is used for the computation of result(s) and/or task(s) within the body of the method.
  4. Any update and/or modification made to the parameter, within the body of the method, directly applies to the original argument which was initially passed to the method.
  5. In Java programming, Pass by Reference only applies to all Non-Primitive (data) types with the exclusion of the String (data) type.

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

import java.util.Arrays;

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int dataArr[] = {0, 100, -5, 1, 4, 10, 8, 9, 5, 41};
		
		//Create an instance/object of the (host) class block
		ArraysofData2 obj1 = new ArraysofData2();		
		
		System.out.println("Before update, dataArr[] = " + Arrays.toString(dataArr));
		int sumRes1 = obj1.summation(dataArr); //Argument = "dataArr[]" (Pass by Reference)
		System.out.println("Before update, sum of values in dataArr[] = " + sumRes1);
		
		obj1.alternator(dataArr); //Argument = "dataArr[]" (Pass by Reference)
		
		System.out.println("After update, dataArr[] = " + Arrays.toString(dataArr));
		int sumRes2 = obj1.summation(dataArr); //Argument = "dataArr[]" (Pass by Reference)
		System.out.println("After update, sum of values in dataArr[] = " + sumRes2);
	}
	
	
	public void alternator (int[] arrRef1) { //Parameter = "arrRef1[]" (Pass by Reference)
		for (int i = 0; i < arrRef1.length; i++) {
			arrRef1[i] = arrRef1[i] + (i * i); //Accessing and Updating the true value of "arrRef1[]"
		}
	}
	
	public int summation (int[] arrRef2) { //Parameter = "arrRef2[]" (Pass by Reference)
		int sum = 0;
		for (int element : arrRef2) {
			sum += element; //Accessing the true value of "arrRef2[]"
		}
		
		return sum;
	}
	
}
Code Snippet: Pass by Reference to instance methods

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

import java.util.Arrays;

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int dataArr[] = {0, 100, -5, 1, 4, 10, 8, 9, 5, 41};
		
		System.out.println("Before update, dataArr[] = " + Arrays.toString(dataArr));
		int sumRes1 = ArraysofData2.summation(dataArr); //Argument = "dataArr[]" (Pass by Reference)
		System.out.println("Before update, sum of values in dataArr[] = " + sumRes1);
		
		ArraysofData2.alternator(dataArr); //Argument = "dataArr[]" (Pass by Reference)
		
		System.out.println("After update, dataArr[] = " + Arrays.toString(dataArr));
		int sumRes2 = ArraysofData2.summation(dataArr); //Argument = "dataArr[]" (Pass by Reference)
		System.out.println("After update, sum of values in dataArr[] = " + sumRes2);
	}
	
	
	public static void alternator (int[] arrRef1) { //Parameter = "arrRef1[]" (Pass by Reference)
		for (int i = 0; i < arrRef1.length; i++) {
			arrRef1[i] = arrRef1[i] + (i * i); //Accessing and Updating the true value of "arrRef1[]"
		}
	}
	
	public static int summation (int[] arrRef2) { //Parameter = "arrRef2[]" (Pass by Reference)
		int sum = 0;
		for (int element : arrRef2) {
			sum += element; //Accessing the true value of "arrRef2[]"
		}
		
		return sum;
	}
	
}
Code Snippet: Pass by Reference to static methods

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

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int dataArr[] = {0, 100, -5, 1, 4, 10, 8, 9, 5, 41};
		int arrSize = dataArr.length;
		
		//Create an instance/object of the (host) class block
		ArraysofData2 obj1 = new ArraysofData2();		
		
		int sumRes = ArraysofData2.summation(dataArr); //Argument = "dataArr[]" (Pass by Reference)
		obj1.outputStr(arrSize, sumRes); //Arguments = "arrSize", "sumRes" (Pass by Value)
	}
	
	
	//Instance method
	public void outputStr (int arrLen, int arrSum) { //Parameters = "arrLen", "arrSum" (Pass by Value)
		System.out.println("The sum of the " + arrLen + " elements resident in the array is = " +  arrSum);
	}
	
	//Static method
	public static int summation (int[] arrRef) { //Parameter = "arrRef[]" (Pass by Reference)
		int sum = 0;
		for (int element : arrRef) {
			sum += element; //Accessing the true value of "arrRef[]"
		}
		
		return sum;
	}
	
}
Code Snippet: Pass by Reference and Pass by Value to methods

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

import java.util.Arrays;

public class ArraysofData2 {
	
	public static void main(String[] args) {
		int[] retArr = ArraysofData2.arrayReturn(15); //Argument = "15" (Pass by Value)
		System.out.println(Arrays.toString(retArr));
	}
	
	
	public static int[] arrayReturn (int arrLen) { //Parameter = "arrLen" (Pass by Value)
		int[] newArr = new int[15]; //Create a new array identified as "newArr"
		
        for (int i = 0; i < newArr.length; i++) {
        	newArr[i] = newArr[i] + (i * i); //Accessing and Updating the true value of "newArr"
        }
        
        return newArr; //Returns a integer-type array structure
    }
	
}
Code Snippet: Returning an array (data) structure from a call to a method



9.5Two-Dimensional (2D) Arrays in Java Programming
Earlier in section 5.3 herein, we introduced (and worked on) the concept of two-dimensional (2D) data arrays. Kindly refer to section 5.3 for several algorithms and tasks which employed the concept of 2D arrays. Thus, a two-dimensional (2D) data array is a data matrix comprising several (variable) values possessing the same data type. Therefore, using a 2D array in programming usually require the actualization of the following steps, viz:
  1. Declaration of a valid identifier for the 2D-array's data structure: <dataType>[][] <identifier>; or <dataType> <identifier>[][];
  2. Instantiation of the 2D-array with respect to a specific data type and content size/length: <identifier> = new <dataType>[rows][columns];

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

public class ArraysofData2 {
	
	public static void main(String[] args) {
		//Declaration and Instantiation of two-dimensional (2D) arrays - Approach 1
		float[][] newFloatArr1;
		newFloatArr1 = new float[10][5];
		float newFloatArr2[][];
		newFloatArr2 = new float[5][5];
		
		//Declaration and Instantiation of two-dimensional (2D) arrays - Approach 2
		double[][] newDoubleArr1 = new double[10][5];
		double newDoubleArr2[][] = new double[5][5];
		
		//Declaration and Instantiation of two-dimensional (2D) arrays - Approach 3
		int[][] newIntArr1 = {
								{8, 5, 66, 2, 0},
								{55, 11, 9, 4, 22},
								{100, 77, 50, 14, 3},
								{1, 6, 7, 12, 15},
								{13, 16, 18, 20, 19}
							 }; //Initialization values for 'newIntArr1[][]' array
		int[][] newIntArr2 = {
								{8, 5, 66, 2, 0},
								{55, 11, 9, 4, 22},
								{100, 77, 50, 14, 3},
								{1, 6, 7, 12, 15},
								{13, 16, 18, 20, 19}
							 }; //Initialization values for 'newIntArr2[][]' array
	}
	
}
Code Snippet: Declaration and instantiation of two-dimensional (2D) array data structures

2D array with index(es) positionings and corresponding sample value(s)
Caption: 2-Dimensional (2D) array with index(es) positionings mapped to corresponding sample value(s)

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

public class ArraysofData2 {
	
	public static void main(String[] args) {
		/* Rectangular Array: 2D-array with strictly consistent column sizes */
		int[][] myArr = { {8, 5, 66, 2, 0},
						  {55, 11, 9, 4, 22},
						  {100, 77, 50, 14, 3},
						  {1, 6, 7, 12, 15},
						  {13, 16, 18, 20, 19} };
		
		//Traverse data rows (horizontally)
		for (int i = 0; i < myArr.length; i++) {
			//Traverse data columns (vertically)
			for (int j = 0; j < myArr[i].length; j++) {
				System.out.print(" | " + myArr[i][j]);
			}
			System.out.println(" |");
		}
		
		/* Ragged (or Jagged) Array: 2D-array with inconsistent column sizes */
		int[][] jaggedArr = { {1,2,3},
							  {6},
							  {11,12,13,14},
							  {16,17},
							  {21,22,23,24,25,26,27},
							  {30,33} };
		
		//Traverse data rows (horizontally)
		for (int i = 0; i < jaggedArr.length; i++) {
			//Traverse data columns (vertically)
			for (int j = 0; j < jaggedArr[i].length; j++) {
				System.out.print(" | " + jaggedArr[i][j]);
			}
			System.out.println(" |");
		}
	}
	
}
Code Snippet: Traversing a two-dimensional (2D) array. Refer to Algorithms 9 to 13 for additional examples on 2D arrays.



9.6Practice Exercise
  1. Consider the following Java program with respect to the implementation of a popular algorithm. Thus, do you think that this program actualizes its goal? If yes, then state the exact screen output(s). If otherwise, then expantiate on the bug(s) as well as the type of error/bug herein.
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Arrays of Data 2.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
      
    public class ArraysofData2 {
    	
    	public static void main(String[] args) {
    		int dataArr[] = {0, 100, -5, 1, 4, 10, 8, 9, 5, 41};		
    		
    		boolean found = false;
    		int low = 0, high = (dataArr.length -1), mid = 0, searchValue = 8;
    		
    		while ((low <= high) && !found) {
    			mid = (low + high) / 2; //Division of integers returns a truncated (or floored) result
    			if (dataArr[mid] == searchValue) {
    				found = true; //Found a match
    			}
    			else if (dataArr[mid] < searchValue) {
    				low = mid + 1; //Exclude the lower halve of the array
    			}
    			else {
    				high = mid - 1; //Exclude the upper halve of the array
    			}
    		}
    		
    		if (found) {
    			System.out.println(searchValue + " found at index " + mid + " of the sorted array.");
    		}
    		else {
    			System.out.print(searchValue + " not found in the entire sorted array. ");
    			System.out.println("You may wish to insert if before index " + mid + " of the sorted array.");
    		}
    	}
    	
    } 
    

  2. Consider the following Java program with respect to the implementation of a common algorithm. Thus, do you think that this program actualizes its purpose? If yes, then generate the for {} loop equivalent with respect to the while {} loop construct within the program. If otherwise, then expantiate on the bug(s) as well as the type of error/bug herein.
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Arrays of Data 2.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
      
    public class ArraysofData2 {
    	
    	public static void main(String[] args) {
    		int dataArr[] = {0, 100, -5, 1, 4, 10, 8, 9, 5, 41};
    		
    		boolean found = false;
    		int idx = 0, high = (dataArr.length -1), searchValue = 8;
    		
    		while ((idx <= high) && !found) {
    			if (dataArr[idx++] == searchValue) {
    				found = true; //Found a match
    			}
    		}
    		
    		if (found) {
    			System.out.println(searchValue + " has been found at index " + (idx - 1) + " of the array.");
    		}
    		else {
    			System.out.println(searchValue + " was not found in the entire array. ");
    		}
    	}
    	
    } 
    

  3. TRUE or FALSE: The Binary Search algorithm can be employed with regard to any type of items/elements collection irrespective of the elements' ordering?

  4. TRUE or FALSE: The sort() method, which is resident in the Arrays class block, essentially implements a Bubble Sort algorithm in its backend code?

  5. Kindly examine the following Java program with the aid of hand tracing, and explain the logic as well as the purpose of the program. Also, after the program execution, state the expected values that should be resident in the arrays: dataArr and retArr.
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Arrays of Data 2.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
    
    import java.util.Arrays;
      
    public class ArraysofData2 {
    	
    	public static void main(String[] args) {
    		int dataArr[] = {0, 100, -5, 1, 4, 10, 8, 9, 5, 41};
    		
    		int[] retArr = ArraysofData2.autoAction(dataArr);
    
    		System.out.println(Arrays.toString(dataArr));
    		System.out.println(Arrays.toString(retArr));
    	}
    	
    	
    	public static int[] autoAction (int values[]) {
    		int result[] = new int[values.length];
    		
            for (int i = 0; i < values.length; i++) {
            	result[i] = values[values.length - 1 - i];
            }
            
            return result;
        }
    }
    

  6. Examine the following Java program via hand tracing, and explain the logic as well as the purpose of the program. Also, upon completion of the program's execution, state the expected values that should be resident in the arrays: dataArr and retArr.
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Arrays of Data 2.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
    
    import java.util.Arrays;
      
    public class ArraysofData2 {
    	
    	public static void main(String[] args) {
    		int dataArr[] = {0, 100, -5, 1, 4, 10, 8, 9, 5, 41};
    		
    		int[] retArr = ArraysofData2.autoAction(dataArr);
    
    		System.out.println(Arrays.toString(dataArr));
    		System.out.println(Arrays.toString(retArr));
    	}
    	
    	
    	public static int[] autoAction (int values[]) {		
            for (int i = 0; i < values.length; i++) {
            	values[i] = values[values.length - 1 - i];
            }
            
            return values;
        }
    }
    

  7. Given the following Java program; kindly describe what this program does, and generate the do-while {} loop equivalent with respect to the while {} loop construct within this block of code.
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Arrays of Data 2.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
    
    import java.util.Scanner;
    import java.util.Arrays; //package required for the toString() method
    
    public class ArraysofData2 {
    	
    	public static void main(String[] args) {
    		int iterator = 0;
            final int NUMBER_OF_INPUTS = 3;
            double[] inVals = new double[NUMBER_OF_INPUTS];
            Scanner usrInput = new Scanner(System.in);
            
            while (iterator < NUMBER_OF_INPUTS) {
                System.out.print("Please enter a value for number " + ++iterator + ": ");
                inVals[iterator-1] = usrInput.nextDouble();
                System.out.println();
            }
    
            //toString(): Returns (data) contents of a 1D array in human-friendly format
            System.out.println(Arrays.toString(inVals));
            
            //Flushes and closes the "Scanner" buffer so as to prevent resource leakage/wastage.
            usrInput.close();
    	}
    	
    }
    

  8. Consider and dry-run the following Java program; thus, find out if there exists any error within the program? If yes, then expantiate on the bug(s) as well as the type of error/bug herein. If otherwise, then state the exact screen output(s).
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Arrays of Data 2.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
    
    public class ArraysofData2 {
    	
    	public static void main(String[] args) {
    		int[][] myArr = { {1,2,3},
    						  {6},
    						  {11,12,13,14},
    						  {16,17},
    						  {21,22,23,24,25,26,27},
    						  {30,33} };
    		
    		//Traverse data rows (horizontally)
    		for (int i = 1; i <= myArr.length; i++) {
    			//Traverse data columns (vertically)
    			for (int j = 1; j <= myArr[i].length; j++) {
    				System.out.print(" | " + myArr[i][j]);
    			}
    			System.out.println(" |");
    		}
    	}
    	
    }
    

  9. Which of the following options represents the proper and error-free syntax for defining an instance method that accepts an array (as a parameter) and returns an array (of at most 3 elements)?
    1. public int[3] autoAction (int values[3]) {...}
    2. public int[3] autoAction (int values[]) {...}
    3. public int[] autoAction (int values[]) {...}
    4. public int[] autoAction (int values[3]) {...}
    5. public static int[3] autoAction (int values[]) {...}
    6. public static int[] autoAction (int values[]) {...}

  10. Dry-run the following block of code, and specify the exact screen output(s).
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Arrays of Data 2.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
    
    public class ArraysofData2 {
    	
    	public static void main(String[] args) {
    		int[][] myArr = { {1,2,3},
    						  {6},
    						  {11,12,13,14},
    						  {16,17},
    						  {21,22,23,24,25,26,27},
    						  {30,33} };
    		
    		System.out.print(myArr[4][5]);
    		System.out.print(myArr[2][3]);
    	}
    	
    }
    

  11. Dry-run the following block of code, and specify the exact screen output(s).
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Arrays of Data 2.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
    
    public class ArraysofData2 {
    	
    	public static void main(String[] args) {
    		int[][] myArr = { {1,2,3},
    						  {6},
    						  {11,12,13,14},
    						  {16,17},
    						  {21,22,23,24,25,26,27},
    						  {30,33} };
    		
    		System.out.println(myArr[2][3]++ + ++myArr[4][5]);
    	}
    	
    }
    

  12. With reference to following Java program, dry-run via hand tracing and state the exact screen output(s).
    /**
     * @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
     * @course ProgrammingLessons (proglessons).
     * @title Arrays of Data 2.
     * @author Dr. Bonaventure Chidube Molokwu.
     */
    
    public class ArraysofData2 {
    	
    	public static void main(String[] args) {
    		int[][] myArr = { {8, 5, 66, 2, 0},
                              {55, 11, 9, 4, 22},
                              {100, 77, 50, 14, 3},
                              {1, 6, 7, 12, 15},
                              {13, 16, 18, 20, 19} };
    		
    		System.out.println("Resultant is = " + myArr[2][3]++ + myArr[2][3]);
    	}
    	
    }
    

Sponsored Ads