OCAJP 8 (IZ0-808)

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What methods does the String class have (most important)? Also don't forget that the class has implemented the Comparator CASE_INSENSITIVE_ORDER!

length() : int isEmpty() : boolean charAt(int) : char equals(Object) : boolean equalsIgnoreCase(String) : boolean startsWith(String) : boolean endsWith(String) : boolean indexOf(int) : int indexOf(int char, int fromIndex) : int indexOf(String) : int indexOf(String, int fromIndex) : int substring(int) : String substring(int beginIndex, int endIndex) : String concat(String) : String replace(char old, char new) : String --> no change = same String object replace(String old, String new) : String --> always returns a new String object contains(CharSequence) : boolean trim() : String valueOf(Object) : String toString() : String intern() : String

Given: private Integer myInt = 5; m(Integer i) { ... } m(int i) { ... } m(long l) { ... } m(int... i) { ... } If 'm(myInt);' is called somewhere, in what order will the methods be preferred?

m(Integer i) { ... } m(int i) { ... } m(long l) { ... } m(int... i) { ... }

Given: a variable without access modifier. Is a protected more or less visible?

more public > protected > default > private

What to look for if switch is used on a char?

negative cases (-1, -2, ...) don't compile! e.g. switch (myChar) { case -1: // nope! ... }

Given: a[m()][i=1]; What happens if m() throws an Exception?

no part of any dimension expression will be evaluated, so 'i=1' won't execute

Is a constructor static or non-static?

non-static

Given: final MyObject obj = new MyObject(); What's possible to change here, what not?

obj.vars can be changed, the obj itself not, e.g. obj.size = 10; // possible obj = null; // not possible

When to use enhanced for loops? e.g. for (char c : charArray) { ... }

only if (processing-through) order doesn't need to be changed

Given: List<String> list = new ArrayList<>(); Which one is the reference type, which the object type?

reference type: - 'List<String>', the variable data type (left) object type: - 'ArrayList', the assigning object data type (right)

List<String> list = new ArrayList<>(); Which one is the reference type/object type?

reference type: List<String> object type: ArrayList

Given: List<String> list = new ArrayList<>(); String s = list.getClass().toString(); What value will 's' have?

s = "class java.util.ArrayList"; The method getClass() always returns the class of the current object, irrespective of its reference type.

Can static methods reference to non-static fields? What about non-static methods to static fields?

static methods: - to non-static fields: NOT POSSIBLE - to static fields: possible non-static methods: - to static fields: possible - to non-static fields: possible

Where can 'break' be used where 'continue' can't?

switch

What happens if two variables are calculated together with operands like + - / *? How is it with compound assignment operators (+= *= etc)?

they get promoted (auto-casted) to at least int compound: auto-casted to reference type e.g. byte b *= 5 --> byte b = (byte)(b * 5)

How to call nonStaticMethod() from a non-static block?

this.nonStaticMethod(); nonStaticMethod();

Given: interface I2 { default m1(); default m2() { ... } static m3(); static m4() { ... } m5(); m6() { ... } } What method declarations are valid, which not?

valid: default m2() { ... } static m4() { ... } m5(); invalid: default m1(); static m2(); m6() { ... } In general: m() of interface that are not default or static never have a { ... } body but a ';' instead.

What data types are valid inside a switch, what not?

valid: - String, byte, char, short, int, enum - wrappers of these (Byte, Char, ...) invalid: - double, float, long, bool

What and where is the keyword 'default' used for?

where: only for interface methods what for: implementing methods inside interaces

Where and what is the keyword 'native' used for?

where: only for methods what for: for calling native code (C, C++, FORTRAN, or Assembly), e.g. native int square(int param);

Where can the keyword 'continue' be used and where not?

where: - while - do - for not: - switch

Where can the keyword 'break' be used and where not?

where: - while - do - for - switch

Given: [static] final int size; Where can a value of 'size' be set?

- { ... } / static { ... } - constructor - directly: final int size = 10;

What operators are right-associative?

?: ternary = apart from that, every operator is left-associative or directly associated with its object (unary) m1() + m2(m3() + m4()) is evaluated like: m1, m3, m4, m2

What is an unsigned integer?

A positive integer. Unsigned = capable of representing only non-negative integers.

How to call nonStaticMethod() from a static block?

ClassName cn = new ClassName(); cn.nonStaticMethod();

Which collection subclass doesn't implement Iterable and what's the consequence of it?

Map --> enhanced for loops can't iterate over it directly

Where is the return type of a m() defined?

