Choose units 1 through 5, or units 1 through 10
| Data Structures | |
|
starswhat's a data structure? starsWhat's an Array? starsWhat's an ArrayList? starsWhat's a LinkedList? |
question_answer
A data structure is a feature that supports storing and processing data and maintaining relationships between data. An array in Java is a data structure that stores a fixed number of items the same type or class, either all primitives or all objects. A 2D array is an array of arrays. An ArrayList instance is a data structure that can be added to dynamically. ArrayLists can only store objects, not primitives. A LinkedList instance is a data structure that can be added to dynamically. LinkedLists store objects called nodes. Nodes include a pointer to the next element (single linked list) or both a pointer to the next element and a pointer to the previous element (double linked list). |
| Arrays | |
|
starsIs an array an instance? starsHow is an array declared? starsHow are array elements accessed? starsIs it easy to sequence through an array? starsWhat key algorithms are used with arrays |
question_answer
An array is an object itself and has to be both declared and instantiated to make space for the number of items. An array in Java is of fixed size. Array elements are accessed using square brackets and an index, or subscript,
You can use loops to traverse an array, for loop, enhanced for loop, while loop. There are standard array algorithms, for searching, sorting, finding max/min/average. Some useful algorithms:
The number of elements in an array is given by
arrayName.length; This is the length property, be careful not to include the parentheses, (). You can declare an array of primitive types, like ints, In a situation where the size of the array and variables of the array are already known, array literals (initializer list) can be used. Here is an example. int[] codes = new int[]{ 101,222,373,444,555};Note, the length determines the length of the new array.You can drop the 'new int[]'' part in recent versions of Java. Given array of ints, players for (int index = 0; index < arr.length; index++) { for (int index = 0; index < team.length; index++) {
Given array of ints, players for (int item : arr) { for (SoccerPlayer player : team) { Given array of ints, players, int[] arr = {1,2,3,4,5,6,7,8,9}; int index = 0; while (index < arr.length) { int index = 0; while (index < team.length) { |
| ArrayLists | |
|
stars How are ArrayLists different from arrays?
starsIs an ArrayList an instance? starsHow is an ArrayList object declared? starsWhat methods are used for ArrayLists? starsHow are elements accessed? starsIs it easy to sequence through an ArrayList instance? starsWhat key algorithms are used with ArrayLists |
question_answer
ArrayList instances dynamically grow (you can add more elements) and shrink (you can remove elements). So, ArrayLists are flexible and are not of fixed size, like Arrays. An ArrayList instance has a core Array - whenever a new item is added or removed, a new array is created behind the scenes.
The ArrayList class is imported into a Java application. The class, ArrayList, is newed up/instantiated to create an ArrayList object. Methods commonly used are get, set, remove, add. Elements are accessed by using the get method and a valid index. for, while, enhanced for loops (and more) are used to traverse or sequence through an ArrayList instance. Standard algorithms are used to process elements in an ArrayList instance. So, what's the difference between Array and ArrayList? |
| LinkedLists | |
|
stars How is LinkedList different from ArrayList?
starsIs a LinkedList an instance? starsHow is a LinkedList declared? starsWhat methods are used for LinkedLists? starsHow are elements accessed? starsIs it easy to sequence through a LinkedList ? starsWhy would you use a LinkedList? |
question_answer
Linked Lists dynamically grow (you can add more elements) and shrink (you can remove elements), just like ArrayLists. LinkedLists differ from ArrayLists in that they are not based on arrays. They store data inside nodes, which can be set up in 2 ways : as a single linked list with just a pointer to the next node,
The LinkedList class is imported into a Java application. The class, LinkedList, is newed up/instantiated to create a reference to the first node in the list. LinkedList methods commonly used mirror ArrayList, and include some targeted methods for increased efficiency. Elements are accessed by using the get method and a valid index. for, while, enhanced for loops (and more) are used to traverse or sequence through a LinkedList. So, what's the difference between ArrayList and LinkedList? Why use one instead of the other? |
| 2D Arrays | |
|
starsHow is a 2D Array object declared? starsHow are elements accessed? starsIs it easy to sequence through a 2D Array instance? starsCan 2D arrays have out of bounds errors? starsWhat's Row Major Order? starsWhat's Column Major Order? |
question_answer
A 2D array is an array of arrays, and has rows and columns similar to a matrix. Here, the number of elements in a row, is the same for each row.
-------------------
| 😀 | 😀 | 😀 | ------------------- | 😀 | 😀 | 😀 | ------------------- | 😀 | 😀 | 😀 | ------------------- 2D arrays have to be newed up before being used, specifying the exact number of rows and columns. A 2D Array is declared using Java syntax, with double brackets, [][], and a specification of the type/class being stored.
SoccerPlayer[][] teams = new SoccerPlayer[3][3]; // 3 rows, 3 columns2D Array numbers holds 3 rows and 3 columns of primitives, 2D array players holds instances of class SoccerPlayer. int[][] numbers = new int[3][3]; SoccerPlayer[][] players = new SoccerPlayer[3][3]; 2D Array instances can be declared and initialized using Object Initialization Syntax, with an initializer list. Important! Remember to new up the 2D array, or use an initializer list before accessing an element! 2D arrays are accessed using row and column. int[][] numbers = { numbers[1][2] is in red, this element is on row 1 and column 2. Valid index values for rows in a 2D array are from 0 to the length of the array, less one. Valid index values for columns in a 2D array are from 0 to the length of a row, less one. See best practices for getting the last element in the 2D array. Row-Major Order and Column-Major Order describe how the 2D array is read, either across rows or down columns. 2D arrays are traversed using nested loops, for, while, enhanced for, using Row major Order or Column Major Order. |
Wrapper Classes 'wrap' primitive as objects.
It is necessary to import the ArrayList class, this is the most economical way to include just ArrayList,
import java.util.ArrayList;
If this import is not included, the ArrayList class is not recognized.
Given class, Employee,
ArrayList<Employee> employees = new ArrayList<Employee>();
A list of numbers,
ArrayList<Integer> numbers = new ArrayList<Integer>();
A list of objects,
ArrayList objectsAll = new ArrayList();
The get method accesses elements of the ArrayList instance. A numeric index is used, between 0 and the last valid index.
Given a list of Employee instances, where Employee is a class, the element at index 2 is accessed like this,Employee employee = employees.get(2);
If the index is outside the bounds of the list, < 0 or, > employees.size()-1, an out of bounds error results
It is best to use the .size() method to get the last viable index,
Employee employee1 = employees.get(employeeArrayList.size()-1);
A list of numbers,
ArrayList<Integer> numbers = new ArrayList<Integer>();
with Integer instances added.
for (int index = 0; index < numbers.size(); index++) {
System.out.println(numbers.get(index));
}
A list of objects -
Given class, Employee, with attribute name and accessor getName(),
,ArrayList<Employee> employees = new ArrayList<Employee>();
Instances e1, e2, .... are added to ArrayList instance, employees
for (int index = 0; index < employees.size(); index++) {
System.out.println(employees.get(index).getName());
}
Given a list of numbers, objects
ArrayList<Integer> numbers = new ArrayList<Integer>();
with Integer instances added.
int index = 0;
while (index < numbers.size()) {
System.out.println(numbers.get(index));
index++;
}
Given class, Employee, with attribute name and accessor getname(),
,ArrayList<Employee> employees = new ArrayList<Employee>();
Instances e1, e2, .... are added to ArrayList instance, employees
int index = 0;
while (index < employees.size()) {
System.out.println(employees.get(index).getName());
index++;
}
Given a list of numbers, objects
ArrayList<Integer> numbers = new ArrayList<Integer>();
with Integer instances added.
for (Integer num : numbers) {
System.out.println(num.get(index));
}
Given class, Employee, with attribute name and accessor getName(),
,ArrayList<Employee> employees = new ArrayList<Employee>();
Instances e1, e2, .... are added to ArrayList instance, employees
for (Employee employee : employees) {
System.out.println(employee.getName());
}
Some useful algorithms are:
Single Linked List
.. consider a series of objects, nodes, with a reference to the previous node and a reference to the next node.
Double Linked List .. consider a series of objects, nodes, with a reference to the previous node and a reference to the next node.
It is necessary to import the LinkedList class, this is the most economical way to include just LinkedList,
import java.util.LinkedList;
If this import is not included, the LinkedList class is not recognized.
import java.util.LinkedList;
LinkedList<ObjectType>=new LinkedList<>;
ACCESS content
A list of numbers,
ArrayList<Integer> numbers = new ArrayList<Integer>();
with Integer instances added.
for (int index = 0; index < numbers.size(); index++) {
System.out.println(numbers.get(index));
}
A list of objects -
Given class, Employee, with attribute name and accessor getname(),
,ArrayList<Employee> employees = new ArrayList<Employee>();
Instances e1, e2, .... are added to ArrayList instance, employees
for (int index = 0; index < employees.size(); index++) {
System.out.println(employees.get(index).getName());
}
Given a list of numbers, objects
ArrayList<Integer> numbers = new ArrayList<Integer>();
with Integer instances added.
int index = 0;
while (index < numbers.size()) {
System.out.println(numbers.get(index));
index++;
}
Given class, Employee, with attribute name and accessor getname(),
,ArrayList<Employee> employees = new ArrayList<Employee>();
Instances e1, e2, .... are added to ArrayList instance, employees
int index = 0;
while (index < employees.size()) {
System.out.println(employees.get(index).getName());
index++;
}
Given a list of numbers, objects
ArrayList<Integer> numbers = new ArrayList<Integer>();
with Integer instances added.
for (Integer num : numbers) {
System.out.println(num.get(index));
}
Given class, Employee, with attribute name and accessor getname(),
,ArrayList<Employee> employees = new ArrayList<Employee>();
Instances e1, e2, .... are added to ArrayList instance, employees
for (Employee employee : employees) {
System.out.println(employee.getName());
}
LinkedList and ArrayList are different implementations of the List interface (contract that states what methods a class should implement). The LinkedList class uses a doubly-linked list of nodes - each node has a next pointer to the next node, and a previous pointer to the previous node, with the head the first node and the tail the last node. The ArrayList class implements the List interface by dynamically re-creating a core array.
Linked lists are preferable over array lists when:
LinkedLists use get, set, remove, add .. just like ArrayLists. More methds are included for targeted efficiency:
An initializer list can be used to new up and populate the content of a 2D array. Below, each 2D array contains 3 rows and 3 columns. The rows are inside the { and }.
When accessing the 2D array, the row always comes first, and as always, the rows are columns start at index 0.
int[][] numbers = {{1,2,3}, {4,5,6}, {7,8,9}};
numbers[1][2] is at row 1, column 2 - 6.
A 2D array can store instances of a class, like SoccerPlayer,
team[][] teams = {{player1,player2,player3}, {player4,player5,player6}, {player7,player8,player9}};
teams[2][1] is at row 2 and column1, player8.
int[][] nums = {{1,2,3}, {4,5,6}, {7,8,9}};
The last element is on the last row and the last column.
Get the last row by using the length property of Array, as a 2D array is an array of arrays. The last row index is nums.length-1.
Get the last column also by using the length property, this time, the length of any row.
The last column is at nums[0].length-1.
The last value? nums[nums.length-1][nums[0].length-1]
If an index is used for either row or column that is less than 0 or greater than the last valid index, an out of bounds error will result.
int[][] numbers = {{1,2,3}, {4,5,6}, {7,8,9}};
4 is the fourth value. The values are printed starting with the first row, and traversing that first row, each time printing/processing a value.
--------------------------
| 1 → | 2 → | 3 → | 4 → |
--------------------------
| 5 → | 6 → | 7 → | 8 → |
--------------------------
| 4 → | 3 → | 2 → | 1 → |
--------------------------
int[][] numbers = {{1,2,3}, {4,5,6}, {7,8,9}};
2 is printed as the fourth value. The values are printed starting with the first column, and traversing down that first column, each time printing a value.
--------------------------
| 1 ↴ | 2 ↴ | 3 ↴ | 4 ↴ |
--------------------------
| 5 ↴ | 6 ↴ | 7 ↴ | 8 ↴ |
--------------------------
| 4 ↴ | 3 ↴ | 2 ↴ | 1 ↴ |
--------------------------
int[][] nums = {{1,2,3}, {4,5,6}, {7,8,9}};
Row Major Order
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[0].length; j++) {
System.out.print(nums[j][i] + " ");
}
System.out.println();
}
Column Major Order
for (int j = 0; j < nums[0].length; j++) {
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i][j] + " ");
}
System.out.println();
}
int[][] nums = {{1,2,3}, {4,5,6}, {7,8,9}};
Row Major Order
int i = 0;
int j;
while (i < nums.length) {
j = 0;
while (j < nums[0].length) {
System.out.print(nums[i][j] + " ");
j++;
}
System.out.println();
i++;
}
Column Major Order
int i;
int j = 0;
while (j < nums[0].length) {
i = 0;
while (i < nums.length) {
System.out.print(nums[i][j] + " ");
i++;
}
System.out.println();
j++;
}
int[][] nums = {{1,2,3}, {4,5,6}, {7,8,9}};
Row Major Order
int i = 0;
int j = 0;
while (i < nums.length) {
j = 0;
while (j < nums[0].length; j++) {
System.out.print(nums[i][j] + " ");
}
System.out.println();
}
Column Major Order
int i = 0;
int j = 0;
while (j < nums[0].length) {
while (i < nums.length) {
System.out.print(nums[i][j] + " ");
j++; }
System.out.println();
i++;
}
int[][] nums = {{1,2,3}, {4,5,6}, {7,8,9}};
Row Major Order
for (int[] numRow : nums) {
for (int j : numRow) {
System.out.print(j + " ");
}
System.out.println();
}
| Primitive data types, reference types | |||||||||
| starsHow do primitive data types and reference types differ? | question_answer Primitives represent values, of known storage requirement. A reference is the beginning memory address of data stored in computer memory. | ||||||||
| Know the bit requirements for primitive data types - boolean, int, double | |||||||||
| starsArrange the data types in order of least amount of storage: double, boolean, int | question_answerbooleans occupy a byte (8 bits) or less, ints occupy 32 bits and doubles take up 64 bits | ||||||||
| Be aware of the Wrapper classes and how to use them | |||||||||
|
stars Associate the primitive with the correct wrapper class. starsDescribe auto-boxing and un-boxing as these terms relate to primitives and references. |
question_answer
Integer num1 = new Integer(7);
num1 = 3; // Auto-boxing, Java 'boxes' the int int num2 = num1; // Un-boxing, Java gets value of Integer instance |
||||||||
| Casting an int to a double | |
| stars Casting an int to a double is a particular type of conversion - what type is it? stars What are the implications of casting a double to an int? |
question_answerCasting from an int to a double is a widening conversion, because int can store less than double. int num1 = 7; double num1 = (double)num1; // Widening conversion A narrowing conversion occurs when a double is cast to an int, as this means that some information might be lost. Any fractional part will be truncated. double num2 = 7.777; int num3 = (int)num2; Now, the value of num3 is 7. |
| Assigning a value to a String instance | |
|
stars How are String instances initialized? |
question_answer String instances are objects, their value is a memory address or reference. The content of that memory address is the content of the string instance. You can new up (instantiate) a String instance or you can assign a string literal.
String firstName = "Jane"; |
| Comparing Strings | |
|
stars What is the correct way to compare strings?
|
question_answer Strings are objects, their value is a memory address. The content of that memory address is the content of the string instance. Always use the equals method to compare strings.
String name1 = "Jane"; |
| Immutability implications | |
|
stars Can strings be changed? stars What happens when a string is passed into a method and then modified? |
question_answer Strings are immutable, they never change after they have been initialized. Instead, a new string instance is created.
String name = "Jane"; // this might be at memory address 0x24B76A73
Given method,
|
| Class | |
| stars What is a class? stars What are class analogies? |
question_answerA class is a software template for creating a software model, called an object. Think of an achitectural blueprint as a class, and the house built from this, as an object. |
| Object Oriented Programming | |
| stars How does a Class relate to OOP? stars What is OOP? |
question_answer
Object Oriented Programming (OOP) is a software engineering paradigm that uses data models called objects, as the basis of the application. Objects are created from templates called classes. The 4 tenets of object oriented programming are
|
| The structure of a class | |
|
starsHow is a class declared? stars What is an attribute? stars What's a method? |
question_answer
A class is a software template for creating a data model called an object, or for acting as a repository for code that can be called by using the class name. A class is typically declared public so as to be visible to client code.A class defines properties called attributes. These properties are called instance variables if they apply to the instance created on instantiation. They are called class variables if they apply to the class. A class defines methods - these are blocks of code given a label and a return type/class, as well as an optional list of data passed into the code block - parameters. A method describes what the object can do, and can apply to an instance (instance method) or class (class method). Constructors, accessors and mutators are special methods. public class SoccerPlayer { <Attributes> <Constructors> <Accessors & Mutators> <other methods> } |
| Attributes and how they are accessed |
stars Are attributes protected? stars How are attribute values seen? |
question_answer In this example, the class is SoccerPlayer, and the attributes are shown.
The attributes (also called properties) defined are name, position and club. These are declared private by convention. This is so that they can only be accessed directly from within the object itself. From outside, calling code uses getters and setters (accessors and mutators).
An instance method is called on the object or instance, and an instance variable's value is tied to the specific object. Important! An instance has to exist before an instance method can be called.
SoccerPlayer player = new SoccerPlayer();
Variable, player, is an instance of SoccerPlayer. Attribute, name, has been set to "Harry Kane". |
| Static attributes and methods |
stars What is a static variable? stars What is a static method? |
A class, or static, method is called on the class, and a static variable's value is retained because it is associated with a class. (using the class name).
The keyword, static, is used to indicate that the attribute or the method is bound to the class. public static int numberOfPlayers; // Static Method public static void playerRequirements() { System.out.println("Players must be 18 years or older."); } This method can be called using just the class name, The static variable can be accessed and incremented each time a constructor is called, and the number of players created can be tallied.
The class is instantiated or newed up, into an object or istance. Constructors are special methods responsible for creating an instance from a class. |
| Constructors | |
|
starsWhat's a constructor? stars Can constructors be overloaded? stars What happens if no constructor is declared? |
question_answer A constructor is a special method that is instrumental in instantiating (newing up) an instance from a class. If no constructor is declared, then Java allows for
the defualt or empty constructor to be used.
SoccerPlayer player = new SoccerPlayer(); Once a constructor is declared, then the empty constructor must be added to the constructor declarations. public SoccerPlayer() { // empty constructor } // Parameterized constructor public SoccerPlayer(String name, double age, String position, String club) { this.name = name; this.age = age; this.position = position; this.club = club; } |
| Creating Objects | |
| starsHow are objects created? starsWhat is the role of the constructor? |
question_answer Objects (also called instances) are newed up (instantiated) from a class definition, like SoccerPlayer, below. public class SoccerPlayer { ..... } SoccerPlayer player = new SoccerPlayer(); SoccerPlayer player2 = new SoccerPlayer("Harry Kane", 27, "Striker", "Tottenham Hotspurs"); The constructor is involved in this process, which creates space in memory for storing the new object. |
| Comparing Objects | |
| starsHow can you tell if objects are the same?
starsWhat's an alias? starsWhen are objects aliases of each other? |
question_answer Objects are references to locations in computer memory, that contain information.
SoccerPlayer player = new SoccerPlayer(); player.setName("Harry Kane"); player.setAge(27); player.setPosition("Striker"); player.setClub("Tottenham Hotspurs"); // Using a different constructor, SoccerPlayer player2 = new SoccerPlayer("Harry Kane", 27, "Striker", "Tottenham Hotspurs"); It looks like both players have the same information, but they do point to different memory locations. So, a comparison with the equality operaor will yield false. In order to compare the content, an equals method is needed.
if (player == player2) |
| Inheritance | |
| stars What is inheritance? stars How is inheritance useful? stars Can a class inherit from more than one other? stars Is inheritance part of OOP? |
question_answer
A class is a software template for creating a software model, called an object. Inheritance allows the reuse of the code from a class, called the parent class or superclass, as the basis for another class, called the child class or subclass. Reuse of code and logic already developed in a parent class results in less lines of code and easier maintenance. In Java, a class can only inherit from one other class, we say it doesn't support multiple inheritance. Inheritance is one of the 4 tenets of Object Oriented Programming! |
| The Mechanics of Inheritance | |
| stars How is inheritance done in Java? stars What is overriding? |
question_answer
A class is designated as a subclass of another class, with the keyword, . A subclass can rewrite a method with the same signature as in the superclass. When this method is called on an instance of the subclass, the method belonging to the subclass is called. The superclass' method is overridden by the method in the subclass. |
| Polymorphism | |
|
starsWhat's Polymorphism? starsWhat's the link between inheritance and polymorphism? |
question_answer
Polymorphism is defined as the ability of different objects (related via inheritance) to respond to the same request in different ways. A subclass can override a method defined in the superclass, and thus respond in a different way to an instance of the superclass. |
| Class Cast Exceptions |
stars What's a Class cast Exception? |
question_answer A class cast exception occurs when an object is instantiated using a subclass, but cast to the parent class. |
Class, MidfieldSoccerPlayer, extends class SoccerPlayer. MidfieldSoccerPlayer inherits all of the attributes and methods of the parent class.
public MidfieldSoccerPlayer extends SoccerPlayer {
private double depthPerception;
}
Class, MidfieldSoccerPlayer, overrides the trainingRequirement() method defined in SoccerPlayer.
public class SoccerPlayer {
private String name;
//
public String trainingRequirements() {
// Generic requirements print
}
}
}
public MidfieldSoccerPlayer extends SoccerPlayer {
private double depthPerception;
public String trainingRequirements() {
// Specialized requirements print
}
}
Class, MidfieldSoccerPlayer, overrides the trainingRequirement() method defined in SoccerPlayer.
public class SoccerPlayer {
private String name;
//
public String trainingRequirements() {
// Generic requirements print
}
}
}
public MidfieldSoccerPlayer extends SoccerPlayer {
private double depthPerception;
public String trainingRequirements() {
// Specialized requirements print
}
}
What happens as a result of the code?
(a) SoccerPlayer player1 = new SoccerPlayer();
player1.trainingRequirements();
(b) SoccerPlayer player2 = new MidfieldSoccerPlayer();
In (a) the generic requirements are printed. In (b) the specialized requirements are printed because the instance is recognized as an instance of MidfieldSoccerPlayer at runtime.
Class, MidfieldSoccerPlayer, is a subclass of class, SoccerPlayer.
public MidfieldSoccerPlayer extends SoccerPlayer {
// Attributes, Methods }
The code causes a class cast exception, as MidfieldSoccerPlayer instances are more specialized than SoccerPlayer instances.
MidfieldSoccerPlayer player = (MidfieldSoccerPlayer)(new SoccerPlayer());
This code works fine, but may require a future cast to MidfieldSoccerPlayer!
SoccerPlayer player = new MidfieldSoccerPlayer();
| Structure of a method | |
|
stars What's a method? stars What's a method header? stars What does 'return' mean? stars Do methods always return stuff? |
question_answer
Methods are blocks of code, given a name, and an optional set of values to be passed in to the method from the calling code. Methods also specify what, if any, information is to be passed back from the method to the calling code. This comprises the method header. Methods are associated with a class or an object and are called in this context, as opposed to a free standing function.
<(optional)accessibility modifier> <return type> <method name> (<parameter list >(optional))
If return type is int, then an int should be returned to the calling code. If the return type is specified as void, then no return value is expected. public double distanceToTopOfGoal(double distanceFromGoal) {double distance = Math.sqrt(Math.pow(distanceFromGoal, 2) + Math.pow(GOAL_HEIGHT_IN_FT - 0.3, 2)); return distance; } Above, the method is called distanceToTopOfGoal, it returns a double value to the calling code, and is accessible from client code because of the public accessibility modifier. A value, distanceFromGoal, which is of type double, is passed into the method. |
| Parameters | |
|
stars What are formal parameters? stars What are actual parameters? stars Does the order of the parameters matter? |
question_answer In the method definition, formal parameters are the values that are specified as the values expected to be passed in, in the call. The method below, isProlificScorer,
is defined in a class called SoccerClub, and is an instance method.
public String isProlificScorer(int goals, String playerName) { if (goals > MAX) { return playerName + " is a prolific scorer!"; else return playername + " should keep practicing!"; } goals and playername are formal parameters. In the call, actual parameters give values to the formal parameters. SoccerClub club = new SoccerClub(); club.isProlificScorer(27, "Harry Kane"); In the method, goals has a value of 27, and playerName is set to "Harry Kane".
The parameters are positional, which means that calling the method with, ... would result in an error! |
| Passing variables to methods | |
|
starsAre variables changed by methods? stars What does 'pass by value' mean? stars What does 'pass by object reference' mean? |
question_answer Java is 'pass by value'. This means that only the value of variable is passed to a method, so the variable's value remains unchanged in the calling code. However, Java
is also 'pass by object reference'. This means that an object's reference (memory address) is passed to a method, and that the content of the object can be accessed and modified because of this.
SoccerPlayer player = new SoccerPlayer();
Given method, In the runner code, changer(player, clubLeaguePosition);
|
| static method, instance method | |
|
stars What's a static method? stars What's an instance method? |
question_answer Static methods are also known as class methods because they are bound to the class, not the object. Static methods are declared with key word, static.
public class SoccerClub { Instance methods need an instance of the class!
public class SoccerClub { |
| What is Boolean logic? | |||||||
| starsWhat is Boolean Logic? starsIs there a boolean data type? |
question_answer
Boolean logic is a branch of mathematics devleoped by mathematician George Boole, in the 1800s. Primitive data type, boolean, and wrapper class, Boolean, represent boolean values of true or false only.
|
||||||
| Basic Boolean operators | |||||||
| starsWhat Boolean operators are important? |
question_answer There are more Boolean operators, but the 3 basic Boolean operators are AND, OR and NOT. The other operators are composed of these three.
|
||||||
| Boolean expressions | |||||||
|
starsWhat are simple Boolean expressions?
starsWhat are compound Boolean expressions? |
question_answer Boolean expressions evaluate to either true or false. Compound Boolean expressions are Boolean expressions that are joined by Boolean operators, and also evaluate
to true or false.
int val1 = 3; |
||||||
| Truth tables | |||||||
|
starsWhat is a truth table? starsHow do truth tables help evaluate Boolean expressions? |
question_answer
Truth tables show the result of evaluating a Boolean expression with 2 (or more) operands. Here are truth tables for the three basic boolean operations - AND, OR, NOT.
Given Boolean variables isA and isB, |
||||||
| Logic gates | |||||||
|
starsWhat digital logic gates represent Boolean operations?
|
question_answer
Logic gates represent Boolean operations in circuit diagrams. AND
OR
NOT
These gates can be viewed in the same way as truth tables, with operands and an output. |
||||||
| Simplifying Boolean exressions | |||||||
| starsCan Boolean expressions be short-circuited?
starsWhat is De Morgan's Law? starsHow is De Morgan's Law useful? |
question_answer
Compound Boolean expression may not have to be fully evaluated, they may be
short-circuited. If the first expression in an AND operation is false, then stop right there - the expression is false. If the first expression in an OR is true, the same principal applies, as the expression
must be true.
De Morgan's law provides a strategy to simplify Boolean expressions. Given Boolean variables a and b, comprising Boolean expressions, !(a && b) <=> !a || !b!(a || b) <=> !a && !bDe Morgan's law can be applied to more complex expressions. This helps to simplify the evaluation and determine the outcome. ! ( ( a || !b) && (a && b) ) Apply the negate to the sub-expressions, and switch the && to an || !( a || !b ) || !(a && b ) Now distribute the negate across each of the sub-expressions (!a && b) || (!a || b) This is true if b is true. |
||||||
| If statement | |
|
stars What are If statements used for? |
question_answer
If statements, conditionals support making decisions based on the value of a Boolean expression, or condition. |
| One way selection statment | |
| stars Why would a one way selection statement be used? |
question_answer
A one way selection statement is used when action should be taken based on a Boolean expression's truth, and no action otherwise. int goals = 4; int goalScoringThreshold = 15; if (goals > goalScoringThreshold) { System.out.println("Goal scoring range exceeds expectations!"); } |
| Two way selection statment | |
| stars Why would a two way selection statement be used? |
question_answer
A two way selection statement is used when action should be taken based on a Boolean expression's truth, and another action should be taken based on the expression being false. int goals = 4; int goalScoringThreshold = 15; if (goals > goalScoringThreshold) { System.out.println("Goal scoring range exceeds expectations!"); } else { System.out.println("Player may need more training!"); } |
| Multi way selection statment | |
| stars Why would a multi-way way selection statement be used? stars Why is it better to use if/else if../else instead of a sequence of if statements? |
question_answer
A multi way selection statement is used when different actions should be taken based on a Boolean expression's truth, such as the value of a discrete quantity, like goals scored by a soccer player this season. int goals = 4;int goalScoringThreshold = 15; if (goals > goalScoringThreshold) { System.out.println("Scoring range exceeds expectations!"); } else if (goals > 10) { System.out.println("Scoring within range!"); } else if (goals > 5) { System.out.println("Scoring acceptable, outside range!"); } else { System.out.println("Scoring unacceptable, training!"); } |
| Sequence of ifs | |
|
stars Why is it better to use if/else if../else instead of a sequence of if statements? |
question_answer
When one of the conditions is true, the code associated with the condition is executed. After a branch executes, control flows away from the if statement. Where the value of a variable has not changed, it is inefficient to use a sequence of singleton if statements. This is because a condition that is true has already been found. There is no point in evaluating all the other possibities. int goals = 4; int goalScoringThreshold = 15; if (goals > goalScoringThreshold) { System.out.println("Goal scoring exceeds expectations!"); } if ((goals > 10) && (goals <= 15)) System.out.println("Goal scoring within range!"); } if (goals < 5) { System.out.println("Goal scoring unacceptable, training!"); } |
| Intent of loops | |||||||
|
stars What's the purpose of a loop? stars What does iteration mean? stars What terms are associated with a loop? stars When are loops required? |
question_answer
Loops are structures that support repetitive execution of a sequence of commands, like adding compound interest to a bank account, or printing the times tables. Loops are useful when a set of commands should be repeated, either infinitely or a set number of times. A common term used to represent looping is iteration, as in, a loop might iterate or repeat x amount of times. The body of the loop describes code that is executed each time through the loop. A special variable called a loop variable, sentry variable or control variable guards access to the loop by virtue of being used in a loop condition. The loop condition determines access to and continued execution of the loop - when the loop condition is no longer true, the loop exits. while (condition is true) statements in body of loop |
||||||
| While loop | |||||||
|
stars How is a while loop structured? stars When does a while loop become an infinite loop? stars How many times does a while loop execute? |
question_answer A while loop is a type of loop characterized by key word,
while , a loop condition and statements in the body of the loop, executed each time the loop iterates.
int itemNumber = 1; while (itemNumber < MAX_ITEMS) { System.out.println("Processing item number " + itemNumber); processItem(itemNumber); itemNumber++; }
The while loop executes until the loop condition is false. If MAX_ITEMS is 10, then the loop executes for values of itemNumber of 1,2,3,4,5,6,7,8,9. This is 9 times in total. If the loop variable, itemNumber, is not incremented in the body of the loop, then the loop will be an infinite loop because the loop condition, which is that itemNumber be less than MAX_ITEMS, is always true. |
||||||
| For loop | |||||||
|
stars How is a for loop structured? stars When does a for loop become an infinite loop? stars How many times does a for loop execute? stars Is it necessary to include all parts of the for loop? |
question_answer
The for loop is characterized by key word, for, an optional initialization part, a loop condition, and an optional loop statement.
The initialization part can be done prior to the for loop, and the loop statement can be left out. The loop could be written
The for loop runs as long as the loop condition is true. If MAX_ITEMS has a value of 10, the loop iterates through values for itemNumber of 1,2,3,4,5,6,7,8,9. This is a total of 9 iterations. |
||||||
| Nested Conditionals | |
|
stars What are nested conditionals? stars What's the purpose of a nested conditional? stars Can a nested conditional be represented as a compound condition? stars When are nested conditionals required? |
question_answer
Nested conditionals are conditionals inside other conditionals. Nested ifs, or nested conditionals, represent a compound condition, like, ascertaining first if a soccer player is a goal keeper, and then figuring out if the player should be on the junior team or the senior team, based on age. Given SoccerPlayer object, player, if (player.isGoalKeeper()){ if (player.getAge() >= 21) { System.out.println("Put player " + player.getName()) + " on the senior team as a goal keeper"); } else { System.out.println("Put player " + player.getName()) + " on the junior team as a goal keeper"); } } else { System.out.println("Player is not a goal keeper"); } This could also be done by using a compound condition,
Nested conditions can be used in staggerred evaluations, like the one presented above. Typically, a compound condition or a series of compound conditions can be used in the place of a nested if. |
| Nested loop | |
|
stars What is a nested loop? stars When is a nested loop required? |
question_answer
A nested loop is a loop within another loop. A nested loop is required for processing a set of data in an inner loop for each value in an outer loop. An example would be processing blood work in a hospital for each patient in a ward full of patients with a common ailment and all patients requiring a set number of tests. int patientNumber = 1; while (patientNumber < MAX_PATIENTS) { int testNumber = 1; while (testNumber <= TESTS_REQUIRED_COUNT) processTest(patientNumber, testNumber); testNumber++; } } A nested while loop can be mirrored with a nested for loop, and for loops can exist inside while loops and vice versa. for (patientNumber = 1; patientNumber < MAX_PATIENTS; patientNumber++) { for (testNumber = 1; testNumber <= TESTS_REQUIRED_COUNT; testNumber++) processTest(patientNumber, testNumber); testNumber++; } } |
| Nested loop execution | |
|
stars How many times does a nested loop run?
stars Can a nested loop be an infinite loop? |
question_answer
A nested loop runs for all sentry variable values in the outer loop, and for each value of the outer loop's sentry variable, for all values of the inner loop's sentry variable. The times tables is a good way to see this.
This produces, 1 x 1 = 1to 12 x 12 = 144 For each of the 12 values, 1,2,3,4,5,6,7,8,9,10,11,12, in the outer loop, the inner loop also runs 12 times. The body of the inner loop is executed 12 by 12 times in total, which is 144. A nested loop can easily become an infinite loop if either the outer loop condition does not ever become false, or if the inner loop condition does not ever become false. |
| Swapping primitive variable values | |
| starsHow do primitive type variable assignments cause values to change? starsDoes the order of assignments matter? |
question_answer
Assignments between variables cause changes in the current values of the variables.
The order of the assignments is important for the final result. |
| Swapping references | |
|
starsWhat happens when references are reassigned?
starsAre aliases created when references are reassigned? starsHow do object attributes change after objects are reassigned? starsDoes the order of assignments matter? |
question_answer
References are memory addresses, and we see them in using objects. When one 'object' is assigned to another, references are changed and objects point to different locations in memory.
Assume class SoccerPlayer, with a constructor that takes the player name as a parameter. SoccerPlayer player1 = new SoccerPlayer("Harry Kane"); SoccerPlayer player2 = new SoccerPlayer("Jamie Vardy"); SoccerPlayer player3 = new SoccerPlayer("Moussa Sissoko"); player1 = player2; player2 = player3; player3 = player1; Above, player1, player2 and player3 have been newed up as instances of class SoccerPlayer.
The content of name parameter is transferred to instance variable, name, and getter getName() has been defined. After the first assignment, player1 = player2, player1 points to the memory location that player2's information starts at. At this point, player1 and player2 are aliases of each other. player1.getname() andplayer2.getName() both return "Moussa Sissoko"
After the second assignment, player2 = player3, the reference for player2 is set to point at the starting memory location for player3's data.
Now, player2.getname() returns "Jamie Vardy", and player3.getName() also returns "Jamie Vardy". Finally, after the third assignment, player3 = player1, player3 now shares a reference with player1, player1 and player3 end up as aliases of each other.
After the assignments, player1's name is "Jamie Vardy", player2's name is "Moussa Sissoko" and player3's name is "Jamie Vardy". The order of these assignments determines the end result. |
| Recursion | |
| stars What is recursion? stars Why is recursion useful? stars Any alternative to recursion? |
question_answer
Recursion is seen when a method (or a function) calls itself, like a recursive solution to Factorial. It is a way to break a problem down into smaller parts of the same problem ... There are times when a recursive algorithm works well, and times when recursion is less efficient. |
| The Mechanics of Recursion | |
| stars What's a base case? stars What's a recursive case? |
question_answer
The base case is the last issue to be handled by the recursive solution. This is the condition that exits the recursive process. If it is not created, the recursive solution will recurse infinitely. The recursive case is the part of the solution that calls the method or function recursively, typically using parameters with different values. Recursive solutions must have a base and recursive case. |
| Loops Versus Recursion | |
|
stars Any alternative to recursion? |
question_answer
The use of loops can provide a solution to a coding issue, anything that can be coded as a recursive solution can also be coded using loops. |
| Recursion & The Stack |
stars What part of memory does recursion use? stars Is recursion efficient? stars What's a Stack Overflow Exception? |
question_answer Recursion works on an area of memory called the stack(popup). Each time a recursive call is made, data is added to the stack - which increases memory usage. This is not an issue for fewer calls, but once many calls are made the increase in the use of the stack may impact the efficiency of the solution.(popup) A Stack Overflow exception happens when a recursive solution does not have a valid base case. The stack is added to in an infinte loop. |