13
Assignment
Conditionals
Conditional logic in Java is performed with the
if statement
Default values:
The default initial value is:
zero for numbers
false for type boolean
null for String (and other non-primitive type)
Dont go out of bounds!
Read or writing any index outside the
valid range will throw an
ArrayIndexOutOfBoundsException
Combining
Loops &
Arrays
ArrayLists
Dynamically Changing Sized Arrays
So:
ArrayList<String>grades=newArrayList<>();
Arrays vs. ArrayLists
ArrayList Generic Types
To get around this problem, Java defines a wrapper class for
each of the primitive types:
boolean Boolean
byte Byte
char Character
double Double
float Float
int Integer
long Long
short Short
ArrayList Example
ArrayList<String>myArr=newArrayList<String>();
myArr.add("ItalianRiviera");
myArr.add("JerseyShore");
myArr.add("PuertoRico");
ArrayListcanholdelementsofdifferenttypes
TocheckthesizeofanArrayList
Youdosize()so:
myArr.size();
Removing Elements from a list
We need to be careful removing
elements from an ArrayList
Remember when we remove
elements, the entire ArrayList shifts
into the position of the removed
element:
remove(6);
Removing Elements from a list
COMMON MISTAKES
Arrays vs. ArrayLists
If only we had a way to reverse the rest of the lines of the file....
Reversal solution
public static void reverseLines(Scanner input) {
if (input.hasNextLine()) {
// recursive case
String line = input.nextLine();
reverseLines(input);
System.out.println(line);
}
}