Java 8 Se OCA 1Z0 808 Exam checklist

Posted by Monik, 28 May 2016.
Programming Java
Preparation for certification

Again, trying to make a summary of the summary ;) (see this post for more context). Tried to put the main topics together in a form of questions, along with the short answers (click on the “see” links to see them).

Very important: please comment if you see an error.

Update: I passed :) It was a really really annoying exam to prepare. And yes it was a good idea to do some online mock exams, even as late as on the day before the exam.

Table of contents

Checklist on every question

Questions around Java

  • when they ask you about compilation errors, they ask you about all of them, not the first one
  • when they ask for the “output” they can mean any part of the output
  • if there is an answer like “an exception is thrown” it still does not mean that some other outputs are not true as well, that will happen before the exception
  • when there are no line numbers in a code snippet assume that missing imports do cause compilation errors
  • to start a Java program:
    • $ javac com/bla/Zoo.java - requires JDK
    • $ java com.bla.Zoo - requires only JRE
  • if main is missing, the process will throw an exception
  • if main is of wrong signature, Java will throw an exception
  • heap: objects, sometimes references to objects, arrays
  • stack: primitives, references to objects

Operators and primitive types

  • byte (from -128 to 127), short, int, long are respectively: 8, 16, 32, 64-bit;
  • float and double are 32 and 64-bit floating-point(=decimal), respectively;
  • char is 16-bit Unicode
  • octal: starts with 0, e.g. 017
  • hexadecimal: starts with 0x or 0X, e.g. 0xFF
  • binary: starts with 0b or 0B, e.g. 0b10
  • upcasting happens e.g. here double d = 98; - where a number of lower precision is automatically casted to the one of higher precision
  1. the most popular i++, i--
  2. ..and the reverse ++i, --i
  3. be or not to be” unary +, -, !
  4. this follows maths *, /, %
  5. ..still maths +, -
  6. <<, >>, >>> (shift operators)
  7. and now we see that.. <, >, <=, >=, instanceof (relational operators)
  8. ..equality is later than non equality ==, !=
  9. logic comes quite late &, ^, | (logical operators)
  10. ..even later short circuited &&, || (short circuit logical operators)
  11. ternary a ? b: c
  12. assignment is last =, +=, -=, *=, /=, %=, &=, ^=, !=, <<=, >>=, >>>= (assignment operators)
  • it occurs for example here 5==5.0 - even though the numbers are of different type, 5 is first converted to 5.0 and then the comparison is made
  • promotion occurs before an operand is applied or before method invocation
  • there are 4 rules for numeric promotion:
    • smaller datatypes are promoted to larger ones
    • integral types are promoted to floating point types
    • short, byte and char are always promoted to int when applying a binary operator
    • the resulting value is of common type of the two operands
  • yes, it will just result in precision loss/overflow
  • int and Integer
  • byte and Byte
  • short and Short
  • char and Character
  • enum
  • String
  • no long, no boolean
  • all must be final
  • double, float would be that: 9.5f
  • you would use it to save yourself casting back to the smaller data type, in case a is of smaller data type than b; the casting is done automatically (which also means be careful here)

Java methods

  • default = package private - visible only to classes from the same package
    • subpackage is understood here as another package
  • protected - visible to classes from the same package and to subclasses
    • subclass means an actual object of subclass type; you cannot access another object’s protected field that is in another package, no matter how its type related to yours is
  • you cannot change it, but if you didn’t initialize it right where you defined it, you can still set it in the static{} class initializer
  • import static; import must be first
  • remember that static imports are only for class memebers, not clases
  • remember that statically importing a class member does not import the owning class
  1. exact match
  2. larger primitive type
  3. autoboxing
  4. varargs
    • while trying to find an overload, Java does max one conversion, later is compilation error!
  • in inheriting class the return type must be same or more narrow than in superclass’ method
  • hiding refers to one of the two cases:
    • when a static method is overridden, this is actually called hiding, not overriding ;)
    • all fields are always hidden when extending - both instances exist in memory independently, within the child class object; to refer to the parent field you need to write ParentClassName.fieldName
  • you cannot hide final members
  • LaBel: is an optional pointer to the head of a statement
  • used like this: break LABEL; (break from the statement labelled like this) or continue LABEL;
  • none, all interfaces are assumed to be abstract, and each that is not marked so, will be changed to abstract interface by the compiler
  • variables are assumed to be public static final (so must be initialized, even if no final is explicitly written!)
  • methods are assumed to be public abstract/default/static
  • it’s a method whose implementation is not determined until runtime
  • all non-final, non-static and non-private methods in Java are virtual

