Methods Flashcards
What about methods with same name, but they have wrapping class and primitive as only parameters?
It is allowed for them to exist in same class:
public void method(int a) {}
public void method(Integer a) {}
public void method(Integer[] a) {}
public void method(int[] a) {}
Same goes for arrays, but not varargs and arrays
What happens when we set a value to autobox and numeric promote?
Java wont do both at the same time, it can ether autobox or numeric promote smaller value to bigger. Eg.
Long l = 9 wont compile.
long l = 9 will.
Same applies for methods:
method(Long a) <- method(9) wont compile
What is alternative to autoboxing and unboxing?
Depending on value type:
Integer i1 = Integer.valueOf(int) is autoboxing
int i2 = i1.intValue() is unboxing
How can we get NullpointerException while unboxing?
When we try to unbox a wrapper class that is null to primitive
Are varargs and arrays interchangeable?
Yes.
new boolean[2] -> boolean…
method(new int[] { 1, 2, 3 }) is also valid.
What is position where varargs need to be when used as parameters?
At the end
Can varargs have … before name of the varargs?
No, they must be after the name.
args… O
…args X
What is rule for initializing static final class member?
It can be initialized only once, second time will throw compile error. So they can be inited directly inline or with static blocks, but only once.
What are rules for package access methods?
If class is public, then it can be initialized from anywhere, but if it contains package access protected methods, they can be only ran from inside the same package.
This access type is more restrictive than protected.
What modifiers can instance variable have?
static
transient
volatile
final
What access modifiers are there?
public
protected
package protected
private
What optional modifiers can methods have?
synchronized
final
static
abstract
default
What do we need to watch out when using final with instance variables?
We must initialize its value before it is used, in instance variable case, before constructor call ends. In static class members, before usage or end of the class.
What do we need to watch out regarding modifiers?
Optional modifiers can come before other modifiers
Can “final” and “var” be used together?
Yes, but only in method bodies.