always directly before, e.g. public int m() { ... }

Given: int i = 4; int iA[][][] = new int[i][i = 3][i]; With what lengths will iA be instantiated?

int iA[][][] = new int[4][3][3] dimension expressions are, like most, evaluated left-to-right

Given: I2 a = obj; I2 is an interface, obj an object. Is this code valid?

yes!

Given: for(int i = 0; Boolean.TRUE; i++) { ... } is this code valid?

yes, all loops also accept the boolean wrapper object

If there's a 'break' statement inside a nested loop, where does the program jump to after executing it?

'break' always breaks the innermost loop, so it jumps just right after that loop

Given: ((I)var).m(); ((A)var).m(); Assume that I is an interface and A a class. What can be said about this code?

((I)var).m() is illegal --> use I.m() instead ((A)var).m() works

What are the most important RuntimeExceptions?

- ArrayIndexOutOfBoundsException - StringIndexOutOfBoundsException - NullPointerException - ClassCastException - IllegalArgumentException - DateTimeException --> DateTimeParseException

What are subclasses of the class Throwable?

- Error - Exception Note: RuntimeException is a subclass of Exception!

What are the most important Exceptions?

- IOException --> FileNotFoundException

What are the most important Errors?

- OutOfMemoryError - ExceptionInInitializerError* - StackOverflowError** * = if from { ... } and static { ... }, used as wrapper since only RuntimeExceptions can be thrown from this context ** = appears if recursive calls never end

Which of the following data types are final? - String - char, byte, short, int, long, double, float - Character, Byte, Short, Integer, Long, Double, Float - StringBuilder - StringBuffer - Number

- String - Character, Byte, Short, Integer, Long, Double, Float - StringBuilder - StringBuffer

Given: boolean b1 = myInt.equals(myLong); boolean b2 = myInt == myLong; What can you say about these two lines of code?

- The first line always equals to false since the equals() method of wrapper classes only compare values if they're in the same class - The second line results in a compilation error since '==' is only used for primitives

What do you know about the char values of a-z, A-Z and 0-9?

- They all are below the value 127 and can therefore be assigned to a byte without explicit casting. - The uppercase letters always hold the same value of its lowercase letter equivalent MINUS 32. So e.g. the following expression returns true: 'a' - 32 == 'A'

What's the MAX_VALUE for following data types: - byte - char - short - int - long

- byte: 127 - char: 65536 (4^16 --> chars range from \u0000 to \uFFFF, 16 possible values for each) - short: 32767 (2^15-1) - int: 2^31-1 - long: 2^63-1

What happens with following loops? - for(int i = 0; false; i++) { ... } - while(false) { ... } - for(int i = 0; returnsFalse(); i++) { ... } - while(returnsFalse()) { ... } - do { ... } while(false)

- first two loops don't even compile as there is unreachable code - the second two loops are not even once stepped through since their conditions already equal to false - the last loop steps through once

How is a staticMethod() of MyClass inside 'test' imported?

- import static test.MyClass.staticMethod; - import static test.MyClass.*;

How is a nonStaticMethod() of MyClass inside 'test' imported?

- import test.*; - import test.MyClass;

Where are protected variables accessible?

- inside same package - in subclasses

What packages are always auto-imported?

- java.lang.* - packages without names

What to look for in a try/catch?

- most specific Exception must always come first - finally will always execute* - a try always needs at least a catch or finally - catch param can be anything that is-a Throwable

What can be said regarding the following method attributes when overloading the method? - name - params - return type

- name: remains - params: change - return type: is irrelevant

What attributes do interface fields always have?

- public - static - final = values not modifiable (constants)!

What can you say about LocalDate?

- the class is immutable - it has no setters and only private constructors - it's ISO-8601 formatted (yyyy-MM-dd) - it doesn't store times (LocalDateTime) and zone infos (ZonedDateTime) - its parsing functions throw RuntimeExceptions (DateTimeParseException)

What steps does the compiler go through when evaluating expressions?

1. Evaluate Left-Hand Operand First 2. Evaluate Operands before Operation 3. Evaluation Respects Parentheses and Precedence 4. Argument Lists are Evaluated Left-to-Right

What are checked exceptions?

All Exceptions except RuntimeExceptions.

How to call staticMethod() from a static block?

ClassName.staticMethod(); staticMethod();

How to call staticMethod() from a non-static block?

ClassName.staticMethod(); staticMethod(); this.staticMethod(); // this.staticVar also possible in this context!

What's the concept behind encapsulation?

