This example is in Java. For AP CSP Pseudocode, see Parameters as abstractions in AP CSP Pseudocode.
Abstractions in computer science hide details to manage complexity.
Commonly used abstractions include:
- Variables
- Procedures (often called methods or functions)
- Parameters (see details below)
- Classes (in object oriented languages such as Java)
- Lists
- Strings
Many methods can be written more generally by using one or more parameters.
The example below assumes an understanding of:
- Writing and calling Methods with parameters
- Traversing ararys and lists
Example: Searching for a value in a list
With a key parameter
public static boolean search(int[] arr, int key)
{
for (int i = 0; i < arr.length; i++)
if (arr[i] == key)
return true;
return false;
}
The search method returns true if its parameter key is in its parameter arr, false otherwise.
Without a key parameter
public static boolean searchForFive(int[] arr)
{
for (int i = 0; i < arr.length; i++)
if (arr[i] == 5)
return true;
return false;
}
public static boolean searchForTen(int[] arr)
{
for (int i = 0; i < arr.length; i++)
if (arr[i] == 10)
return true;
return false;
}
The searchForFive and searchForTen methods implement the same algorithm as the search method, but without the parameter key.
Without the parameter key, searchForFive must compare each value in arr to 5 and searchForTen must compare each value to 10. Searching for a different value, such as 15, would require writing another version.
The parameter manages complexity
Parameters are abstractions because they allow the code inside a method to be written more generally.
Related examples
Help & comments
Get help from AP CS Tutor Brandon Horn