Wikipendium

Share on Twitter Create compendium Add Language
Edit History
Tools
  • Edit
  • History
  • Share on Twitter

  • Add language

  • Create new compendium
Log in
Table of Contents
  1. Chapter 3
    1. Strings
      1. The String Pool
      2. String methods
    2. StringBuilder
      1. Methods in StringBuilder
    3. Equality
    4. Arrays java.util.Arrays
      1. Methods in Array
      2. Multidimensional Arrays
    5. ArrayList
      1. Methods in ArrayList
      2. Wrapper Classes and autoboxing
      3. Converting between array and List
    6. Working with Dates and Times
      1. Periods
      2. Formatting Dates and Times
    7. Questions extra
‹

1Z0-808: Oracle Certified Associate Java SE 8 Programmer I

Tags:
+

Chapter 3

Strings

Rules for the "+" operator

  1. Numeric + numeric = numeric
  2. If one is a string, result is String
  3. 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.

  1. new StringBuilder();
  2. new StringBuilder("animal");
  3. 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

  1. "Hello" == "Hello".trim(); Book says this is false?
  2. "Hello" == new String("Hello"); False
  3. "Hello" == "Hello"; True
  4. new StringBuilder() == new StringBuilder(); False

Arrays java.util.Arrays

Creating an array:

  1. int[] numbers1 = new int[3];
  2. Type[] name = new Type[size];
  3. int numbers2 = new int[] {42,55,99};
  4. int numbers2 = {42,55,99};
  5. int numbers2[] or int [] numbers2 or int numbers2 [];
  6. int ids[], types; //Creates one array and one Integer!

Be carefull when casting arrays:

  1. String[] strings = {"stringValue"};
  2. Object[] objects = strings;
  3. 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

  1. Returns index of target if found
  2. Returns (negative index)-1 of where it should be in a sorted array
  3. 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:

  1. int[][] vars1;
  2. int vars2[][];
  3. int[] vars3[];
  4. int[] vars4 [], space[][]; //Creates one 2D and one 3D array
  5. String[][] rectangle = new String[3][2];
  6. int differentSize = {[1,4}, {3}, {9,8,7}} //Array of variable size

ArrayList

Requires import ArrayList

  1. list1 = new ArrayList();
  2. = new ArrayList(10);
  3. = 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)

Written by

skotn
Last updated: Mon, 13 May 2019 15:26:27 +0200 .
  • Contact
  • Twitter
  • Statistics
  • Report a bug
  • Wikipendium cc-by-sa
Wikipendium is ad-free and costs nothing to use. Please help keep Wikipendium alive by donating today!