CHAPTER 3 CORE JAVA APIs
API: Application Programming Interface, can be a group of classes or interface definitions that gives you access to a service or functionality.
String and StringBuilder are used for text data. An array and an ArrayList are used when you have multiple values.
1. Strings
A string is basically a sequence of characters.
String s = "fluffy"; //doesn't need to be instantiated with new
1) Concatenation
- If both operands are numeric, + means numeric addition.
- If either operand is a String, + means concatenation.
-The expression is evaluated from left to right.
String s = "old";
s = s + false; //outputs oldfalse
2) Immutability
Once a String object is created, it is not allowed to charge. It cannot be made larger or smaller, and you cannot change one character inside it.
3) String pool
The string pool contains literal values that appear in your program.
String s1 = "fluffy";
String s2 = "fluffy";
s1 == s2; // returns true
String s3 = new String("fluffy");
s1 == s3; // returns false
4) String methods
int length() //type returned is int
char charAt (int index)
int indexOf(char ch) //returns -1 when no match is found
int indexOf(char ch, int fromIndex)
int indexOf(String str)
int indexOf(String str, int fromIndext)
String substring(int beginIndex, int endIndex) //char at endIndex NOT included; to the end if endIndex is missing
String toLowerCase()
String toUpperCase()
boolean equals(String str) //to check whether two String object contain exactly the same characters in the same order
boolean equalsIgnoreCase(String str)
boolean startsWith(String str)
booean endsWith(String str)
boolean contains(String str)
String replace(char oldChar, char newChar)
String replace(charSequence oldChar, charSequence newChar) // taking string as parameters
String trim() // remove whitespace from the beginning and end of a String.
5) method chaining
"AniMal ".trim().toLowerCase().replace('a','A');
2. StringBuilder
StringBuilder changes its own state and returns a reference to itself.
1) create StringBuilder
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder("animals");
StringBuilder sb3 = new StringBuilder(10); // reserve a certain of slots for characters
StringBuilder sb4 = new StringBuilder(sb2); // make a copy of sb2
StringBuilder sb5 = sb1;
2) important methods
same as String methods: charAt(), indexOf(String str), lengh(), substring()
StringBuilder append(String str)
StringBuilder sb1 = new StringBuilder().append(1).append(true); //we can directly call append() without coverting parameter to String
StringBuilder insert(int offset, String str)
StringBuilder delete(int start, int end) // the char at the end is not deleted.
StringBuilder deleteCharAt(int index)
StringBuilder reverse()
String toString() //StringBuilder used internally for performance purposes but the end results needs to be String
4. Equality
1) reference equality ==
String s1 = "hello";
String s2 = "hello";
String s3 = "hello ".trim();
s1 == s2; //true, cause JVM reuses String literals
s1 == s3; // false, cause s3 is not same as s1 at comile-time, s3 is newly-created object.
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
sb1 == sb2; //false, different objects
2) logical equality equals
s1.equals(s2); //true, check logical equality
s1.equals(s3); // true
sb1.equals(sb2); // StringBuilder doesn't implement equals(), so it will check reference equality
5. Arrays
An array is an area of memory on the heap with space for a designated number of elements.
1) create an array
int[] numbers = new int[3]; // set all the elements to the default value
int numbers[] = new int[3]; //[] before or after the name, space is optional
int numbers [] = new int[3];
String[] animals = {"monkey","chimp","donkey"};
String[] bugs = animals;
System.out.println(animals.equals(bugs)); //reference equality, doesn't look at the elements inside the array.
2) use an array
animals.length; //returns length of array
import java.util.Arrays;
int[] numbers = {6,9,1};
Arrays.sort(numbers); //return numbers ordered in increment. {1,6,9}
Arrays.binarySearch(numbers, 7); //returns -(2+1)
int[][] numbers= new int[][]; //compile error, cause size of array's first dimension must be set;
6. ArrayList
Just like a StringBuilder, ArrayList can change the size at runtime as needed.
ArrayList requires import
import java.util.ArrayList;
1) create an ArrayList
import java.util.ArrayList;
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList(2);
ArrayList list3 = new ArrayList(list2); // make a copy of list2
ArrayList<String> list4 = new ArrayList<>();
List<String> list5 = new ArrayList<>(); // < wrapped class>
ArrayList<String> list6 = new List<>(); //compile error, cause List it an interface, can NOT be instantiated
2) ArrayList methods
boolean add(E element) // always return true
void add(int index, E element)
boolean remove(Object object)
E remove(int index)
E set(int indext, E newElement)
boolean isEmpty()
int size()
void clear()
boolean contains(Object object)
boolean equals(Object object)
Collections.sort(ArrayList)
Integer.parseInt("") //convert string to primitive
Integer.valueOf("") //convert string to wrapper class
autobox and unbox //convertion between primitive and wapper class automatially
3) converting between Array and ArrayList
list.toArray(); // defaults converted to an array of class Object, isn't usually what you want
list.toArray(new String[0]); //new array of the proper size was created, usually used
list.toArray(new String[10]); //depends on how long
Arrays.asList(array); // convert to fixed size list, can not change the size of it
example 1: list -->array
import java.util.List;
List<Integer> list = new ArrayList<>();
list.add(1);
Object[] array = list.toArray(); // defaults to an array of class Object
Integer[] array = list.toArray(new Integer[0]); // converted to an array of class Integer
example 2: array -->list
import java.util.List;
import java.util.Arrays;
Integer[] array = new Integer[]{1,2,3,4};
List<Integer> list = Arrays.asList(array);
list.remove(0); // throws exception, because the size of list can not be changed
7. Dates and Times
Dates and times are immutable.
import java.time.*;
1) create dates and times
method signatures:
public static LocalDate of(int year, int month, int dayofMonth)
public static LocalDate of(int year, Month month, int dayofMonth) //Month is a special type of class called enum
public static LocalTime of(int hour, int minutes)
public static LocalTime of(int hour, int minutes, int seconds)
public static LocalTime of(int hour, int minutes, int seconds, int nanos)
LocalDateTime: 6 method signatures + 1
public static LocalDateTime of(LocalDate, LocalTime)
example:
LocalDate date = LocalDate.of(2019, Month.JANUARY, 14);
LocalDate date = LocalDate.of(2019,5,14);
LocalDateTime dt = LocalDateTime.of(2019,5,14,15,21);
LocalDate date = LocalDate.of(2019,5,50); // compile but throw exception
2) Manipulating Dates and Times
date.plusDays(1);
date.plusWeeks(1);
date.plusYears(1);
date.minusDays(1);
date.minusWeeks(1);
date.minusYears(1);
time.plusHours(1);
time.minusHours(1);
......
time.minusNanos(1);
time.minusDays(1); //compile error
3) period
Five ways to create a period: no time period.
Period annually = Period.ofYears(1);
Period quarterly = Period.ofMonths(3);
Period weekly = Period.ofWeeks(1);
Period dayly = Period.ofDays(1);
Period everyYearAndAWeek = Period.of(1,0,7);
Period p = Period.ofYears(1).ofWeeks(1); // only the last method is excuted in code chain.
date.plus(dayly);
datetime.plus(weekly);
time.plus(annually); // try to add year to an object that only has a time. UnsupportedTemporalTypeException
4) Formatting Dates and Times
date.getYear();
date.getMonth();
date.getDayOfYear()
date.getDayOfWeek();
......
DateTimeFormatter is in the package java.time.format. // import java.time.format.*;
DateTimeFormatter shortF = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
DateTimeFormatter mediumF = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
DateTimeFormatter mediumF = DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM);
DateTimeFormatter mediumF = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
DateTimeFormatter f = DateTimeFormatter.ofPattern("MMMM dd, yyyy, hh:mm"); // create your own pattern
--M outputs 1, MM outputs 01, MMM outputs Jan, MMMM outputs January
--d outputs 1, d outputs 01
--yy outputs 19, yyyy outputs 2019
--h outputs 1, hh outputs 01;
--mm outputs 01;
The format() method is decleared on both formatter object and date/time object.
example:
LocalDate date = LocalDate.of(2019,5,14);
LocalTime time = LocalTime.of(16,43,10,10);
LocalDateTime datetime = LocalDateTime.of(date, time);
DateTimeFormatter f = DateTimeFormatter.ofPattern("MM dd, yy");
Period weekly = Period.ofWeeks(1);
datetime = datetime.plus(weekly);
System.out.println(datetime);
System.out.println(datetime.format(f));
System.out.println(f.format(datetime));
5) parsing Dates and Times
DateTimeFormatter f = DateTimeFormatter.ofPattern("MM dd, yyyy");
LocalDate date = LocalDate.parse("05 14, 2019", f);
LocalTime time = LocalTime.parse("17:00"); // default settings
LocalDateTime dt = LocalDateTime.of(date, time);
System.out.println(dt);