These are my study notes taken while preparing for Java Oracle Certified Associate exam and reading the “Oca: Oracle Certified Associate Java Se 8 Programmer I Study Guide: Exam 1z0-808” by Jeanne Boyarsky. Reading such study guide is in my opinion the best way to prepare for the exam, as it actually teaches you things you will need on the exam rather than what you need when you program in Java (which is entirely different than taking an exam, of course). Here I make notes on the stuff I found new, important or surprising.
Some background about me - I have been programming in Java for about 7 years now (plus minus 2 years, I’m not good at memorizing stuff:P). My programming experience I started at Java 5, by reading thoughroughly the first two thirds of Thinking in Java book (what I didn’t read were threading and custom annotations), and then starting my first job. I recently understood some Java 8 stuff, though this came mostly by learning F# aside (a functional language derived from C#).
Very important: please comment if you see an error.
public void MyClass()
- this is how they may trick you, notice this is NOT a constructor since it has void
return type..StringBuilder str = "bla";
- another way to trick, this does not compileArrays.asList()
returns a special fixed size list that is linked to the actual array - attempting an operation that changes the size causes an exceptionSystem.gc()
is just a suggestionSystem.out.println()
calls the .toString()
method internallyfinally
block masks the exception thrown in the catch
block (actually learnt it recently, but the book confirmed it)_
$
is a perfectly valid variable name, or start of onestring1 ==string2
will render true
but stringBuffer1.toString()==s2
(with same string) will render false
- there’s something called string pool; also sth like new String("bla")
will be always created not taken from string poolint[] array = {3,5};
- this is also how you can initialize an array (along with =new int[]{3,5};
), but only if it is in same line as declaration!super()
in public F() { super();...
is optional, super();
will be invoked anyway (first) if no super is invoked manuallyjava.lang.Error
: An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.RuntimeException
is thrown by both JVM and developer, Error is thrown by JVM, both are not required to be caughtint x = 6, j=8;
- almost forgot this multiple assigment syntax; int i, int j;
- wrong, int i,j;
- gooddo {....} while(condition);
java.time.LocalDate
, with a static method: of(int year, java.time.Month month, int dayOfMonth)
, which works predicably, throwing DateTimeException
if the input is messed up; months numbered from 1.{}
are used, return
must be used tooint
<->Integer
) works for collections but not for inferring Predicate
s;default
method and normal interface method also do not combine well when implementing 2 interfaces with same method signature (compilation error)/**
is Javadoc comment, and /*
is normal commentstatic void main
’s code is executed; JVM allocates the memory, CPU, file access, etc.$ javac com/bla/Zoo.java
$ java com.bla.Zoo**
where Zoo
has static void main
of course (JDK required for javac, for java only JRE); if main
is missing the process will throw exception; if main
is wrong signature the Java will throw exception; args[0]
is not the program name but the first input arg; if an input arg has a space, wrap it in d-quotes;
java.lang.*
is automatically importedjava.util.Date
and java.sql.*
); if both are explicit but collide, you get another compilation error: The import … collides with another import …{..}
directly in a class is called instance initilalizer (may be static or not); instance initilalizer is also a code blockbyte
(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 Unicodeint num;
- and the 32 bits is already allocated by Java0
, e.g. 017
, hexadecimal: starts with 0x
or 0X
, e.g. 0xFF
, binary: starts with 0b
or 0B
, e.g. 0b10
1_000_000
, or 1_00_0_000
:P but not at beginning/end/touching the decimal pointSystem.gc()
is only a suggestion to run gc, not an order.0
, e.g. double d = 98;
is ok! (it’s called upcasting), same for float!i++
, i--
++i
, --i
+
, -
, !
*
, /
, %
+
, -
<<
, >>
, >>>
(shift operators)<
, >
, <=
, >=
, instanceof
(relational operators)==
, !=
&
, ^
, |
(logical operators)&&
, ||
(short circuit logical operators)a ? b: c
=
, +=
, -=
, *=
, /=
, %=
, &=
, ^=
, !=
, <<=
, >>=
, >>>=
(assignment operators)int t = 11/3
= 3! (floor)short t =9, g=2; t *= g;
works :) - use of compound assignment, casts automatically after(short)1921222 = 20678
- because overflow happenedint y = (x=3);
- this is correct, and the value is 3
;^
means exclusive or!5 == 5.0
is true (promotion)a ? b : c
is also doing short circuitingswitch
supports: int
, byte
, short
, char
, their wrappers, enums
and strings (some since Java 7), no long, no boolean! and they must be either constants (e.g. literals) or final
do-while
loop guarantees that the statement will be executed at least once, on contrary to the while loopfor (;;)
is correct, it’s an infinite loopLABEL:
is an optional pointer to the head of a statement; does not have to uppercase; can be used after break: break LABEL;
or continue: continue LABEL;
continue
- finish execution only of current loop;continue
or break
in if!byte y = (int)short1 + short2
- will not work, bracket missing!do-while
- watch out for variable scope!!==
operator will not compile if the compared objects are of different type!String
System.out.println(1 + 2 + "c");
outputs 3c
(order of operators)final
), so doing operations on them always returns a new String
str.indexOf()
- returns first index of occurence, or -1str.substring(inclusively, exclusively)
str.startsWith()
and str.endsWith()
is case sensitiveString
implements CharSequence
str.replace(oldChar, newChar)
or oldSequence, newSequence
- replaces all occurences!StringBuilder=new StringBuilder(10);
- initial capacity, default 16
strBuilder.charAt()
, .indexOf()
, .length()
, .substring();
substring returns a String
strBuilder.insert(offset, string)
strBuilder.delete(startInc, endExc)
, .deleteAt()
strBuilder.reverse()
StringBufferv is just an old, thread-safe, slow version of
StringBuilder`System.out.println(stringBuilder);
will actually convert it to String
Array
String
is implemented as an arrayint[] numbers = new int[3];
int[] numbers = new int[]{14,12,53};
int[] numbers = new int{14,12,53};
int [] numbers = new int[3];
int numbers[] = new int[3];
int a[], b;
- this is one int array
and one int
, and is correct![Ljava.lang.String;@160bc7c0
- array of reference type java.lang.String
and 160bc7c0
hash codeArrayStoreException
is thrown on an attempt to store a an object that does not match the initialized type)java.util.Arrays.sort(array)
java.util.Arrays.binarySearch(array, what)
- works only for sorted array, for non sorted the result will be random; if the element is not found, this method returns (-1*i)-1
, where i is the index where a new element would have to be put to matchint[] vars4 [], space [][]
- this is one 2D and one 3D array!int[][] differentSize = { {2},{4,6},{1,2,5,7}}
int[][] args = new int[4][]; args[0] = new int[5]; args[1] = new int[3];
char[]c
- compiles (no space)final int[][] java = new int[][];
- does not compile! cannot have more dimensions before first one is specified (only the first one needs to be specified)!ArrayList
new ArrayList(10);
- capacitynew ArrayList(anotherList);
Object arrayList.remove(index);
boolean arrayList.remove(object);
- removes first matchingarrayList.removeIf(condition)
- new! Java 8!ReplacedObject set(index, object)
.isEmpty()
, .clear()
.contains()
- calls equals on elements!.equals()
- deep comparingArrays.asList()
converts not to ArrayList, but something that does not let you remove() - it’s a fixed size version of a listWrappers for Primitives
parseInt()
returns a primitive, while valueOf()
returns a wrapper classlistOfIntegers.add(null)
- is legal! but unboxing it into int will cause NullPointerException
(as it’s not an int
), meaning this: int h = listOfIntegers.get(0);
btw adding null
is no longer called autoboxinglist.remove(2)
- will rather treat 2 as index, not object - as int is closer to int
than Integer
Dates and Times
import java.time.*
LocalDate
- date without time and timezone, use e.g. for birthdayLocalDate.now();
2015-01-20
LocalDate.of(2015, Month.JANUARY, 1)
, same as LocalDate.of(2015, 1, 1)
LocalTime
- time without timezone and without date12:45:16:245
LocalTime.of(6, 15);
LocalTime.of(6, 15, 30);
LocalTime.of(6, 15, 30, 234);
- last one is nanosecondsLocalDateTime
- both date and time but without timezone2015-01-20T12:45:16:245
T
to separate date from time when converting it to a StringLocalDateTime.of(2015, Month.JANUARY, 16, 15, 30);
LocalDateTime.of(date, time);
ZonedDateTime
is for timezonesnew LocalDate();
DateTimeException
if the numbers are invalidDate
class represented both date and time, always; moths started from 0
; actually Calendar
was newer way, but still it’s old :P and long to use..Manipulating Date and Time
localDate.plusDays(2);
, .plusWeeks()
, … - immutable!localTime.minusHours(3);
, … - notice, LocalDate
does not operate on hours, and vice versa!LocalDate
is immutable! - chain those methodsLocalDate.toEpochDay()
- number of days since Jan 1 1970
LocalDateTime.toEpochTime()
- number of secondsLocalTime.toEpo...
Period.ofMonths(1);
localDate.plus(period);
for LocalTime
it throws UnsupportedTemporarTypeException
Period.of(1,0,7)
- every year and 7 daysDuration
is for hours, minutes and seconds, but it’s not on the examlocalDate.getDayOfWeek(); //MONDAY
localDate.getDayOfYear(); //30
Formatting Date and Time
java.time.format.DateTimeFormatter
localDate.format(DateTimeFormatter.ISO_LOCAL_DATE); //2020-02-20
DateTimeFormatter.ISO_LOCAL_TIME //11:12:34
DateTimeFormatter.ISO_LOCAL_DATE_TIME //2020-02-20T11:12:34
DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(dateTime); // 1/20/20
- notice that also has to match, cannot have a time type for localDate (exception)date.format(formatter)
as well as formatter.format(date)
FormatStyle.SHORT: 1/20/20 11:12 AM
FormatStyle.MEDIUM: Jan 20, 2020 11:12:34 AM
DateTimeFormatter.ofPattern("MMMM dd, yyyy, hh:mm"); //January 20, 2020, 11:12
- but remember, also has to match with the formatted type!SimpleDateFormat
, same stuffDateTimeFormatter.ofLocalizedTime
outputs only time, even though the formatter is for both dates and timesParsing Date and Time
LocalDate.parse(string, formatter);
LocalDate.parse(string);
- uses defaultdefault
(i.e., when you don’t specify any) and protected
access - default is only available for the classes in same package, knows nothing about inheritancestatic
, abstract
, synchronized
(out of scope), native
(out of scope), strictfp
(out of scope), and they go between the access modifier and the return type_
and $
are allowed in method name, cannot start with a numberbla()
is protected in A
, A
and B
are in different packages:final
only means that that variable cannot be reassigned, but if it is a list for example, we can add elements (call methods){}
block, directly in the class; it runs when the class is first used; and here (and only here) the final
variables can be reassigned! (but not more than once)import static java.utils.Arrays.asList;
in case of conflicts local have precedence; and if two imports collide there’s compilation errorstatic
and non static
int
and Integer
- autoboxing is only done when is neccessaryString
and Object
int
and long
; even passing 123
to a method accepting long worksthis.name = name;
it works because local variable has priority*.class
file has themgetNumWings(){return numberWings;}
was correct..public interface Predicate{boolean test(T t);}
(java.util.function.*
)default
access !final
, don’t forget thisstatic void main()
is called? nothing, they are not executed!byte
(8)!extends java.lang.Object
or super();
call in constructorsuper
, e.g. super.age
this
and this()
, super and
super()`SuperClassName.doSomething()
final
methods cannot be overridden or hiddenabstract
class and interface
cannot be marked as final
(of course, right..); same with abstract
methodabstract
, you can even specify them abstract:public
or default
accesspublic static final
(so must be initialized, even if no final
is explicitly written!)public abstract
, or actually either abstract
, static
or default
, since Java 8!default
(Java 8)abstract
, nor static
, nor final
, always assumed to be public
thoughabstract
in extending interface/implementing abstract class!static
; must be referred to using the interface name (even in implementing class)Throwable
, and are meant to express something that went very wrong; JVM throws them; you’re not supposed to catch them, as anyway you won’t be able to fix them;RuntimeException
s you may catchtry-catch
, like you can with if
and with while
catch
and finally
blocks have to be in the right order; at least one must be presentfinally
runs always, except when System.exit(int code)
is called!RuntimeException
examples:
ArithmeticException
ArrayIndexOutOfBoundsException
ClassCastException
IllegalArgumentException
NullPointerException
(extends IllegalArgumentException)NumberFormatException
IOException
FileNotFoundException
(extends IOException)ExceptionInitializerError
- when static initializer block in a class throws an exceptionStackOverflowError
NoClassDefFoundError
System.out.println(e);
has same effect as System.out.println(e.getClass().getName()+": "+e.getMessage());
Comments: