1Z0-808: Oracle Certified Associate Java SE 8 Programmer I
Chapter 3
Strings
Rules for the "+" operator
- Numeric + numeric = numeric
- If one is a string, result is String
- Evaluated from left to right
Strings are immutable (final and only has a getter).
The String Pool
Contains literal values that appear in your program. myObject.toString() or new String("Fluffy") are not here.
String methods
- .length()
- "test".length() //returns 4
- .charAt(int index)
- returns char, don't go out of bound!
- .indexOf(char ch, index fromIndex)
- returns index of ch from index, or return -1 if not found. fromIndex is optional
- .subString(int beginIndex, int endIndex)
- returns substring, throws exception on out of bound and backwards indexing. endIndex is optional
- .toLowerCase() and .toUpperCase()
- returns String
- .equals(String) and .equalsIgnoreCase(String)
- returns boolean
- .startsWith(String preFix) and endsWith(String suffix)
- returns boolean
- .contains(String str)
- returns boolean, is case-sensitive
- .replace(char oldChar, char newChar)
- returns String where all the oldChar sequences or characters are replaced
- .trim()
- returns String, without whitespace, \t, \r and \n before or after
StringBuilder
Is mutable and reuses itself, changing a StringBuilder returns itself and changes itself. StringBuilders share the same object here.
- new StringBuilder();
- new StringBuilder("animal");
- new StringBuilder(10);
Methods in StringBuilder
- .charAt(), indexOf(), length(), subString()
- Works as in String
- .append(String str)
- returns the StringBuilder, can also add numbers, booleans, char etc
- .insert(int offset, String str)
- Pushes str in at offset
- .delete(int start, int end) and .deleteCharAt(int index)
- removes characters between start and end or at index
- .reverse()
- reverses string
- .toString()
- returns the string
Equality
== checks for reference equality on objects but not on literals, Strings are checked against the string pool if not instantiated. You should use .equals(String str) to compare Strings.
Examples
- "Hello" == "Hello".trim(); Book says this is false?
- "Hello" == new String("Hello"); False
- "Hello" == "Hello"; True
- new StringBuilder() == new StringBuilder(); False
Arrays java.util.Arrays
Creating an array:
- int[] numbers1 = new int[3];
- Type[] name = new Type[size];
- int numbers2 = new int[] {42,55,99};
- int numbers2 = {42,55,99};
- int numbers2[] or int [] numbers2 or int numbers2 [];
- int ids[], types; //Creates one array and one Integer!
Be carefull when casting arrays:
- String[] strings = {"stringValue"};
- Object[] objects = strings;
- object[0] = new StringBuilder(); // This will throw an exception!
Methods in Array
array[index] - > Used for accessing/getting/setting element
Length is a field and is accessed using array.length
Arrays.sort(array) - > Sorts array duh
Arrays.binarySearch(array, value) -> Does binary search on array
- Returns index of target if found
- Returns (negative index)-1 of where it should be in a sorted array
- Return surprise index of unsorted array
Multidimensional Arrays
Ways to create, remember that the first size must be defined, but the last can be unspecified:
- int[][] vars1;
- int vars2[][];
- int[] vars3[];
- int[] vars4 [], space[][]; //Creates one 2D and one 3D array
- String[][] rectangle = new String[3][2];
- int differentSize = {[1,4}, {3}, {9,8,7}} //Array of variable size
ArrayList
Requires import ArrayList
- list1 = new ArrayList();
- = new ArrayList(10);
- = new ArraList(oldList);
Generics: Specifying the class in <>: ArrayList<String> = new ArrayList<String>; or new ArrayList<String>;
Methods in ArrayList
- add()
- Insert new value -> boolean add(E elements), void add(int index, E element)
- remove()
- boolean remove(Object object), E remove(int index)
- set()
- E set(int index, E newElement), replaces element at index and returns replaced E
- isEmpty() and Size()
- boolean isEmpty(), int Size()
- clear()
- void clear(), removes all objects and sets list to []
- contains()
- boolean contains(Object object), calls .equals() on all objects
- equals()
- boolean equals(Object object), checks if ArrayList has same elements in same order
Wrapper Classes and autoboxing
Each primitive has a wrapper class, an object corresponding to the primitive.
int primitive = Integer.parseInt("123); //converts to an Integer from the String
Integer wrapper = Integer.valueOf("123"); //converts a String to an Integer wrapper class
The String passed must be valid for the type!
Java will convert a primitive type to relevant wrapper automatically using autoboxing.
.add(50.5) is the same as .add(new Double(50.5))
Remember when removing Integers using .remove(Object object), that you need to wrap the Integer so not to use .remove(int index)!
Converting between array and List
- ArrayList to array
- Object[] objectArray = list.toArray(new array to store in); //Object here should be specified
- Array to list
- List<Object> list = Arrays.asList(array); //Can not change size of list afterwards because array and list are linked
Sorting is done using Collections.sort(list);
Working with Dates and Times
import java.time.*;
- Classes and methods
- Descriptions
- LocalDate
- Just date, no time and no time zone
- LocalTime
- Just time, no date and no time zone
- LocalDateTime
- Date and time, but no time zone
- ...static now()
- returns the time and or date right now
- ...static LocalDate of(int year, int month, int dayOfMonth)
- returns LocalDate object, int month can be object "Month month"
- ...static LocalTime of(h, m, s, ns)
- returns LocalTime object, seconds and nanoseconds are not needed
- ...static LocalDateTime(too many examples to mention)
- returns LocalDateTime, see book page 141 for all examples
You can use .plusDays() .minusDays() etc to manipulate date and time.
Date and time must be constructed using static methods, all constructors are private!
Remember Date and Time objects are immutable, when changing an object use the return type!
Periods
Period class is combined with .plus(Period period) or .minus(Period period) on Date and Time.
Created using Period period = Period.ofXXX(int X)
Use Period.of(year, month, weeks) to make more complex periods, and don't use clock-periods on date or vice versa!
Formatting Dates and Times
You can use getters to get dates and times from these objects or use the DateTimeFormatter from package java.time.format: LocalDate.format(DateTimeFormatter.ISO_LOCAL_DATE).
To print short and simple versions:
DateTimeFormatter f = DateTimeFormatter.____(FormatStyle.SHORT);
The blank space must be filled with the appropriate (ofLocalizedDate, ofLocalizedDateTime or ofLocalizedTime) and the used using f.format((localDate, localDateTime or localTime)) to return. MEDIUM can be used instead of SHORT to produced longer versions. Or use DateTimeFormatter.ofPattern("your own pattern, ex "MMMM dd, yyyy, hh:mm""); to create something new.
.parse(String string, DateTimeFormatter) can be used to convert String to Date or Time. .parse(String string) uses default formatter.
Questions extra
List.add(null)