Classes expose only certain fields and methods to other classes for access. Good encapsulation: - private field variables - public/protected getters and setters.

Given: date.plus(Duration.ofDays(1)); date.plus(Period.ofDays(1)); What's the difference?

Duration.ofDays(1): - adds exact numbers, ignoring DST (Sommer-/Winterzeit) Period.ofDays(1): - adds a conceptual day

How does implicit narrowing work and with what data types?

Implicit narrowing auto-casts values to the according data type if they are representable by that data type, e.g. the expression 'byte b = 1;' will be processed like this: 'byte b = (byte) 1;' This works with byte, char, short and int. This doesn't work though with float and double, so 'float f = 1;' ends up in a compilation error.

What are instance members?

Instance members are variables, constants and method of its object (not class). So basically everything that isn't static.

Given: private Integer myInt = 5; m(int... i) { ... } m(int i) { ... } m(long l) { ... } m(Integer i) { ... } If 'm(myInt);' gets executed, in what order will the given methods be preferred?

Integer > int > long > int...

What is a functional interface and how does it work?

It's an interface that contains exactly one abstract method. It may contain default/static methods. It's used to provide a method that works with any object. Since it only has 1 method, the compiler knows which one to use, it's name can therefore be ommited. e.g. interface Predicate<T> { boolean test(T t); } --> Used for lambdas!

What's special about java.lang.Number?

It's not final, since the wrappers of int, double and float all extend it.

Given: int[] iArray = new int[0]; int[0] iArray2; What can be said about the given int arrays?

Java allows zero-length arrays, so '... new int[0]' is allowed. However, the size of an array can't be declared before it's instantiation

What's the benefit if a variable is final regarding conversions?

No / less casting needed since the compiler already knows its value.

Do default and static methods need to be implemented by subinterfaces?

No!

Given: try { throw new MyException(); } catch (MyException e) { throw new MyException2(); } catch (MyException2 e) { ... } Will the thrown MyException2() get caught?

No!

Given: float f = 43e1; Does this work?

No! '43e1' is a double, so this code is invalid.

Given: private static int i = 5; static int m() { return this.i; } Does this work?

No! Compilation error. The keyword 'this' doesn't work in a static context.

Can a static method be overridden by non-static methods? Can a non-static method be overridden by static methods?

No! No! A static method can never be overridden by a non-static method & vice versa

Given: class A { static int i = 5; { // Line 1 } } class B extends A { void m() { int y = i; ... } { // Line 2 } } Will the lines 1 and 2 be executed?

No! Only line 1. References to static variables do only initialize the class that declares it.

Given: int i = Integer.parseInt(12.3); Does this work?

No. The method parseInt(...) only accepts integers (Ganzzahlen) in form of a String or digits.

Given: byte b = 130; Does this work?

No. This expression needs to be explicitly casted e.g. 'byte b = (byte) 130;' This will assign 'b' to '-126' (Byte.MIN_VALUE is '-128'), so it simply adds the overflowing amount to the MIN_VALUE.

Where are variables with the keyword 'abstract' allowed?

Nowhere! --> only for methods and classes

Where is an abstractMethod() allowed?

Only inside an abstract class!

Where does the keyword 'default' occur?

Only on interface methods.

Where does the keyword 'abstract' occur?

Only on methods (not mandatory!) inside abstract classes. Note: Abstract methods don't have a { ... } body. Also keep in mind that abstract classes still are able to implement some or all methods.

Given: Period.of(...) Duration.of(...) Do you know their parameters?

Period.of( int years, int months, int days ) Duration.of( long amount, ChronoUnit.<DAYS|...> )

Given: System.out.println(null); System.out.println(null + true); System.out.println(null + "a"); What can be said about the 3 code lines?

System.out.println(null); --> doesn't compile (char[] or String param?) System.out.println(null + true); --> doesn't compile (operator '+' can't be applied to null and sth else!) System.out.println(null + "a"); --> only way 'null' works with '+'!

Given: public int m() {... } int public m() {... } What can you say about the code lines on top?

The return type always needs to be declared directly before the method name. public int m() {... } <-- valid int public m() {... } <-- invalid

How do the constructors of wrapper classes of primitives look like?

They all have params, so having no params is invalid! Note that the constructors always expect the corresponding primitive data types, e.g. new Short(...) expects a short. So these never allow int values without explicit casting! new Short((short)1); <-- valid new Short(1); <-- invalid!

Whats the main difference between the StringBuilder and String class?

They have different methods but most importantly, String is immutable while StringBuilder is not! This has following consequences: - a StringBuilder object passed to another method might change the original object while passed Strings don't - changes to a String only apply if they are directly set to the original String, e.g. str = str.substring(4);

Why does ArrayList implement the Interface RandomAccess?

This is to indicate that it supports fast random access. Meaning: The following code... for (int i=0, n=list.size(); i < n; i++) list.get(i); ... runs faster than iterating over it with an Iterator (rule of thumb).

Is it possible to call methods on parent-interfaces?

Yes! super(); --> Interface.super(); super.m(); --> Interface.super.m();

Given: boolean b = false; if (b = true) { ... } if (b = true != b) { ... } Does this work?

Yes! Assignment statements always return the assigned value. The if needs a boolean expression which is provided by both boolean assignments.

Given: private static int i = 5; int m() { return this.i; } Does this work?

Yes! But a 'this' before a static variable only works, if the variable and the method are in the same class. The reason behind is, that 'this' represents the current class instance. So it's actually the same as 'MyClass.i'.

Given: interface I1 { int i = 5; m(); } interface I2 { int i = 5; m(); } Is it possible to implement both interfaces by the same class?

Yes! Having ambiguous fields or methods does not cause any problems, but referring to them does (compilation error).

Given: private int i; void m() { i++; } Does this code compile?

Yes! Instance variables get a default value if they're not initialized, so here 'i' will be set to '0', the method 'm()' can therefore always increment it by 1.

Can a default method be redeclared by a subinterface? What if it's redeclared as abstract by a class?

Yes! It also can be redeclared as abstract e.g. no m() body.

How does an abstractMethod() look like?

abstract abstractMethod(); // never has a body! Don't forget the semicolon!

Where are underscores for allowed and where not?

allowed: - between digits invalid: - before or after a dot or 'L', 'F', 'D' e.g. _L or _.

What methods does the StringBuilder class have (most important)?

append(Object) append(String, int start, int end) delete(int start, int end) replace(int start, int end, String str) insert(int offset, String str, int start, int end) insert(int offset, String str) insert(int, Object) indexOf(String) : int indexOf(int char, int fromIndex) : int reverse() toString() : String charAt(int) : char <-- also accepts chars obviously setLength(int) : void <-- <-- length longer than current: fills remaining chars with \u0000 length() : int capacity() : int ensureCapacity(int) : void substring(int) : String substring(int start, int end) : String equals(Object) : boolean

Given: Boolean.parseBoolean(...) Boolean.valueOf(...) Which one returns a boolean, which a Boolean?

boolean: - Boolean.valueOf(...) Boolean: - Boolean.parseBoolean(...)

What's the order of primitive data types regarding to the amount of values they can hold?

byte < short < int < double < float

What are exceptions good for?

customization: - allow creation of custom exceptions logic separation: - exceptions are separated from the main program logic

What labels for labelled breaks/continues are not working?

every label with a Java keyword, e.g. - for - do - while - if - break

Given: new Boolean("true") == new Boolean("true") What does the statement on top return?

false

When and what for is 'instanceof' used?

for Objects to check it for it's class, e.g. if (obj instanceof MyClass) { ... } Note: Doesn't work for primitives. Also consider that obj is always left, MyClass right!

What methods does the ArrayList class have (most important)?

get(int) : T set(int, T) : T add(T) : boolean add(int, T) : void addAll(Collection) : boolean addAll(int, Collection) : boolean remove(int) : T remove(Object) : boolean removeIf(Predicate) : boolean clear() : void subList(int from, int to) : List indexOf(Object) : int contains(Object) : boolean

How are packages imported?

import [static] package.MyClass.<field>; import [static] package.MyClass.*;

What methods do String and StringBuilder have in common?

indexOf(String) : int indexOf(int char, int fromIndex) : int length() : int charAt(int) : char substring(int) : String substring(int beginIndex, int endIndex) : String toString() : String replace(...) <-- different parameters though! equals(Object) : boolean

What to look for if switch is used on an int?

it can be used with other data types as well. They need to be assignable to an int though switch (myInt) { case 'a': // works! case myByte: // works! case myShort: // works! ... }

What does the ArrayList inherit from?

java.lang.Object - java.util.AbstractCollection<E> - java.util.AbstractList<E>


Set pelajaran terkait

Poetry: Cambridge English AS Level Songs of Ourselves

View Set

Abeka English 10- Poetry Quiz 4 ("Ozymandias")

View Set

environmental science a - unit 3: bionomics

View Set