Loops

  • do{...}while(booleanExpression); - you can use it when you want that the body is executed at least once
  • note that do System.out.println();while(booleanExpression); is also correct syntax
  • for(initialization; booleanExpression; updateStatement){}
  • everything except the booleanExpression in the middle can have multiple expressions, seprarated by a comma ,
  • continue only inside loops
  • break only inside loops and switch statement

Java classes and variables

  • must start with a letter (Unicode) or _ or $
  • cannot start with a number
  • can contain letters, numbers, _ and $
  • cannot be same as reserved keyword (if it’s different letter case then it’s fine though)
  • required to initialize local variable (also primitive), or final instance and class variable
  • not required to initialize non-final instance and class variable, if they are primitive type they are given the default value for that type
  • more visibility is allowed
  • less visibility is not allowed (compilation error)
  • one
  • either compiler error saying The type xxx is ambiguous, or The import xxx collides with another import statement, depending on whether you imported those explicitly or implicitly (with wildcard *)
  • if you import one implicitly and another explicitly, there’s no conflict
  1. initialise the superclass
  2. class fields and class initializers (so everything static) in the order they appear
  3. instance fields and instance initializers in the order they appear
  4. constructor
  • shit, actually yes!

Java 8 stuff

  • if {} are used, return and ; must be used too, they always come together
  • if type of input argument is specified, it must be wrapped in ()
  • if there are more than 2 input args, they have to be wrapped in () (if one arg has type, then all of them have to have it)
  • can access everything as long as it doesn’t attempt to change them
  • java.util.function.Predicate
  • bunnyArrayList.removeIf(s->s.charAt(0)!='h'); - removes all bunnies starting with ‘h’, cool isn’t it :D
  • defined in an interface
  • has body
  • is not abstract but still public
  • it’s like default implementation in abstract class - can be overridden but doesn’t have to
  • cannot be invoked on the interface
  • as long as there is no ambiguity which method should be called when (e.g. one of them is overridden in the hierarchy) everything is ok, otherwise compilation error
  • yes, in an extending/implementing interface/class
  • is static and inside interface
  • assumed to be public
  • must be invoked on the interface, is not inherited
  • an interface which has exactly 1 method
  • (annotated with @FunctionalInterface, but this is out of scope)

Java APIs

String and StringBuilder

  • String literals are stored in string pool, so using == to compare them will result in true if they look the same
  • new String() is already forcing not using string pool
  • the result of "abc"+"d" is already a new String, not the one from String pool
  • the boolean value of "s"=="s".trim() is true
  • the easy ones:
    • length(), toLowerCase(), toUpperCase(), trim()
    • equals(String), equalsIgnoreCase(String)
    • startsWith(String), endsWith(String), contains(String)
  • a bit trickier:
    • substring(start[, end])
    • indexOf(char[, fromIndex]), indexOf(String[, fromIndex])
    • charAt(int)
    • replace(char old, char neww), replace(CharSequence old, CharSequence neww)
  • same as in String:
    • length(), String substring(), indexOf(), charAt()
  • new ones:
    • append(String)
    • insert(offset, String)
    • delete(start, end), deleteCharAt(int)
    • reverse()
    • toString() :)
  • it replaces all the occurences

Arrays

  • ways to instantiate:
    • int i[] = new int{1,2};
    • int i[] = {1,2};- anonymous array
    • int i[] = new int[2];
    • int i[][]= { {2,3},{1,2,3}};
    • int i[][]= new int[2][3];
    • int i[][]= new int[2][];
    • int i[][]= new int[][]; - this won’t compile
  • possible placement of the braces:
    • int[] i = {1,2};
    • int [] i = {1,2};
    • int []i = {1,2};
    • int i[] = {1,2};
    • int i [] = {1,2};
    • and analogically for 2D+
  • when you try to read from an array, and the declared type does not match the actual type, you get an ArrayStoreException
  • int[] a, b; - two 1D arrays
  • int[] a[], b[][]; - two arrays, one 2D and one 3D
  • a variable of type array holds the the reference to the array object
  • the array object holds either a series of primitive values (in case of primitive type array), or series of object references (in case of non primitive type array)
  • memory allocation happens on array initialization
  • java.util.Arrays.sort(array)
  • value that is one smaller than the negative of index where such element would be, if it was there

