OCA Flashcards

1
Q

Can you redeclare variables in the initialization block of the for loop?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Can you use more datatypes in the initialization block of a for loop?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Are immutable classes final or not?

A

They are final

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What happens with strings that are not in the string pool(they are not literals, hence, were created using “new”) when they are no longer used?

A

They are garbage collected, just like any other object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

True or false: Varargs are always allowed in place of an array

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What kind of operators can & have?

A

Integral and boolean

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does this code block print?

Class.forName(“not_a_real_class”)

A

ClassNotFoundException

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What objects types can be caught (as Exceptions)?

A

All Throwable instances

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What datatypes can be used as switch variables?

A

String, byte, char, short, int + their Wrappers, enum

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

True or false: a switch can contain two or more identical cases

A

False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Are java.time package classes mutable or immutable?

A

Immutable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

True or false: you can create arrays of any type, with length zero

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

True or false: subclasses can define methods with the same signature as the private methods in the base class. Justify.

A

True (since private methods are not inherited)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

True or false: polymorphism applies to both static and non-static methods.

A

False. When applied to static methods, it is called ‘method hiding’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Does an assigment executed inside the condition of a conditional block alter the assigned variable permanently?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Can a subclass override the superclass’ constructors? Justify

A

No, because constructors are NOT inherited

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

True or false: Any type of class can implement any interface

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

True or false: Any class(abstract/concrete) can extend any class

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

True or false: Native methods cannot be abstract

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

True or false: String, StringBuilder and StringBuffer cannot be extended. Justify.

A

True, because they are final

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

On what types of operands does % work?

A

Both integral and floating point

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

On what types of operands do !, && and || work?

A

Boolean

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

On what types of operands does ~(bitwise complement) work?

A

Only on integral types

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

