Chapter 5 Flashcards
What is an array in Java?
An array is a collection of variables of the same type, stored in a fixed-size sequential order. It allows grouping multiple variables under one name, making data management more efficient.
How do you declare and initialize an array in Java?
```java
int[] scores = new int[50]; // Declares an array of integers with 50 elements
char[] letters = new char[10]; // Declares an array of characters with 10 elements
~~~
Arrays must be instantiated before use.
How are arrays indexed in Java?
An array of size N is indexed from 0 to N-1. Each element can be accessed using an index in square brackets.
Example:
```java
int[] scores = {79, 87, 94, 82, 67, 98, 87, 81, 74, 91};
System.out.println(scores[2]); // Outputs: 94
~~~
What are array elements in Java?
Array elements are the values stored within an array. Each element has an index and must be of the same type as the array. Arrays can store primitive data types (int, char, double) or objects.
Where are arrays stored in Java memory?
Arrays are objects in Java, and Java Virtual Machine (JVM) stores them in the heap memory.
How do you assign values to an array?
```java
scores[2] = 89; // Assigns 89 to index 2
scores[first] = scores[first] + 2; // Updates value at ‘first’ index
mean = (scores[0] + scores[1]) / 2; // Uses array values in a calculation
System.out.println(“Top = “ + scores[5]); // Prints a specific element
~~~
Arrays allow direct element manipulation using their index.
How can you declare an array in Java?
An array can be declared as:int[] scores;
// just declaringint[] scores = new int[10];
// declaring and initializing
What is the type of the variable scores
when declaring it as int[] scores
?
The type of the variable scores
is int[]
, meaning it is an array of integers.
Does the array type in Java specify its size?
No, the array type does not specify its size. However, each object of that type has a specific size once it is instantiated.
What happens when you declare an array like int[] scores = new int[10];
?
The reference variable scores
is set to a new array object that can hold 10 integers.
How can the brackets of the array type be associated in Java?
The brackets of the array type can be associated either with the element type or with the name of the array.
For example:float[] prices;
float prices[];
Both are equivalent, but the first format is generally more readable and should be used.
Can you give examples of array declarations with initialization in Java?
Yes, here are some examples:float[] prices = new float[500];
boolean[] flags; flags = new boolean[20];
char[] codes = new char[50];
What is the default value for numeric primitive data type elements in an array?
The default value is zero.
What is the default value for boolean elements in an array?
The default value is false
.
What is the default value for char
elements in an array?
The default value is \u0000
.
How can a programmer initialize an array’s elements with non-default values?
A programmer can specify the initial values in braces {}
separated by commas.
For example:int[] myArray = {5, 7, 11};
char[] letterGrades = {'A', 'B', 'C', 'D', 'F'};
What are the key points when using an initializer list for an array in Java?
When an initializer list is used:
- The new
operator is not used.
- No size value is specified.
- The size of the array is determined by the number of items in the initializer list.
- It can only be used in the array declaration.
Example:int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476};
How would you declare and initialize an array of Strings in Java?
Declare an array and assign values as follows:String[] names = new String[3];
names[0] = "Sophia";
names[1] = "Emma";
names[2] = "Isabella";
What happens when you declare and initialize an array of Strings, but only assign values to some elements?
Unassigned elements will have the value null
.
Example:String[] names = new String[3];
names[0] = "Sophia";
After initialization:names[0] = "Sophia";
names[1] = null;
names[2] = null;
How do you assign a value to an element of an array and then modify it in Java?
You can assign a value and modify it later. For example:String[] names = new String[3];
names[0] = "Sophi";
names[0] = names[0] + "a";
This will result in names[0] = "Sophia";
.
How does array syntax compare to non-array types in Java?
For arrays:
- Square brackets []
are used.
- Arrays require an additional statement to size the array using new
.
- Square brackets and an index are used to access elements (both to get and to set).
Can elements of an array in Java be object references?
Yes, the elements of an array can be object references.
How would you declare an array to store 5 references to String
objects in Java?
String[] words = new String[5];
This reserves space for 5 references to String
objects but does not create the String
objects themselves.
What is the initial value of each element in an array of objects when it is declared in Java?
Initially, each element in an array of objects holds a null
reference.
What happens if you try to access an element of an array of objects that has not been instantiated yet?
Trying to access an uninitialized element will throw a NullPointerException
.
Example: System.out.println(words[0]);
This would throw an exception if words[0]
is `null.
How do you instantiate objects and store them in an array of object references?
Each object in the array must be instantiated separately. For example: words[0] = new String("friendship");
words[1] = new String("loyalty");
`words[2] = new String(“honor”);
How can String
objects be created using literals in Java?
String literals are sequences of characters enclosed in double quotation marks.
Example: “TCNJ”
How do you declare and initialize an array of String
objects using literals?
You can declare and initialize an array of String
objects using literals like this: String[] verbs = {"play", "work", "eat", "sleep"};
This creates an array called verbs
with 4 String
objects.
How do you declare a two-dimensional array in Java?
A two-dimensional array can be declared as follows: int[][] myArray = new int[2][3];
This creates an array with 2 rows and 3 columns.
How is a two-dimensional array represented in memory?
A two-dimensional array is conceptually a table with rows and columns but is stored in memory as a one-dimensional array. Each row follows the previous row in memory. This is called row-major order.
How would you access an element in a two-dimensional array?
To access an element, you use two indices: one for the row and one for the column.
Example: myArray[0][1]
This accesses the element in the first row and second column.
How would you initialize a two-dimensional array in Java?
You can initialize a two-dimensional array during declaration like this: int[][] numVals = {{22, 44, 66}, {97, 98, 99}};
How can you format a two-dimensional array initialization to make the rows more visible?
You can use multiple lines for clarity:
```java
int[][] numVals = {
{22, 44, 66}, // Row 0
{97, 98, 99} // Row 1
};
~~~
What is row-major order in the context of two-dimensional arrays?
Row-major order refers to how the elements of a two-dimensional array are stored in memory, where each row is stored consecutively in memory, one after the other.
what makes this array two dimensional?
int[][] myArray = new int[2][3];`
the two sets of []
What is bounds checking in arrays?
Bounds checking ensures that an index used in an array reference specifies a valid element. The index must be in the range 0 to N-1. If the index is out of bounds, Java throws an ArrayIndexOutOfBoundsException.
What happens if you try to access an array with an invalid index?
If an array index is out of bounds, Java throws an ArrayIndexOutOfBoundsException, which is known as automatic bounds checking.
How do off-by-one errors occur in arrays?
Off-by-one errors occur when an index is used incorrectly, such as using an invalid range (e.g., index <= 100 instead of index < 100) when accessing an array, leading to exceptions.
How is the size of an array represented in Java?
Each array object has a public constant called length
, which stores the size of the array (the number of elements), not the largest index. It can be referenced using arrayName.length
.
What would cause an ArrayIndexOutOfBoundsException in the following code?
```java
int[] codes = new int[100];
System.out.println(codes[count]);
~~~
If the value of count
is 100, accessing codes[count]
would cause an ArrayIndexOutOfBoundsException, because valid indices for the array codes
range from 0 to 99.
how do we loop thru an array?
for (i = 0; i < myArray.length; ++i) {
// Loop body accessing myArray[i]
}
What is an enhanced “for” (foreach) loop in Java?
The enhanced “for” loop enables programmers to traverse an array sequentially without using an index variable. It’s useful for iterating over all elements of a collection.
What are the limitations of using an enhanced “for” loop?
An enhanced “for” loop is only useful for collections, cannot modify the collection while iterating, and does not have an automatic loop counter.
What is the primary advantage of using an enhanced “for” loop?
The enhanced “for” loop simplifies iterating over all elements of a collection in a more elegant manner compared to using a traditional index-based for loop.
What type of variable does an enhanced “for” loop declare?
The enhanced “for” loop declares a new loop variable whose scope is limited to the loop and is assigned each successive element of the array.
Can you modify the collection while using an enhanced “for” loop?
No, you cannot modify the collection while iterating with an enhanced “for” loop.
How does an enhanced “for” loop iterate through an array?
The enhanced “for” loop iterates over elements in the array from the first element to the last, accessing each element in order.
What is an enhanced “for” loop to print all scores in an array?
The enhanced “for” loop iterates through the scores array, printing each score without needing an index variable.
for (int score : scores)
System.out.println(score);
What is an iterator in Java?
An iterator is an object that allows sequential access to the elements of a collection, such as the Scanner
class, which is an iterator in the Java standard library.
How is the Scanner
class useful as an iterator in Java?
The Scanner
class is an iterator that allows sequential reading of input, particularly useful when reading from files.
What is an example of using a Scanner
iterator to process a file in Java?
A Scanner
can be set up to read each line of a file sequentially until the end of the file is encountered, enabling easy processing of file contents.
How can multiple Scanner
objects be used with iterators in Java?
Multiple Scanner
objects can be set up, with one for reading each line of the input and others for processing specific parts of the input, such as individual components of a URL.
Why is the fact that a Scanner
is an iterator helpful when reading input from a file?
It allows for efficient and sequential reading of file contents, processing each part of the input, such as URLs or other data elements, line by line.
How does array assignment work in Java when copying arrays?
When using Array1 = array2;
, it copies the reference, not the content. Both arrays will point to the same memory location, and the old content of array2
becomes garbage.
What are the three ways to copy an array in Java?
1) Using a loop to copy element by element.
2) Using arraycopy()
from the System
class.
3) Using the clone()
method to copy arrays.
How can you use a loop to copy one array to another?
You can loop through the source array and assign each element to the corresponding index in the target array:
```java
for (int i = 0; i < sourceArray.length; i++) {
targetArray[i] = sourceArray[i];
}
~~~
How do you use arraycopy()
to copy an array in Java?
You can use arraycopy()
as follows:
```java
System.arraycopy(sourceArray, srcPos, targetArray, tarPos, length);
~~~
Here, srcPos
and tarPos
are the starting positions, and length
is the number of elements to copy.
How does the clone()
method work to copy arrays in Java?
You can use the clone()
method like this:
```java
int[] targetArray = sourceArray.clone();
~~~
How are arrays passed to methods in Java?
Arrays are passed by reference (pass-by-reference or pass-by-sharing), meaning the reference to the array is passed, not a copy of it.
How do you pass an array to a method in Java?
You can pass an array to a method like this:
```java
public static void printArray(int[] testArray) {
for (int i = 0; i < testArray.length; i++) {
System.out.print(testArray[i] + “ “);
}
}
printArray(new int[] {1, 2, 3, 4});
~~~
How do you return an array from a method in Java?
When returning an array, you return the reference to the array. For example:
```java
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j–) {
result[j] = list[i];
}
return result;
}
~~~
What is a variable-length argument list in Java?
A variable-length argument list allows you to pass a variable number of arguments of the same type to a method, which are treated as an array.
How do you declare a method with a variable-length argument list in Java?
You specify the type followed by ellipsis (...
) in the method declaration.
Example:
```java
public static void printMax(double… numbers)
~~~
What are the restrictions when using variable-length argument lists in Java?
1) Only one variable-length parameter may be specified.
2) The variable-length parameter must be the last parameter.
3) The return type cannot be a variable-length parameter.
How can you use a variable-length argument list in a method in Java?
The variable-length argument list is treated as an array.
Example:
```java
public static void printMax(double… numbers) {
if (numbers.length == 0) {
System.out.println(“No argument passed”);
return;
}
double result = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > result)
result = numbers[i];
}
System.out.println(“The max value is “ + result);
}
~~~
How can command-line arguments be accessed in Java?
Command-line arguments are passed to the main()
method as a String[] args
array. You can determine the number of arguments by accessing args.length
.
how do you do a command line argument?
go into cmd compiler on windows
then change directory
than enter
java ProgramName.java argument1 argument2 argument3…