Data types and Arrays Flashcards

1
Q

What are some characteristics of Primitive data?

A

Aspects of primitive data:

* When working with primitive data types Java stores them directly in memory

* When you copy a primitive variable, only the data is copied, creating a separate variable that holds the same value

* When working with primitives you can use mathematical operators to perform direct calculations like +, -, / and *

* You can use shortcuts to update the value of a primitive value like ++, – or += examples: int, double, boolean, char, byte, short, long, float

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are some characteristics of Object data?

A

Aspects of Object data:

* An object is a method of storing multiple pieces of data and the methods who act on this data under a single data type

* This means within a single object you could have multiple pieces of data including both primitives and other objects

* Because objects have the potential to store large amounts of data Java stores them in memory differently from primitives, storing the location for the data in the actual variable as a “reference”

* When you are working with Objects you can’t use the mathematical operators or shortcuts, instead you need to rely upon the methods provided by the object like “string”.equals(“string”) or scanner.nextInt()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is Null?

A

Each primitive has its own associated “zero value”. This is a value that java uses as a stand in when creating a place in memory for a primitive before you actually give it a value to store.

All object types share a single “zero value”- null

Null means literally “no object”, which is different from an empty object. For example, if you try to use the String’s lengh method on a null string you get an error. However, calling length on an empty string is perfectly valid.

String temp; // if you don’t initialize a String it defaults to null temp.length(); // causes a “Null Pointer Exception”

String empty = “”;

empty.length(); // returns 0;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is an Array?

A

The array is an object that holds multiple pieces of the same type of data. Within the structure each individual piece of data is called an “element” and it has its own address within the array called an “index”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the Syntax to declare an array?

A

The syntax to declare an array is:

dataType[] arrayVariableName = new dataType[numberOfElementsToStore];

The dataType is whatever type of data you want each index to store. An array can store multiple items, but they must all be of the same data type.

For example, you may have a list of ints that represent a single student’s grades across 10 different exams:

int[] studentGrades = new int[10];

The number between the square brackets is the capacity, or how many individual indexes there will be within the array. Keep in mind that once you create the array the capacity cannot be changed. In our above example it will always be 10, the array cannot grow or shrink.

When you first create an array it is filled with “zero values”. Each primitive has an associated zero value, where as the zero value for objects is null. Null literally means “no object”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the Syntax to add an element to an array?

A

Here is the syntax to update the value stored in an index:

arrayName[index] = value;

In our example of student grades, let’s say we want to add in the first three test scores:

studentGrades[0] = 98;

studentGrades[1] = 86;

studentGrades[2] = 90;

This would result in an array with the following values:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the Syntax to add an element to an array and fill it with values in a single statement?

A

dataType[] name = {dataValue1, dataValue2, dataValue3};

The computer can determine the capacity from how many values you provide and places them in the array according to the order you specify.

For example, if we create an array of exam scores like so:

int[] studentGrades = {98, 86, 90};

This would result in an array with the following values:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are some common Array methods?

A

Java also provides an Arrays class that has a series of methods you can use on your own array instances. If you have ever used the Java Math class you will find the syntax very familiar. You start the statement with “Arrays” followed by the method you want to use and pass in the array instance you want to operate on as a parameter.

int a = 10;

double aSq = Math.pow(a, 2);

int[] b = new int[10];

Arrays.toString(b);

These functions do not come included by default, so if you want to use them you have to include the following import statement.

import java.util.Arrays;

Here is a table of some of the most useful array methods:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the Syntax to return the data stored in an array?

A

The data type of an array includes whatever data it stores, so if you want to return an array of ints you would write a method header that looks like this:

public static int[] myMethod(int[] a) {}

If instead you wanted to return an array of doubles your method header would look like this:

public static double[] myMethod(double[] a) {}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Explain how one would trigger the “IndexOutOfBoundsException” error message

A

This exception this means that you have tried to access an index of the array that doesn’t exist. This could mean you are trying to access a negative index, but more likely it means you tried to access an index beyond the capacity of the array. This is a common mistake because the index of the last element is one fewer than the capacity. For example, an array of size 5 only has indexes 0 through 4, so if you tried to access index 5 you would get an IndexOutOfBounds exception.

However, arrays can tell you what their capacity is so you can protect yourself from making this mistake.

arrayName.length // returns the capacity of the array

You can use this to get the value of the last valid element like so:

arrayName[arrayName.length-1] // the last valid index

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the “length” functionality in arrays and what is the Syntax?

A

arrayVariableName.length // returns the capacity of the array

This value is stored as a “field”, or a variable that exists within the entire scope of the object. To access it we call it by the name “length”. This functionality is built into Arrays by Java. You use the length field on the individual instance of an array, so you get the length of that specific array.

For example, if you had multiple different arrays here’s how you would use the length field for each:

int[] a = new int[5];

double[] b = new double[10];

char[] c = new char[20];

int aLength = a.length; // returns 5

int bLength = b.length; //

returns 10 int cLength = c.length; // returns 20

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do arrays and loops work together?

A

As arrays are often used to solve problems at a scale individual primitive variables can’t handle you will likely need to use a loop to move over the array in an efficient way.

For loops and arrays make great partners as you can use the for loop variable to access each individual index in the array like so:

for (int index = 0; index < a.length; index++) {

a[index] = value;

}

Notice that you’ll want to set the bounds of the for loop based on the array’s length, this will help protect you from running off the end of the array and getting an ArrayIndexOutOfBounds exception. You’ll likely want to start the for loop variable at 0 and go until array.length-1, that way the for loop variable will perfectly match the array indexes.

For example, after this code:

int[] a = new int[10];

for (int i = 0; i < a.length; i++) {

a[i] = i;

}

the array “a” will store these values:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the fundamental difference between how Java stores primitive data and object data in memory?

A

Primitives are stored directly in memory, so when you copy a primitive variable the value is copied, leaving the original variable unaffected. This is called value semantics.

Since objects are more complicated Java doesn’t store their data directly in memory with the variable name, instead it creates a special space in memory for the data and then stores the address of that location in the variable. This means that any variable holding an object (like an array) actually stores a reference to the object. Therefore, when you make a copy of an object variable, you copy the reference, which still points at the original data. This is called reference semantics.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do individual arrays set equal to each other affect one another when altered?

A

Let’s say you create an array of ints:

int[] a = new int[5];

The variable “a” stores a reference to where the data for the array is going to be stored. Now let’s say we make a new array variable and set it equal to “a”, what we’re actually copying is the reference to the original data. Meaning if we alter something in our second variable it affects the data stored under a.

int a[] = new int[5]; // [0, 0, 0, 0, 0]

a[0] = 10; // [10, 0, 0, 0, 0]

int b[] = a; // [10, 0, 0, 0, 0]

b[0] = 5; // [5, 0, 0, 0, 0]

System.out.println(“a = “ + Arrays.toString(a)); System.out.println(“b = “ + Arrays.toString(b));

The two printlns at the end of this code would produce the following output:

a = [5, 0, 0, 0, 0]

b = [5, 0, 0, 0, 0]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What happens when you pass an array as a parameter?

A

When you pass an array as a parameter, the reference is passed into the method, which then alters the original array.

public static void main(String[] args) {

int[] a = new int[5];

System.out.println(“before method: “ + Arrays.toString(a)); myMethod(a);

System.out.println(“after method: “ + Arrays.toString(a));

}

public static void myMethod(int[] b) {

b[0] = 5;

}

The output of the above code would be:

before method: [0, 0, 0, 0, 0]

after method: [5, 0, 0, 0, 0]

Which means the original array “a” was changed by the method without having to return the results and save them back at the call site. This is because when you pass an array variable as a parameter it is the reference, not the actual array data that is passed. Arrays can store any type of data you like, so they can store objects. This means that each element then stores a reference to another object somewhere in memory and the rules of reference semantics still apply. That means that if you copy the value stored at this index you are again copying a reference to an object and not the data itself.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is a 2 dimensional array and how would you create one?

A

A 2D array is an array that stores other arrays. When creating a 2D Array you have to specify two capacities, one for the number of arrays to hold and one for how big each of those arrays should be.

dataType[][] name = new dataType[numOfArrays][capacityOfEachArray];

It helps to think of the outer array as the “rows” and the inner capacity as the “columns” creating your grid of data.

int[][] a = new int[3][5];

In this case you have an outer array with a capacity of 3, which stores 3 separate arrays of ints, each of which can store up to 5 ints.

17
Q

How would you access individual elements of a 2D array and how can you initialize a 2d array with values?

A

To access individual elements of a 2D array you need to provide two indices, the row and the column.

name[row][column] = value;

Like 1D arrays you can initialize a 2D array with values.

int[][] a = {{1,2} {3,4} {5,6}};

18
Q

How do 2D arrays and loops work together?

A

If you need 1 loop to examine every element in a 1D array, you need 2 loops to examine each element in a 2D array.

To loop over each element you’ll want to use nested loops. The outer loop will traverse each of the indexes in the outer loop or the “rows”:

int[][] a = new int[numRows][numCols];

for (int row = 0; a.length < a) {

As you can see the overall length of the 2D array will return the number of rows, or the first capacity you pass in during constructor. This is what you want to use as the bounds on your outer loop.

The inner loop will traverse each of the individual inner arrays or the “columns”:

int[][] a = new int[numRows][numCols];

for (int row = 0; row < a.length; row++) {

for (int col = 0; col < a[row].length; col++) {

Here you will note that you actually call length on each array contained within the outer array to make sure you loop over the full length of each inner array.

int[][] a = new int[numRows][numCols];

for (int row = 0; row < a.length; row++) {

for (int col = 0; col < a[row].length; col++) {

a[row][col] = value;

}

}

Then on the inside of your nested loop structure you can use the two different loop variables as the indexes to access each element of the array.

This method will traverse all the elements within the first row, then all the elements within the second row etc…

int[][] a = new int[3][3];

int count = 0;

for (int row = 0; row < a.length; row++) {

for (int col = 0; col < a[row].length; col++) {

a[row][col] = count;

count++;

}

}

In the above code we create a variable “count” that will demonstrate the order in which each element of the 2D array will be accessed, resulting in the following values:

19
Q

What are some limitations of arrays?

A

* are static in size, once you define their capacity they cannot grow or shrink

* store data in a rigid structure, so it is difficult to move the location of any single value

* it is difficult to insert a value into the array and maintain order

* it is difficult to remove a value from an array and reorder elements accordingly

* it is difficult to change the overall order of elements, say to sort them

20
Q

What is an ArrayList?

A

An ArrayList is an implementation of Java’s “List” type. Lists can grow and shrink in size and they allow you to add elements at any index and will automatically reorganize the other elements accordingly.

21
Q

How do you create an ArrayList?

A

ArrayLists are their own data type and then you specify what type of data they store in a parameter during construction.

You do not need to specify a capacity for an ArrayList because the structure will grow and shrink automatically. In fact, the ArrayList has a size variable that it maintains for you, so you’ll always have an easy way to check how many elements are stored in the list.

However, ArrayLists require that you give them an object as a data type. This means that primitive data must first be converted into objects

22
Q

What is a wrapper class?

A

A wrapper class is the way that Java allows you to use primitives when an object is required. They are the simplest possible “wrapper” around a primitive data type to make it into an object.

23
Q

How do you retrieve and store data in an ArrayList? How do you find out how many elements are stored in an ArrayList?

A

Once you have created your ArrayList you’ll likely want to fill it up with data as you have been doing with arrays. Unlike the array, where you directly access each element using the square bracket notation, ArrayLists provide methods to access elements like so:

dataType variable = name.get(index); // equivalent of name[index]

name.set(value, index); // equivalent of name[index] = value;

These methods function exactly as you would expect based on how we used arrays. ArrayLists have 0 based indexes, just like arrays, and when you set a value it will override whatever value was stored there before. To know how many elements are currently stored in an ArrayList you use the .size() method like so:

list.size(); // equivalent to list.length

24
Q

What are some useful ArrayList methods?

A
25
Q

How are ArrayLists and loops used together?

A

Like arrays, it’s likely you’ll want to loop over the data stored in an ArrayList. This code looks very similar to looping over an array:

ArrayList<integer> myList = new ArrayList<integer>();</integer></integer>

int sum = 0;

for (int i = 0; i < myList.size(); i++) {

sum += myList.get(i);

}

This code works great, but because ArrayLists automatically resize you have to keep an eye on how many times you are looping. It makes sense to use the ArrayList’s size() method as the for loop test, but if you are changing how many elements are stored in the list within the loop that variable can cause a lot of problems.

Let’s say as you are looping over your ArrayList you decided to delete an element. Now the index of the last element is one less than when you started the loop- this means if you don’t adjust the loop variable you will run off the end and get an ArrayIndexOutOfBounds exception.

One way to solve this is to store the size of the array as a static variable before your loop, and then to manually adjust the variable whenever you change the size of the list. This way you have direct control over what value is being used in your loop test.

ArrayList<integer> myList = new ArrayList<integer>();</integer></integer>

int staticSize = myList.size();

for (int i = 0; i < staticSize; i++) {

if (myList.get(i) == 0) {

myList.remove(i);

staticSize–;

} else if (myList.get(i) == -1) {

myList.add(-1);

staticSize++;

}

}