True or false: A short variable can never be assigned to a char without explicit casting

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
True or false: A short constant can be assigned to a char, but only if the value fits into a char.
True
26
What is implicit narrowing and on what types does it work?
If you have a final variable and its value fits into a smaller type, then you can assign it without a cast because the compiler can already tell it can fit into the smaller type. It works only on byte, char, short and int.
27
Does int to float need a cast? Justify.
No, because float can hold any value of int
28
Does float to int need a cast? Justify.
Yes, because of the loss of precision
29
What happens when you use == on objects of different types? How about equals?
Compilation error. For equals(), it will always return false, because the compiler will know they cannot be the same object.
30
To what constructs can the 'synchronized' keyword be applied?
Methods and blocks
31
Are method parameters assigned default values?
No. Think of them as special local variables
32
True or false: you can call the superclass' constructor from any method in the subclass
False. It can only be called from one of the subclass' constructors
33
True or false: the call to the superclass' constructor can be called only as the first statement of the base class' constructor
True
34
What is the difference between super() and this()?
super() calls the base class' constructor, while this() calls the subclass' constructor
35
Will this compile? | if (false) ; else ;
Yes, because ; is the empty statement
36
Will this compile? | if(true) if(false);
Yes
37
When is a member with default access inherited?
When both classes are in the same package
38
Which things in a class never get inherited?
Constructors and static initializers, because they are NOT members
39
Can static methods be abstract? Justify.
No, because static methods are inherited, but can NOT be overriden (only hidden) in the subclass
40
What value does main() receive as argument if no parameter is passed to it?
A NON-null array of Strings, of length zero(it has zero elements).
41
What does this print: | System.out.println(1 + 2 + "ceva");
3ceva
42
What does this print: | System.out.println(1 + "ceva" + 2);
1ceva2
43
Give the method signature: returns the number of characters in the string
int length()
44
What is the name of the interface for String and StringBuilder?
CharSequence
45
Which one is slower and why: StringBuilder or StringBuffer?
StringBuffer, because it's thread safe
46
If you compare two Strings with ==, one of which is computed at runtime, what will be the result of the evaluation?
false
47
Does StringBuilder implement equals()?
NO
48
Do String and StringBuilder require imports?
NO
49
Are arrays stored on stack or on heap? Why?
Heap, because they are objects
50
Do array elements get initialized by default? If yes, what value do they get
Yes. They get the default value of the element type
51
Is equals() overriden for arrays?
No
52
Do object arrays allocate space for the element itself or the reference?
The reference
53
Does this have a default value or is it null (it's a local variable)? String names[];
null
54
Is this correct: Numbers sort before letters and uppercase sorts before lowercase
Yes
55
What is the order of initialization of a derived class? What about when we refer a class without a new call? Between the main and rules 1 and 2, which will run first?
1) Superclass 2) Static variable declarations and static initializers, in declaration order 3) Instance variable declarations and instance initializers, in declaration order 4) Constructor Then only rules 1 and 2 apply and they always run before the main
56
When are the static variable declarations and static initializers executed?
When the class is loaded (the loading takes place only if the class is used)
57
How would main()'s signature look like if you passed varargs to it?
public static void main(String… args)
58
Does ArrayList implement toString()
Yes
59
Do collections accept primitives?
NO
60
What happens when you try to unbox a null?
NullPointerException
61
How would you sort an ArrayList called "arli"?
Collections.sort(arli);
62
Can a file which imports another package access its package-private classes or class members?
No
63
Are methods shared or does each instance get its own copy?
They are shared
64
Protected = subclasses + package. In what situation do we get compilation errors for trying to access protected members?
When the class containing the member is in one package, and the class trying to access this member, on a class instance, is in a different package and this class is NOT a subclass of the class containing the member
65
Where can you initialize a static variable?
At the time of its declaration or in a static block
66
What are the mandatory and the optional changes in the method signature for method overloading?
Mandatory: something in the parameter list Optional: return type, access modifier, exception list
67
Does this code compile? Justify. public void fly(int[] lengths) { } public void fly(int... lengths) { }
No, because varargs and arrays are equivallent
68
Which can be called by passing an array? Which can be called by giving the elements directly? public void fly(int[] lengths) { } //1 public void fly(int... lengths) { } //2
Both can be called by passing an array, but only the varargs one can be used to pass the elements directly
69
What is the order in which Java chooses the right overloaded method? (hint: there are 4 argument categories)
1) Exact match by type 2) Larger primitive type 3) Autoboxed type 4) Varargs
70
Given this method signature: public void func(Long par) ``` Will this compile? Justify. func(4); ```
No, because 4 is an int. Java will convert it automatically to a long, but it can only do one conversion by itself, so it will not be able to autubox the long => compilation error
71
Knowing that the members of class Bird are protected, will this compile? Justify. ``` package pond.goose; import pond.shore.Bird; public class Goose extends Bird { public void helpGooseSwim() { Goose other = new Goose(); other.floatInWater(); System.out.println(other.text); } public void helpOtherGooseSwim() { Bird other = new Goose(); other.floatInWater(); System.out.println(other.text); } } ```
``` package pond.goose; import pond.shore.Bird; public class Goose extends Bird { public void helpGooseSwim() { Goose other = new Goose(); other.floatInWater(); System.out.println(other.text); } public void helpOtherGooseSwim() { Bird other = new Goose(); other.floatInWater(); // DOES NOT COMPILE System.out.println(other.text); // DOES NOT COMPILE } } ``` The problem is that we are trying to access protected members, from a different package, using a Bird reference. Protected access only works for subclasses and the same package, and, obviously, from within the defining class, but Bird is NOT a subclass of Bird, nor are we accessing it from the same package
72
Given that count is a static variabile of Koala, will this work? Koala k = null; System.out.println(k.count);
Yes
73
Which will run first if a static block calls the constructor?
The static block
74
What access modifiers can be added to a top-level class or interface?
Only public and default
75
Why is the parent constructor always executed before the child constructor?
Because the first call in a subclass' constructor will always be the call to the superclass' constructor
76
What are the 3 ways of calling an inherited member, called "member"?
1) member 2) this.member 3) super.member Be careful when 3) is used for accessing a subclass-only memeber => compilation error
77
What are the 4 rules for overriding a method?
1) It must have the same signature as the one in the base class 2) The method in the derived class must be at least, or MORE ACCESIBLE than the one in the base class 3) The method in the derived class must NOT throw a checked exception that is new or broader than the original exception 4) The return type may be a subclass of the original return type -> covariant return type
78
Can you overload in the derived class a method from the base class?
YES
79
Can an overriden method eliminate the original method's exception?
YES
80
What are the rules for method hiding?
The same for overriding + both the original and the overriding method contain the keyword "static"
81
Can you override final methods? Cand you hide final methods?
No. No
82
What is the difference between overriding and hiding, wrt to which method gets called at runtime?
Override = at runtime, the child version of a method is always called, unless both the reference and the value are of types Base Hiding = at runtime, the parent version is always called, unless explicitly called FROM WITHIN the child(ex: another method in the child calls the hidden method) OR when both the reference and the object are of type derived class(see ex on page 254, with the Kangaroo)
83
How would you access the supertype of a hidden variable called "hiddenVar"?
super.hiddenVar
84
Can you declare an abstract method in a concrete class?
NO
85
What modifiers can not be applied to abstract classes?
Private, final
86
What modifiers can not be applied to abstract methods?
Private, final
87
What are the rules for implementing an abstract method?
The same as for overriding a method
88
What are the legal modifiers for a top-level interface declaration?
Public, abstract, (default)
89
What are the legal modifiers for interface methods?
Public, abstract
90
What happens if a concrete class implements 2 interfaces, both of which declare the exact same method? What if they have different signatures? What if they have the same signature but different return types?
They will be considered duplicates of each other and it will be OK. It's ok, as long as you implement both It will NOT work
91
What happens if an interface or abstract class inherits from two conflicting interfaces?
Compiler error
92
Can you access an interface's attributes without an instance of the interface? Justify.
Yes, because they are static
93
Can you override a default method? How?
Just like overriding a normal method, just that the overriding method does not declare the method as default anymore
94
What happens if a class(concrete or abstract) implements two interfaces that have default methods with the same name and signature?
Compiler error
95
What is special about static methods in interfaces? What is the consequence of this thing if a class implements two interfaces containing static methods with the same signature?
They don't get inherited in classes implementing the interface. It's ok, because they are not inherited and can only be called in a static way
96
What happens when we change the reference of a type to a broader one?
Even though the value might be of the specialized type, by accessing it with a reference of a broader type we no longer have access to the fields and operations of the derived class
97
Do interfaces inherit Object? Justify
NO, because interfaces can only inherit other interfaces
98
W.r.t the Exception class hierarchy, what is an unchecked exception and what is a checked exception?
Unchecked = unchecked by the compiler => runtime exceptions. These are exceptions that extend java.lang.RuntimeException Checked = Exceptions that extend java.lang.Exception, but NOT java.lang.RuntimeException
99
What happens if the catch block for the superclass is first and the catch block for the subclass is second?
Unreachable code => compiler error
100
Can try-catch blocks be nested?
YES
101
How many catch blocks can run per try-catch block?
ONLY ONE
102
If you throw an exception that you dont' catch, then the finally block throws a different exception, what will happen?
Only the last exception will be thrown? This is why we sometimes see try-catch blocks inside finally, to make sure the first exception doesn't get forgotten about
103
``` What will this print? -> explain public String exceptions() { String result = ""; String v = null; try { try { result += "before"; v.length(); result += "after"; } catch (NullPointerException e) { result += "catch"; throw new RuntimeException(); } finally { result += "finally"; throw new Exception(); } } catch (Exception e) { result += "done"; } return result; } ```
beforecatchfinallydone Because first the innermost block has to finish(including the finally)
104
Who can throw RuntimeExceptions?
The programmer and the JVM
105
Who can throw checked exceptions?
The programmer and the JVM
106
Who can throw errors?
Only the JVM
107
Which type of exceptions are these? ArithmeticException - Thrown by the JVM when code attempts to divide by zero ArrayIndexOutOfBoundsException - Thrown by the JVM when code uses an illegal index to access an array ClassCastException - Thrown by the JVM when an attempt is made to cast a class to a subclass of which it is not an instance IllegalArgumentException - Thrown by the programmer to indicate that a method has been passed an illegal or inappropriate argument NullPointerException - Thrown by the JVM when there is a null reference where an object is required NumberFormatException - Thrown by the programmer when an attempt is made to convert a string to a numeric type but the string doesn’t have an appropriate format
Runtime: ``` ArithmeticException ArrayIndexOutOfBoundsException ClassCastException IllegalArgumentException Thrown NullPointerException NumberFormatException Thrown ```
108
Which type of exceptions are these? FileNotFoundException - Thrown programmatically when code tries to reference a file that does not exist IOException - Thrown programmatically when there’s a problem reading or writing a fi le
Checked exceptions Keep in mind that FileNotFoundException is a subclass of IOException !
109
Remember these errors: ExceptionInInitializerError - Thrown by the JVM when a static initializer throws an exception and doesn’t handle it StackOverflowError - Thrown by the JVM when a method calls itself too many times NoClassDefFoundError - Thrown by the JVM when a class that the code uses is available at compile time but not runtime
Errors: ExceptionInInitializerError StackOverflowError NoClassDefFoundError
110
What happens if you declare an unused exception?
It's OK
111
What happens if you attempt to catch an exception which cannot get thrown from the try block?
Compiler error
112
Is an overriding method allowed to throw more exceptions than the original one? If yes, in what situation?
Yes, but this only works with Runtime exceptions
113
Are you allowed to handle errors?
Yes, but it's not indicated
114
What are the 3 legal ways of printing an exception named 'e' ?
System.out.println(e); System.out.println(e.getMessage()); e.printStackTrace();
115
What objects can be declared in the throws part of a method declaration?
Any Throwable
116
True or false: If you throw more exceptions, only the last one’s stack trace will be printed? Justify.
True, because only the last one will be taken into account
117
Can you declare RuntimeExceptions in the catch, even if the try clause doesn’t throw them ? Can you do this for checked ones?
Yes, because they are optional anyway. | No, because that catch will be considered unreachable code
118
Can main() declare that it throws checked exceptions?
YES
119
Is a=b=3 a legal statement? Justify.
Yes, but only if both the variables have already been declared. Ex that will still work: int b; int a = b = 3;
120
Will this work? | System.out.print(null);
YES. It will print "null"
121
Can you directly invoke the GC?
No, but you can suggest JVM to perform GC by calling System.gc();
122
Does Math.round() round up or down?
UP
123
Which operator has the least precedence(is evaluated last) ?
The assignment operator
124
What happens if we change the return type of main()?
RUNTIME EXCEPTION
125
What happens if we remove static from the declaration of main()?
RUNTIME EXCEPTION
126
Which has higher precedence? . OR cast()?
.
127
Can Wrapper classes be extended? Justify.
No, because they are final
128
Do lambdas create a new scope for variables?
NO
129
Does covariant return type apply to primitives?
NO
130
Will this work? Justify. int[] arr = null; System.out.print(arr.length); *
No, it will throw NPE, because we are trying to access a field on a null reference
131
Will this work? Justify. int[] arr = null; System.out.print(arr.length);
No, it will throw NPE, because we are trying to access a field on a null reference
132
Will this work? Justify. int[] arr = null; arr[0] = 4;
No, it will throw NPE, because the array is null
133
Can you throw null as if it were a Throwable value?
No. It will throw NPE
134
Will this work? Justify. public static void main(String args[]){ throw null; }
No. It will not compile, because we are throwing an exception but not declaring a throws or enclosing it in a try-catch
135
Will this work? Justify. public static void main(String args[]){ ArithmeticException ex = null; throw ex; }
No. It will not compile, because we are throwing an exception but not declaring a throws or enclosing it in a try-catch
136
Will this work? Justify. | long g = 012 ;
Yes, because it's a valid octal number
137
Will this work? Justify. | float f = -123;
Yes, because implicit windening conversion from int to float happens in this case, so we don't need the decimal point
138
Are wrapper classes final?
Yes
139
Is java.lang.Number final?
NO
140
Is java.lang.System final?
Yes
141
When a class whose members should be accessible only to members of that class is coded such a way that its members are accessible to other classes as well, this is called ...
weak encapsulation
142
Which elements compose the method signature?
The name and the parameter list
143
Does the the method signature include the return type?
NO
144
Will the finally clause still be executed if we have a labeled break inside the try? Will the break work?
YES. Yes, because a break without a label breaks the current loop (i.e. no iterations any more) and a break with a label tries to pass the control to the given label.
145
What is a byte's range?
-128 to 127.
146
``` What is the result of evalutating each of these? Justify. new Boolean("true") == new Boolean("true"); new Boolean("false") == false; new Boolean("true") == Boolean.parseBoolean("true"); ```
false, true, true. Because if exactly one operand is a wrapper type, it is first unboxed to its primitive version and then the comparison takes place. If both of them are references, it compares by reference
147
What does Boolean(String) return and what are the conditions?
new Boolean("true") if the argument is not null and equalsIgnoreCase("true"); otherwise, new Boolean("false") -> Object
148
What does Boolean(boolean) return and what are the conditions?
new Boolean("true") / new Boolean("false") - obviously
149
What does Boolean.parseBoolean(String) return and what are the conditions?
true, if the argument is not null and equalsIgnoreCase("true"); otherwise, false -> Primitive
150
What does Boolean.valueOf(String) return and what are the conditions?
Boolean.TRUE, if the argument is not null and equalsIgnoreCase("true"); otherwise, Boolean.FALSE -> Static constant
151
What does Boolean.valueOf(boolean) return and what are the conditions?
Boolean.TRUE / Boolean.FALSE -> Static constant
152
Will this work? Justify. | while(false) { int x = 4; };
No, because the body of the loop is seen by the compiler as unreachable code
153
Is Throwable a class or an interface?
Class
154
Will this work? Explain how the code is executed int i; int[] arr = new arr[5]; arr[i] = i = 3*10;
Yes. 1) Evaluate the LHS (arr[i] becomes arr[0]) 2) Evaluate all remaining operands which are expressions 3) Evaluate based on order imposed by paranteses and precedence(not the case) 4) Evaluate assignments right to left
155
Which of these will compile, assuming the following declarations? Justify. Object o = null; Collection c = //valid collection obj int[][] ia = //valid array obj 1) for(o : c){} 2) for(final Object o2 :c) {} 3) for(Iterator it : c.iterator()) {} 4) for (int i : ia[0]) {}
1) No, because you cannot use an already existing variable in the declaration part, as this would mean redeclaring it 2) Yes. Final and annotations are permitted there 3) No, because c.iterator() returns an iterator, not a collection 4) Yes
156
Will this work? Justify. ``` public class Square(){ private int side; ``` ``` public static void main(String[] args){ Square sq = new Square(); sq.side = 6; //will this work? (1) side = 4; //will this work? (2) } } ```
1) Yes, because although the field is private, main is considered a method of this class, so it will have access to it 2) No, because in Java we don't have the concept of global variable
157
What is the default datatype for integral literals?
int
158
What is the default datatype for floating point literals?
double
159
Which of these will work? ``` float f1 = 1.0; float f2 = 43e1; float f3 = -1; float f4 = Ox123; float f5 = 4; ```
float f1 = 1.0; // fail - implicit casting not possible for float float f2 = 43e1; // fail - implicit casting not possible for float float f3 = -1; // pass - implicit casting from int to float done float f4 = Ox123; // pass - implicit casting from hex int to float done float f4 = 4; // pass - implicit casting from int to float done
160
``` Will this work? Justify interface I1 {} interface I2 {} class C1 implements I1 {} class C3 extends C1 implements I2 {} class C4 extends C3 implements I1, I2 ```
Yes. We have redundancy, but it will still work
161
Does String have method .append()?
NO
162
Which of these will be called when doing this: printSum(1, 2) , ? Justify. printSum(double, double); printSum(float, float) ;
printSum(float, float) , because int is closer to float than to double
163
Would such a structure compile? | for(int i=0; i++<5; System.out.println(i));
YES
164
Will this work? Justify. | String String = "String";
Yes, because class names, even built-in ones, are not keywords, so they can be used
165
Will this compile? Justify. String String  = "test"; System.out.println(String.length());
Yes. When a local variable has the same name as a class, the local variable will be considered
166
Can a static field be private?
Yes
167
Do final fields get a default value?
NO. A final variable must be initialized when an instance is constructed, or else the code will not compile. This can be done either in an instance initializer or in EVERY constructor.
168
Can an import appear before a package statement?
NO
169
True or false: All operands of type byte, char or short are promoted at least to an int before performing mathematical operations.
True
170
Can charAt( ) take a char value as an argument? Justify.
Yes, because it will be implicitly promoted to int
171
Is this true about charAt()? It throws ArrayIndexOutOfBoundsException if passed a value higher than or equal to the length of the string (or less than 0).
False. It throws IndexOutOfBoundsException. It actually throws StringIndexOutOfBoundsException, but it seems that this is the correct answer on the exam
172
``` Will this work? class B extends A{ public static void sM1() { } public void sM1() { } } ```
No
173
``` Will this work? public class TestClass { public static void main(String[] args) { ``` boolean hasParams = (args == null ? false : true); if(hasParams){ System.out.println("has params"); }{ System.out.println("no params"); } } }
Yes. The block with "no params" will always be executed and it's valid syntax
174
Which will compile? Justify. System.out.println(null + true); //1 System.out.println(true + null); //2 System.out.println(null + null); //3
None, because none of the parameters is a String, so the + will not concatenate them, and we cannot perform addition on booleans and nulls
175
Which has bigger precendence: parantheses or arr[x]?
Parantheses