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
- Operators and primitive types
- Java methods
- Loops
- Java classes and variables
- Java 8 stuff
- Java APIs
- Exceptions
- .. also, know that
Checklist on every question
- are there typos
- do the braces match, and are the semicolons in the right places
- are imports missing (if line numbers start from 1)
- are the method signatures really correct (e.g. constructor should not have return type)
- are the letters
l
orf
missing at the end of numberlong
ordouble
literals - are we not trying to call non-
static
method from astatic
method - are there any uninitialized local variables or class constants
- is there a method called on an immutable object and not assigned to anything afterwards (look especially at Strings and Dates)
- are the
throws
in checked exceptions propagated correctly - don’t try to compute tricky variable reassignments in memory, that’s a trap - take the paper
Questions around Java
- the question structure on the exam
- 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
- how to start Java program from command line and what is required for which step (JDK or JRE)
- 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
- what is stored on the heap and what is stored on the stack
- heap: objects, sometimes references to objects, arrays
- stack: primitives, references to objects
Operators and primitive types
- what are the bit sizes of each primitive type
byte
(from-128
to127
),short
,int
,long
are respectively:8
,16
,32
,64
-bit;float
anddouble
are32
and64
-bit floating-point(=decimal), respectively;char
is16
-bit Unicode
- how is a binary, octal or hexadecimal number represented
octal
: starts with0
, e.g.017
hexadecimal
: starts with0x
or0X
, e.g.0xFF
binary
: starts with0b
or0B
, e.g.0b10
- what is upcasting
- upcasting happens e.g. here
double d = 98;
- where a number of lower precision is automatically casted to the one of higher precision
- operator types and operator precedence, have practiced that!
- the most popular
i++
,i--
- ..and the reverse
++i
,--i
- “be or not to be” unary
+
,-
,!
- this follows maths
*
,/
,%
- ..still maths
+
,-
<<
,>>
,>>>
(shift operators)- and now we see that..
<
,>
,<=
,>=
,instanceof
(relational operators) - ..equality is later than non equality
==
,!=
- logic comes quite late
&
,^
,|
(logical operators) - ..even later short circuited
&&
,||
(short circuit logical operators) - ternary
a ? b: c
- assignment is last
=
,+=
,-=
,*=
,/=
,%=
,&=
,^=
,!=
,<<=
,>>=
,>>>=
(assignment operators)
- what is numeric promotion and its rules
- it occurs for example here
5==5.0
- even though the numbers are of different type,5
is first converted to5.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
andchar
are always promoted toint
when applying a binary operator- the resulting value is of common type of the two operands
- is it possible to cast from larger numeric type to smaller one?
- yes, it will just result in precision loss/overflow
- which types are allowed as type of
x
inswitch(x)
int
andInteger
byte
andByte
short
andShort
char
andCharacter
enum
String
- no
long, noboolean - all must be
final
- is this
9.5
of typedouble
orfloat
?
double
, float would be that:9.5f
- why would you use compound assignment (
a += b
) over a regular one (a = a + b
)?
- you would use it to save yourself casting back to the smaller data type, in case
a
is of smaller data type thanb
; the casting is done automatically (which also means be careful here)
Java methods
- what is the practical difference between
default
andprotected
access
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
- can you change the value of a
static final
class variable and if yes then how
- 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
- how to do a static import: is it
import static
orstatic import
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
- according to what and in which order is the right overloaded method determined
- exact match
- larger primitive type
- autoboxing
- varargs
- while trying to find an overload, Java does max one conversion, later is compilation error!
- what means covariant return type
- in inheriting class the return type must be same or more narrow than in superclass’ method
- method and variable hiding; when is hiding not allowed
- 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
- when a
- you cannot hide
final
members
- labels
LaBel:
is an optional pointer to the head of a statement- used like this:
break LABEL;
(break from the statement labelled like this) orcontinue LABEL;
- what is the difference between
interface
andabstract interface
- none, all interfaces are assumed to be
abstract
, and each that is not marked so, will be changed toabstract interface
by the compiler
- what modifiers are assumed in an interface
- 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
- what is
virtual
method
- 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
- the
do-while
loop and why to use it at all
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
- what are a segments of the
for
loop and which one can contain multiple expressions
for(initialization; booleanExpression; updateStatement){}
- everything except the booleanExpression in the middle can have multiple expressions, seprarated by a comma
,
- where can you use the
continue
andbreak
keywords
continue
only inside loopsbreak
only inside loops andswitch
statement
Java classes and variables
- class / variable / method valid names
- 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)
- when will you get compilation error on uninitialized variable and when not
- 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
- what happens when you change method visibility while overriding
- more visibility is allowed
- less visibility is not allowed (compilation error)
- how many variables are initialised here
int i1,i2,i3=0;
- one
- what happens on different kinds of import collisions
- 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
- order of initialization on object creation
- initialise the superclass
- class fields and class initializers (so everything
static
) in the order they appear - instance fields and instance initializers in the order they appear
- constructor
- can an
abstract
class extend a nonabstract
class
- shit, actually yes!
Java 8 stuff
- lambda expressions - when can you omit braces, semicolons, variables, etc
- 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 a lambda expression access the containing class’ instance variables
- can access everything as long as it doesn’t attempt to change them
- example of using
Predicate
java.util.function.Predicate
bunnyArrayList.removeIf(s->s.charAt(0)!='h');
- removes all bunnies starting with ‘h’, cool isn’t it :D
- what is a
default
method
- defined in an interface
- has body
- is not
abstract
but stillpublic
- it’s like default implementation in abstract class - can be overridden but doesn’t have to
- cannot be invoked on the interface
default
methods - what happens on any inheritance collisions
- 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
- can
default
method be redeclared to be anabstract
method
- yes, in an extending/implementing interface/class
- what is a
static
interface method
- is
static
and inside interface - assumed to be
public
- must be invoked on the interface, is not inherited
- what is a functional interface
- an interface which has exactly 1 method
- (annotated with
@FunctionalInterface
, but this is out of scope)
Java APIs
String and StringBuilder
- the trick with comparing Strings and string pool
String
literals are stored in string pool, so using==
to compare them will result intrue
if they look the samenew 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()
istrue
- methods on
String
- 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)
- methods on
StringBuilder
- same as in
String
:length()
,String substring()
,indexOf()
,charAt()
- new ones:
append(String)
insert(offset, String)
delete(start, end)
,deleteCharAt(int)
reverse()
toString()
:)
- does
str.replace(oldChar, newChar)
replace all or just the first occurence?
- it replaces all the occurences
Arrays
- all variations on how to declare an array, also multidimensional arrays
- ways to instantiate:
int i[] = new int{1,2};
int i[] = {1,2};
- anonymous arrayint i[] = new int[2];
int i[][]= { {2,3},{1,2,3}};
int i[][]= new int[2][3];
int i[][]= new int[2][];
- this won’t compileint i[][]= new int[][];
- 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+
- how can you get an exception related to object type while operating on arrays? which exception is it?
- when you try to read from an array, and the declared type does not match the actual type, you get an
ArrayStoreException
- all variations on how to declare multiple array variables in one line
int[] a, b;
- two 1D arraysint[] a[], b[][];
- two arrays, one 2D and one 3D
- how is the array represented in the memory
- 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
- how to sort an array
java.util.Arrays.sort(array)
- what does
Arrays.binarySearch(array, what)
return in case it did not find the element
- value that is one smaller than the negative of index where such element would be, if it was there
Collections
- available constructors and methods on
ArrayList
- 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 returnstrue
void add(index, element)
- here is no booleanboolean remove(element)
Object remove(int index)
- be careful when you remove anint
element! it will resolve to this method instead of the one aboveremoveIf(Predicate)
Object set(index, Object)
boolean contains(Object)
equals()
(uses elements’equals()
)
- can you add
null
to anArrayList
- yes of course
- be careful though, as if you try to unbox it to a primitive value you will get a
NullPointerException
- what’s the deal with this conversion to array of custom type
list.toArray(new String[0])
, why would you be forced to create an empty array just to discard it later
- 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
- how to sort a
List
Collections.sort(list);
Wrapper types
parseInt()
andvalueOf()
- which one converts from which to which
Integer.parseInt()
createsint
out of many other types-
Integer.valueOf()
createsInteger
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 ifparseInt()
returned anInteger
it should be calledparseInteger()
- remember that
Character
does not participate in this stuff
Date and Time
- what are the new classes for representing date and time
LocalDate
,LocalTime
,LocalDateTime
, all injava.time.*
packageDateTimeException
- how to create custom date/time
LocalDate.now();
LocalDate.of(2015, Month.JANUARY, 1)
, same asLocalDate.of(2015, 1, 1)
LocalTime.of(6, 15);
LocalTime.of(6, 15, 30, 234);
- last one is nanosecondsLocalDateTime.of(2015, Month.JANUARY, 16, 15, 30);
LocalDateTime.of(date, time);
- how to manipulate 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
- what is
Period
andDuration
; what tricky thing was mentioned in the book about it
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 ofLocalDate/Time/TimeDate
- how to format date/time; what are the predefined formats; what is the default
dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
that resolves to2020-01-20T12:12:34
date.format(DateTimeFormatter.ISO_LOCAL_DATE)
dateTime.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT))
that resolves to1/20/2020
dateTime.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM))
that resolves toJan 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
- how to create a date/time from
String
- 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
- what exceptions were mentioned that are related to date/time, and which is thrown when
- there are two:
DateFormatException
- when you pass e.g. January 67thUnsupportedTemporalTypeException
- when you try to use time with date object, or date with time object
Exceptions
- errors, checked exceptions and runtime exceptions - who throws what and who catches what
Errors
- thrown by JVM, shouldn’t catchRuntimeException
- 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
- in implementing/overriding method, can we rather declare more or less exceptions than the superclass has
- checked exceptions - only less
- unchecked - doesn’t matter
- give examples of
RuntimeException
(6), checked exception (2) andError
(3)
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 exceptionStackOverflowError
NoClassDefFoundError
.. also, know that
- autoboxing does not work with
Predicate
s - there is Java process managed by JVM, and this process executes the
static void main
java.lang.*
is automatically imported- this is correct:
double i = 1_000_000.0
, but this not:double i = 1_000_000_.0
or doublei = _1_000_000.0
(also not) - Oracle claims that “Java prevents memory leaks”, and that “Java is secure because it runs inside JVM”, and that Java 8 is still an OO language
^
means XORif(objectOfTypeA==objectOfTypeB)
will not even compileString implements CharSequence
new StringBuilder(10)
is not"10"
but it is setting the initial capacity to10
StringBuffer
is just an old, thread-safe, slow version ofStringBuilder
- default constructors are automatically added to the
*.class
file by the compiler, and as soon as you write a default constructor yourself, it is no longer called a default constructor package private
access is synonym fordefault access
- lenient means permissive, merciful or tolerant
- it is allowed to catch
Error
s; it should not be done but it is allowed long x=(y=3)
is valid expression and it sets bothx
andy
to3
- if you get a question about number of code blocks, know that whether a block is nested inside another or not one doesn’t matter - total number of
{}
pairs counts finalize()
is called only once, on the first attempt to garbage collect the object (I actually just managed to almost freeze my computer by throwing aRuntimeException
in thefinalize()
method.. not what I expected..)
Comments
Want to leave a comment? Visit this post's issue page
on GitHub and just post your comment as the issue's comment (you'll need a GitHub account. What? Like you don't have one yet?!).
Comments: