Ch3: Core Java APIs Flashcards
What does API stand for?
Application Programming Interface
What is the value of s1 and s2, and why?
String s1 = “1”;
String s2 = s1.concat(“2”);
s2.concat(“3”);
s1 = “1”
s2 = “12”
The String object is immutable, so the .concat method doesn’t modify the object.
What’s another name for the string pool?
The intern pool
What’s another name for the intern pool?
The string pool
What goes into the string pool?
String literals (not String objects created with “new”)
How do you get the number of characters in a String?
.length()
How do you find out what is at a specific index in a string?
.charAt(int index)
How do you find the index of a specific item in a string?
indexOf(char ch) or indexOf(String str)
How do you find the index of a specific item in a string starting from a specific position?
indexOf(char ch, index int)
What happens when you call indexOf for a value that does not exist?
The value -1 is returned
How would you return the value “123” from the object:
String str = “012345”;
str.substring(1,4) // value at the ending index will not be included
What is the method signature to replace characters?
str.replace(orig, new)
How do you remove trailing and leading whitespace from a string and what is removed?
.trim() removes space, new line (\n), tab (\t), and carriage return (\r)
What does the .append() method on StringBuilder return?
A reference to itself
List all StringBuilder constructor signatures.
new StringBuilder(); // empty object new StringBuilder("foo"); // contains val "foo" new StringBuilder(10); // Empty, but capacity of 10
What are the two StringBuilder methods for adding text to the string in the object?
.append(String str)
.insert(int index, String str)
What are the two StringBuilder methods for removing text from the string in the object?
.delete(int startIndex, int stopIndex) // stopIndex is not removed, same as substring
.deleteChatAt(int index)
Which StringBuilder method is used to reorder the text backwards?
.reverse()
What is StringBuffer?
The same as StringBuilder, but slower because it’s thread safe.
What does the StringBuilder.equals(StringBuilder obj) test?
Checks for reference equality (not value equality)
for
char[] letters;
what kind of variable is letters?
A reference variable pointing to an array of primitive char types
What kind of data structure is an array?
Ordered list
How do you create an empty array of ints?
int[] numbers = new int[3];
How do you create an array of ints with values? (2 ways)
int[] numbers = new int[] {11, 20, 45};
int[] numbers = {11, 20, 45};
What are acceptable variable definitions for an array?
int[] name;
int [] name;
int name[];
int name [];
What type are primitive arrays: primitives or object references?
Object references
How do you get the number of elements in an array?
arr.length;
How do you get a string representation of an array?
java.util.Arrays.toString(myArray);
How do you sort an array?
java.util.Arrays.sort(myArray);
What are the rules for binary search?
- Sorted means “smallest to largest”
- Target element found in a sorted array = index of match
- Target element not found in sorted array = Tells us where to insert to keep the array sorted. Does: neg. desired index minus 1. eg, if the target is index 4, would be -4 - 1 = -5.
- If unsorted (must be smallest to largest), result will be unpredictable.
How does binary search work?
- Divides the data set into two equal parts
- Determines which half the data should exist in
- repeats until data is found
- Only works on sorted data sets (for obvious reasons)
What is the syntax for varargs?
String… args;
List all ways to declare a 2D array
int[][] coords;
int coords[][];
int[] coords[];
How do you define an empty asymmetric multidimensional array?
Only define the first (top level) dimension, then go through each element and define each dimension separately:
int[][] args = new int[2][];
args[0] = new int[5];
args[1] = new int[3];
How do you import ArrayList?
import java.util.ArrayList;
What are the signatures of the three ArrayList constructors?
ArrayList()
ArrayList(int capacity)
ArrayList(ArrayList listToCopy)
How do you instantiate a new ArrayList?
ArrayList strList = new ArrayList<>();
Which interface does ArrayList implement?
List
What is the signature for the method that appends elements to an ArrayList?
boolean add(E element) void add(int index, E element)
where E means any element the array can hold
What elements cannot be added to an ArrayList?
Primitives. They must use the object wrapper.
What happens if you add an element to an ArrayList and specify an index that already holds a value?
The new element will be inserted in front of the existing value
What are the method signatures for deleting an element from an ArrayList?
boolean remove(Object object) E remove(int index)
What happens if you try to remove an object from an ArrayList that does not exist?
The method returns false
What happens if you try to remove an object at an index that does not exist?
IndexOutOfBoundsException is thrown
What is the signature for replacing an object in an ArrayList?
E set(int index, E newElement) // where the return value is the object that was replaced
What’s the method for finding out if an ArrayList has any elements?
.isEmpty()
What’s the method for finding out how many elements are in an ArrayList?
.size()
What is the method for removing all elements from an ArrayList?
.clear()
What’s the signature of the method that determines if an object is in an ArrayList?
boolean contains(Object object)
How do you compare two ArrayLists?
.equals(myList) compares contents and order
List all primitive wrapper classes
Boolean Byte Short Integer Long Float Double Character
How do you convert a String to an int?
Integer.parseInt(“123”)
How do you convert a String to an Integer?
Integer.valueOf(“123”)
How do you remove the Integer 1 from an ArrayList?
nums.remove(new Integer(1)) Otherwise, it removes the item at index 1 instead of the Integer object 1.
How do convert an ArrayList of Strings to an array of Strings?
String[] strArray = list.toArray(new String[0]);
If you convert an ArrayList to an array, are the two objects linked in any way?
No
If you convert an array to an ArrayList, are the two objects linked in any way?
Yes
What is the term for a list with an array linked to it?
A backed list
How do you convert an array to a list?
List list = Arrays.asList(array);
What are the properties of a list created with the method Arrays.asList(array)?
- Backed by the source array (a backed list) - a change to one changes both
- Fixed size - cannot add or remove elements
How do you create and populate an ArrayList in a single line?
List list = Arrays.asList(“one”, “two”);
How do you sort an ArrayList?
Collections.sort(list)
What is the import statement for working with dates and time?
import java.time.*;
What are the three objects used for storing date/time information without timezones?
- LocalDate
- LocalTime
- LocalDateTime
What information is stored in LocalDate?
Date information, no timezone or time. eg, Feb. 22nd 2002
What information is stored in LocalTime?
Time information, no timezone or date. eg, 11:59PM
What information is stored in LocalDateTime?
Date and time information, no timezone. eg, December 24th, 9pm.
Which object is used for storing timezone information, and what is the recommendation for dealing with timezones?
ZonedDateTime, and Oracle suggests acting as if everyone is in the same timezone when you can.
How do you get the current date and/or time from a time object?
.now()
What is the format returned for LocalDateTime.now()
YYYY-MM-DDTHH:MM:SS.nnn
How do you create a LocalDate object with a specific date?
LocalDate.of(2015, Month.JANUARY, 28), or
LocalDate.of(2015, 1, 28)
How do you create a LocalTime object with a specific time?
LocalTime.of(h, mm [, ss, nnn])
List two ways to create a LocalDateTime object
LocalDateTime.of(localDate, localTime)
LocalDateTime.of(yyyy, mm, dd, hh, mm)
Can you use the new keyword on DateTime objects?
No, DateTime objects have private constructors
Are DateTime methods mutable or immutable?
immutable
How do you add time to a LocalDate object? (all methods)
date = date.plusDays(2); date = date.plusWeeks(1); date = date.plusMonths(1); date = date.plusYears(5);
How do you remove time from a LocalDateTime object?
dateTime = dateTime.minusDays(1); dateTime = dateTime.minusHours(10); dateTime = dateTime.minusSeconds(30);
How do you compare two dates?
localDate1.isBefore(localDate2)
What is java.time.Period and how do you use it?
* Designates a period of time, a day or longer, independent of a specific point in time (eg, "one month") Period.ofYears(int) .ofMonths(int) ofWeeks(int) ofDays(int) of(m, d, y) // all three required
What does this code do?
java.time.Period.ofYears(1).ofWeeks(1)
Creates a period of one week (Period cannot be chained, so ofWeeks overwrites ofYears)
What is java.time.Duration?
Specifies a period of time, down to the nanosecond, independent of a specific point in time (eg, three minutes)
Which objects and methods can you pass java.time.Period into?
LocalDate.plus()
LocalDateTime.plus()
Note - LocalTime.plus() will return an error, as Period works with larger units of time than LocalTime can handle
Which LocalDate methods return parts of the date (day, month, etc)?
.getDayOfWeek // Monday .getDayOfYear // 45 .getDayOfMonth // 14 .getMonth // February .getYear // 1984
Which class allows you to define date and time formats?
java.time.format.DateTimeFormatter
What are the key methods for DateTimeFormatter, and which kind of time objects does it work with?
.ofLocalizedDate(FormatStyle) // works with date and datetime objects
.ofLocalizedTime(FormatStyle) // works with date and datetime objects
.ofLocalizedDateTime(FormatStyle) // only works with datetime objects
Which two Date and Time format singletons will be on the exam?
FormatStyle.SHORT
FormatStyle.MEDIUM
List two ways to use the date time formatter
DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(localizedDateObj);
localizedDateObj.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
What are the different symbols of the date formatter string?
M = Month d = Day y = Year h = Hour m = Minute
How do you parse a String into a DateTime object?
DateTimeFormatter f = DateTimeFormatter.ofPattern(“MM dd yyyy”);
LocalDate date = LocalDate.parse(“01 02 2015”, f);
LocalTime time = LocalTime.parse(“11:22”);
System.out.println(date); // 2015-01-02
System.out.println(time); // 11:22