Collections

  • constructors:
    • new ArrayList()
    • new ArrayList(capacity)
    • new ArrayList(anotherList)
  • methods:
    • isEmpty(), size(), clear()
    • boolean add(element) - note the boolean there will be questions about it; it always returns true
    • void add(index, element) - here is no boolean
    • boolean remove(element)
    • Object remove(int index) - be careful when you remove an int element! it will resolve to this method instead of the one above
    • removeIf(Predicate)
    • Object set(index, Object)
    • boolean contains(Object)
    • equals() (uses elements’ equals())
  • yes of course
  • be careful though, as if you try to unbox it to a primitive value you will get a NullPointerException
  • you can actually pass an existing array there, and it will be filled with the elements from the ArrayList, as long as it’s big enough
  • if the array you passed is not big enough, it will be ignored all together
  • pay attention that you cannot pass a primitive type array there
  • Collections.sort(list);

Wrapper types

  • Integer.parseInt() creates int out of many other types
  • Integer.valueOf() creates Integer out of many other types

  • you can remember that the method which creates the object has same name for all wrappers, because objects have common superclass Object, and primitive types don’t have a superclass; or you can remember that if parseInt() returned an Integer it should be called parseInteger()
  • remember that Character does not participate in this stuff

Date and Time

  • LocalDate, LocalTime, LocalDateTime, all in java.time.* package
  • DateTimeException
  • LocalDate.now();
  • LocalDate.of(2015, Month.JANUARY, 1), same as LocalDate.of(2015, 1, 1)
  • LocalTime.of(6, 15);
  • LocalTime.of(6, 15, 30, 234); - last one is nanoseconds
  • LocalDateTime.of(2015, Month.JANUARY, 16, 15, 30);
  • LocalDateTime.of(date, time);
  • LocalDate date = LocalDate.of(2014,1,23).plusDays(2).minusWeeks(1); - remember it’s immutable!
  • remember that you cannot add minutes to a date, or days to time, etc
  • Period period = Period.ofMonths(1); date = date.plus(period);
  • Period.of(1,0,7); - every year and 7 days
  • remember that you cannot pass hours, minutes, etc to a Period
  • Duration is not on the exam
  • the tricky part is that the of.. methods are not builder methods but static helper methods - so chaining has no effect, like it does in case of LocalDate/Time/TimeDate
  • dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) that resolves to 2020-01-20T12:12:34
  • date.format(DateTimeFormatter.ISO_LOCAL_DATE)
  • dateTime.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)) that resolves to 1/20/2020
  • dateTime.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)) that resolves to Jan 20, 2020
  • DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)).format(dateTime) - also vice versa
  • you can use dateTime with date or time formatters, but not time or date with dateTime formatter, etc
  • DateTimeFormatter.ofPattern("MMMM dd,yyy hh:mm")).format(dateTime)
  • default is 2015-01-02T11:22, and if seconds or nanoseconds were used, they are also appended
  • by using a DateTimeFormatter, e.g. DateTimeFormatter.ISO_LOCAL_DATE, DateTimeFormatter.ISO_LOCAL_DATE_TIME
  • LocalDate.parse(string, formatter);
  • LocalDate.parse(string); - uses default format (see previous question), it’s rather strict
  • there are two:
    • DateFormatException - when you pass e.g. January 67th
    • UnsupportedTemporalTypeException - when you try to use time with date object, or date with time object

Exceptions

  • Errors - thrown by JVM, shouldn’t catch
  • RuntimeException - thrown by JVM or developer, you may catch
  • checked exceptions - thrown by developer, you must catch
  • if they ask you about programmatic exceptions, then according to here, programmatically thrown exception means an exception thrown by an application/ API developer
    • NumberFormatException, AssertionError, IllegalArgumentException, IllegalStateException
    • custom exceptions
  • checked exceptions - only less
  • unchecked - doesn’t matter
  • RuntimeException examples:
    • ArithmeticException
    • ArrayIndexOutOfBoundsException
    • ClassCastException
    • IllegalArgumentException
    • NullPointerException(extends IllegalArgumentException)
    • NumberFormatException
  • checked exception examples:
    • IOException
    • FileNotFoundException (extends IOException)
  • error examples:
    • ExceptionInitializerError - when static initializer block in a class throws an exception
    • StackOverflowError
    • NoClassDefFoundError

.. also, know that


Comments


Comments: