Week13 14 Arrays Part2 Student
Week13 14 Arrays Part2 Student
Week13 14 Arrays Part2 Student
Fundamentals of
Computer Programming
25
ACCESSING ARRAY
❑ String[] names = new String[6];
❑ names[0], names[1], names[2], names[3], names[4], names[5]
❑ Variables like names[0] and names[1] that have an integer expression in square
brackets are called indexed variables, subscripted variable, array elements, or simply
elements. An index or a subscript is an integer contained within square brackets that
indicates one of an array’s variables, or elements. Note that the numbering starts with
0, not 1 and last index will always be length -1.
❑ Elements within the array are accessed using square brackets `[ ]` with the index
value inside.
❑ String firstName = names[0]; //accessing the first element in `names` array.
ARRAY INDEX
❑ The first element in a Java array has an index of 0, and the last valid index for an array of
length n is n − 1.
❑ For an array named temperature, the last valid index is temperature.length - 1.
❑ In the array declaration double[] entry = new double[5];, valid indices are 0, 1, 2, 3, and 4.
❑ Any indexed expression, such as entry[n + 2], must result in an index within the valid range
(0 to length - 1).
❑ Using an index outside this range is considered out of bounds or invalid, and it's a common
mistake when working with arrays.
❑ You can obtain the length of an array using the length property. For example, int[] numbers
= {1, 2, 3}; int length = numbers.length;.
POPULATING AN ARRAY
POPULATING AN ARRAY
❑ Arrays can have non-default values assigned during creation.
❑ To initialize an array, use a list of values enclosed in curly braces, separated by
commas.
❑ Example: int[] someNum = {10, 20, 30, 40, 50};
❑ Include a semicolon at the end of the statement.
❑ Populating an array during creation means providing values without explicitly
specifying the size.
❑ The array size is determined by the number of values in the initializing list.
❑ The someNum array in the example has a size of 5.
DECLARING AND POPULATING AN ARRAY
Square
Bracket Comma (after every
elements) Closing Curly Braces
26
POPULATING AN ARRAY
USING A FOR LOOP TO ACCESS ARRAY ELEMENTS
USING VARIABLES IN AN ARRAY
❑ Java allocates memory for an array and other objects during execution.
❑ To dynamically determine the array size, you can read the length from the keyboard.
❑ This approach allows flexibility when the array size is not known at the time of program writing.
❑ Reading the array length from the keyboard enables user input to define the size during runtime.
SEARCHING AN ARRAY
LINEAR SEARCH
❑ Precondition: Linear search works on both sorted and unsorted data. It doesn't require
any specific order of data, making it more versatile.
❑ Time Complexity: O(n) in the worst case. Linear search involves checking each element
one by one until the target is found or the end of the list is reached.
❑ Efficiency: Linear search is simple and easy to implement. It is efficient for small
datasets or when the target element is near the beginning of the list. It's also suitable for
situations where the data is frequently changing.
❑ Space Complexity: O(1) for both iterative and recursive implementations.
SEARCHING AN ARRAY
❑ To find an element in an array, we look through each item in the list and
compare it to what we're searching for.
❑ This process can be done using loops, like for loops or while loops.
❑ After going through the whole array, we use a special switch (a boolean
variable) to indicate whether we found the element or not.
❑ Initially set as "not found" (false), it changes to "found" (true) if we discover the
element.
❑ This method helps us determine if an element exists in the array.
SEARCHING AN ARRAY
SEARCHING AN ARRAY
❑ Similarly we can also use the index to find the element of an array.
❑ We begin by examining each item in the array (numbers).
❑ Using a loop (in this case, a for loop), we traverse through each element in the list.
❑ For each element, we compare it to the value we're looking for (target).
❑ If an element matches the target, we record its index.
❑ If the element is found, we display a message stating the index where it was found. If no
match is found, we print a message indicating the element was not present in the array.
❑ Initially set as -1 (indicating "not found"), it changes to the index if we discover the
element.
❑ This variable helps us confirm the existence of the element within the array.
SEARCHING AN ARRAY
BINARY SEARCH
❑ Precondition: Binary search works on sorted data. If the data is not sorted, you would
need to sort it first, which could have a time complexity of O(n log n). However, once
sorted, binary search can be very efficient.
❑ Time Complexity: O(log n) in the worst case. Binary search reduces the search space by
half at each step, making it significantly faster than linear search for large datasets.
❑ Efficiency: Binary search is more efficient than linear search, especially for large
datasets. It's particularly useful when the dataset is static or changes infrequently
because sorting is a one-time cost.
❑ Space Complexity: O(1) for iterative binary search, O(log n) for recursive binary search.
BINARY SEARCH
In summary, return is used for exiting functions/methods and optionally returning values,
while break is used for control flow within loops and switch statements to immediately exit
them.
ENHANCED FOR LOOP
ENHANCED FOR LOOP
The enhanced for loop, also known as the foreach loop, was introduced in Java 5 to simplify
the process of iterating through arrays and collections. It provides a concise and readable
syntax for iterating over elements without the need for explicit indexing.
Syntax:
The syntax of the enhanced for loop is as follows:
for (element_type element : array_or_collection) {
// code block
}
ENHANCED FOR LOOP
❑ element_type: The data type of the elements in the array or collection.
❑ element: A variable representing the current element in each iteration.
❑ array_or_collection: The array or collection through which iteration occurs.
Example:
int[] numbers = {1, 2, 3, 4, 5};
// Enhanced for loop to iterate through the array
for (int num : numbers) {
System.out.println(num);
}
ENHANCED FOR LOOP
❑ Readability: The enhanced for loop enhances code readability by abstracting the details of
indexing and iteration.
❑ No Index Management: It eliminates the need for explicit index management, making the
code less error-prone and more concise.
❑ Immutable Elements: The loop variable (element in the syntax) is effectively final within
the loop; you can't modify it.
❑ Applicability: It's primarily designed for situations where you need to iterate over all
elements in a collection or array and don't need the index.
❑ Arrays and Collections: The enhanced for loop works for arrays and any class that
implements the Iterable interface, such as collections.
❑ No Backward Iteration: It only supports forward iteration. If backward or index-based
iteration is required, the traditional for loop should be used.
LIMITATION OF ENHANCED FOR LOOP
❑No Access to Index: If you need the index or want to modify array
elements, the traditional for loop is more suitable.
❑Read-Only: The enhanced for loop is read-only; you cannot modify the
array or collection being iterated through.
❑No Control Over Iteration: It doesn't provide as much control as the
traditional for loop; for more complex iteration scenarios, the traditional
loop may be preferred.
SEARCHING A PARALLEL
ARRAY
SEARCHING A PARALLEL ARRAY
❑ A parallel array refer to using multiple arrays that are related by their indices. Each array
stores different aspects or attributes of related data using same index for corresponding
elements.
❑ In simpler terms, multiple arrays that has an equal number of elements as another, with
related values in corresponding positions.
❑ Illustratively, consider an array named Fruits storing fruit names. Checking if a color-
matching fruit exists involves comparing the variable to valid values.
❑ To facilitate this, a parallel array named colors is established with the same number of
elements, associating additional information with the corresponding fruit.
❑ This design simplifies accessing related information using the same subscript for both arrays.
SEARCHING A PARALLEL ARRAY
JOPTIONPANE
JOptionPane
JOptionPane is a class in Java's Swing library that provides a set of
methods for displaying dialog boxes or message boxes to interact with
the user in graphical user interface (GUI) applications. It allows you to
display various types of dialogs, prompt for user input, and show
informative messages.
Dialog Types:
• Message Dialog
• Confirmation Dialog
• Input Dialog
• Option Dialog
JOptionPane
Message Dialogs: You can use JOptionPane to display message dialogs to provide
information or notify the user.
Confirmation Dialogs: Confirmation dialogs are used to ask the user for
confirmation or choice. They typically present options such as Yes/No, OK/Cancel,
or custom buttons.
Input Dialogs: Input dialogs allow you to prompt the user for input. You can use
them to request text input or numeric input from the user.
Option Dialogs: Option dialogs provide a customizable set of options for the user to
choose from. You can present a list of buttons with associated actions, and the
selected option can be determined and processed accordingly.
JOptionPane
Message Dialogs:
JOptionPane.showMessageDialog(parentComponent, object message);
Confirmation Dialogs:
JOptionPane.showConfirmDialog(parentComponent, object message, String title, int optionType);
Input Dialogs:
Input (text):
JOptionPane.showInputDialog(parentComponent, object message);
Input (Dropdown):
(String)JOptionPane.showInputDialog(parentComponent, object message, String title,
messageType, icon, object[], initialValue);
Option Dialogs:
JOptionPane.showOptionDialog(parentComponent, Object message, String title, int
optionType,int messageType, Icon icon, Object[] options,Object initialValue);
MESSAGE DIALOG
MESSAGE DIALOG
CONFIRMATION DIALOG
CONFIRMATION DIALOG
INPUT DIALOG
INPUT DIALOG (Numeric Input)
INPUT DIALOG (DROPDOWN)
INPUT DIALOG (DROPDOWN)
OPTION DIALOG
IMPORTANT REMINDERS:
❑ Array indices in Java always start at 0, never at 1 or any other number.
❑ The last valid index is one less than the length of the array.
❑ Ensure that array indices remain within the valid range (0 to length - 1).
❑ An array index less than 0 or greater than or equal to the array size results in an
Array Index Out of Bounds Exception during program execution.
❑ Careful validation of array indices is crucial to prevent this type of error.
❑ There is an alternative syntax for array declarations, where square brackets can
be placed after the variable instead of after the base type. For instance: char
alphabet[];
SUMMARY:
❑ An array in Java is a named list of data items of the same type, declared by
adding square brackets after the type.
❑ Memory space for an array is reserved using the keyword 'new'.
❑ Elements in an array are accessed using subscripts or indices within square
brackets, starting from zero in Java.
❑ Default values for numeric array elements are 0, char elements are '\u0000',
boolean elements are false, and String elements are null.
❑ Initialization of an array with non-default values is done using a list enclosed in
curly braces and separated by commas.
SUMMARY:
❑ Utilizing a variable as a subscript can streamline array-based tasks.
❑ Loops often iterate from 0 to one less than the array size when working with
arrays in applications.
❑ Searching for a value in an array involves looping through and making
comparisons.
❑ Parallel arrays, with the same number of elements, can be used to hold related
information in corresponding positions.
Fundamentals of Computer Programming
The End
WEEK 5