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
Q

True or false: A short constant can be assigned to a char, but only if the value fits into a char.

A

True

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

What is implicit narrowing and on what types does it work?

A

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.

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

Does int to float need a cast? Justify.

A

No, because float can hold any value of int

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

Does float to int need a cast? Justify.

A

Yes, because of the loss of precision

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

What happens when you use == on objects of different types? How about equals?

A

Compilation error. For equals(), it will always return false, because the compiler will know they cannot be the same object.

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

To what constructs can the ‘synchronized’ keyword be applied?

A

Methods and blocks

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

Are method parameters assigned default values?

A

No. Think of them as special local variables

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

True or false: you can call the superclass’ constructor from any method in the subclass

A

False. It can only be called from one of the subclass’ constructors

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

True or false: the call to the superclass’ constructor can be called only as the first statement of the base class’ constructor

A

True

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

What is the difference between super() and this()?

A

super() calls the base class’ constructor, while this() calls the subclass’ constructor

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

Will this compile?

if (false) ; else ;

A

Yes, because ; is the empty statement

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

Will this compile?

if(true) if(false);

A

Yes

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

When is a member with default access inherited?

A

When both classes are in the same package

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

Which things in a class never get inherited?

A

Constructors and static initializers, because they are NOT members

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

Can static methods be abstract? Justify.

A

No, because static methods are inherited, but can NOT be overriden (only hidden) in the subclass

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

What value does main() receive as argument if no parameter is passed to it?

A

A NON-null array of Strings, of length zero(it has zero elements).

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

What does this print:

System.out.println(1 + 2 + “ceva”);

A

3ceva

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

What does this print:

System.out.println(1 + “ceva” + 2);

A

1ceva2

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

Give the method signature: returns the number of characters in the string

A

int length()

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

What is the name of the interface for String and StringBuilder?

A

CharSequence

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

Which one is slower and why: StringBuilder or StringBuffer?

A

StringBuffer, because it’s thread safe

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

If you compare two Strings with ==, one of which is computed at runtime, what will be the result of the evaluation?

A

false

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

Does StringBuilder implement equals()?

A

NO

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

Do String and StringBuilder require imports?

A

NO

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

Are arrays stored on stack or on heap? Why?

A

Heap, because they are objects

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

Do array elements get initialized by default? If yes, what value do they get

A

Yes. They get the default value of the element type

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

Is equals() overriden for arrays?

A

No

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

Do object arrays allocate space for the element itself or the reference?

A

The reference

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

Does this have a default value or is it null (it’s a local variable)?
String names[];

A

null

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

Is this correct: Numbers sort before letters and uppercase sorts before lowercase

A

Yes

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

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?

A

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

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

When are the static variable declarations and static initializers executed?

A

When the class is loaded (the loading takes place only if the class is used)

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

How would main()’s signature look like if you passed varargs to it?

A

public static void main(String… args)

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

Does ArrayList implement toString()

A

Yes

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

Do collections accept primitives?

A

NO

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

What happens when you try to unbox a null?

A

NullPointerException

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

How would you sort an ArrayList called “arli”?

A

Collections.sort(arli);

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

Can a file which imports another package access its package-private classes or class members?

A

No

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

Are methods shared or does each instance get its own copy?

A

They are shared

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

Protected = subclasses + package. In what situation do we get compilation errors for trying to access protected members?

A

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

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

Where can you initialize a static variable?

A

At the time of its declaration or in a static block

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

What are the mandatory and the optional changes in the method signature for method overloading?

A

Mandatory: something in the parameter list
Optional: return type, access modifier, exception list

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

Does this code compile? Justify.
public void fly(int[] lengths) { }
public void fly(int… lengths) { }

A

No, because varargs and arrays are equivallent

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

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

A

Both can be called by passing an array, but only the varargs one can be used to pass the elements directly

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

What is the order in which Java chooses the right overloaded method? (hint: there are 4 argument categories)

A

1) Exact match by type
2) Larger primitive type
3) Autoboxed type
4) Varargs

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

Given this method signature:
public void func(Long par)

Will this compile? Justify.
func(4);
A

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

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

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); 
    }
 }
A
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
Q

Given that count is a static variabile of Koala, will this work?
Koala k = null;
System.out.println(k.count);

A

Yes

73
Q

Which will run first if a static block calls the constructor?

A

The static block

74
Q

What access modifiers can be added to a top-level class or interface?

A

Only public and default

75
Q

Why is the parent constructor always executed before the child constructor?

A

Because the first call in a subclass’ constructor will always be the call to the superclass’ constructor

76
Q

What are the 3 ways of calling an inherited member, called “member”?

A

1) member
2) this.member
3) super.member

Be careful when 3) is used for accessing a subclass-only memeber => compilation error

77
Q

What are the 4 rules for overriding a method?

A

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
Q

Can you overload in the derived class a method from the base class?

A

YES

79
Q

Can an overriden method eliminate the original method’s exception?

A

YES

80
Q

What are the rules for method hiding?

A

The same for overriding + both the original and the overriding method contain the keyword “static”

81
Q

Can you override final methods? Cand you hide final methods?

A

No. No

82
Q

What is the difference between overriding and hiding, wrt to which method gets called at runtime?

A

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
Q

How would you access the supertype of a hidden variable called “hiddenVar”?

A

super.hiddenVar

84
Q

Can you declare an abstract method in a concrete class?

A

NO

85
Q

What modifiers can not be applied to abstract classes?

A

Private, final

86
Q

What modifiers can not be applied to abstract methods?

A

Private, final

87
Q

What are the rules for implementing an abstract method?

A

The same as for overriding a method

88
Q

What are the legal modifiers for a top-level interface declaration?

A

Public, abstract, (default)

89
Q

What are the legal modifiers for interface methods?

A

Public, abstract

90
Q

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?

A

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
Q

What happens if an interface or abstract class inherits from two conflicting interfaces?

A

Compiler error

92
Q

Can you access an interface’s attributes without an instance of the interface? Justify.

A

Yes, because they are static

93
Q

Can you override a default method? How?

A

Just like overriding a normal method, just that the overriding method does not declare the method as default anymore

94
Q

What happens if a class(concrete or abstract) implements two interfaces that have default methods with the same name and signature?

A

Compiler error

95
Q

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?

A

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
Q

What happens when we change the reference of a type to a broader one?

A

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
Q

Do interfaces inherit Object? Justify

A

NO, because interfaces can only inherit other interfaces

98
Q

W.r.t the Exception class hierarchy, what is an unchecked exception and what is a checked exception?

A

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
Q

What happens if the catch block for the superclass is first and the catch block for the subclass is second?

A

Unreachable code => compiler error

100
Q

Can try-catch blocks be nested?

A

YES

101
Q

How many catch blocks can run per try-catch block?

A

ONLY ONE

102
Q

If you throw an exception that you dont’ catch, then the finally block throws a different exception, what will happen?

A

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
Q
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;
}
A

beforecatchfinallydone

Because first the innermost block has to finish(including the finally)

104
Q

Who can throw RuntimeExceptions?

A

The programmer and the JVM

105
Q

Who can throw checked exceptions?

A

The programmer and the JVM

106
Q

Who can throw errors?

A

Only the JVM

107
Q

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

A

Runtime:

ArithmeticException
ArrayIndexOutOfBoundsException 
ClassCastException
IllegalArgumentException Thrown 
NullPointerException
NumberFormatException Thrown
108
Q

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

A

Checked exceptions

Keep in mind that FileNotFoundException is a subclass of IOException !

109
Q

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

A

Errors:

ExceptionInInitializerError
StackOverflowError
NoClassDefFoundError

110
Q

What happens if you declare an unused exception?

A

It’s OK

111
Q

What happens if you attempt to catch an exception which cannot get thrown from the try block?

A

Compiler error

112
Q

Is an overriding method allowed to throw more exceptions than the original one? If yes, in what situation?

A

Yes, but this only works with Runtime exceptions

113
Q

Are you allowed to handle errors?

A

Yes, but it’s not indicated

114
Q

What are the 3 legal ways of printing an exception named ‘e’ ?

A

System.out.println(e);
System.out.println(e.getMessage());
e.printStackTrace();

115
Q

What objects can be declared in the throws part of a method declaration?

A

Any Throwable

116
Q

True or false: If you throw more exceptions, only the last one’s stack trace will be printed? Justify.

A

True, because only the last one will be taken into account

117
Q

Can you declare RuntimeExceptions in the catch, even if the try clause doesn’t throw them ? Can you do this for checked ones?

A

Yes, because they are optional anyway.

No, because that catch will be considered unreachable code

118
Q

Can main() declare that it throws checked exceptions?

A

YES

119
Q

Is a=b=3 a legal statement? Justify.

A

Yes, but only if both the variables have already been declared. Ex that will still work:
int b;
int a = b = 3;

120
Q

Will this work?

System.out.print(null);

A

YES. It will print “null”

121
Q

Can you directly invoke the GC?

A

No, but you can suggest JVM to perform GC by calling System.gc();

122
Q

Does Math.round() round up or down?

A

UP

123
Q

Which operator has the least precedence(is evaluated last) ?

A

The assignment operator

124
Q

What happens if we change the return type of main()?

A

RUNTIME EXCEPTION

125
Q

What happens if we remove static from the declaration of main()?

A

RUNTIME EXCEPTION

126
Q

Which has higher precedence? . OR cast()?

A

.

127
Q

Can Wrapper classes be extended? Justify.

A

No, because they are final

128
Q

Do lambdas create a new scope for variables?

A

NO

129
Q

Does covariant return type apply to primitives?

A

NO

130
Q

Will this work? Justify.
int[] arr = null;
System.out.print(arr.length); *

A

No, it will throw NPE, because we are trying to access a field on a null reference

131
Q

Will this work? Justify.
int[] arr = null;
System.out.print(arr.length);

A

No, it will throw NPE, because we are trying to access a field on a null reference

132
Q

Will this work? Justify.
int[] arr = null;
arr[0] = 4;

A

No, it will throw NPE, because the array is null

133
Q

Can you throw null as if it were a Throwable value?

A

No. It will throw NPE

134
Q

Will this work? Justify.

public static void main(String args[]){
throw null;
}

A

No. It will not compile, because we are throwing an exception but not declaring a throws or enclosing it in a try-catch

135
Q

Will this work? Justify.

public static void main(String args[]){
ArithmeticException ex = null;
throw ex;
}

A

No. It will not compile, because we are throwing an exception but not declaring a throws or enclosing it in a try-catch

136
Q

Will this work? Justify.

long g = 012 ;

A

Yes, because it’s a valid octal number

137
Q

Will this work? Justify.

float f = -123;

A

Yes, because implicit windening conversion from int to float happens in this case, so we don’t need the decimal point

138
Q

Are wrapper classes final?

A

Yes

139
Q

Is java.lang.Number final?

A

NO

140
Q

Is java.lang.System final?

A

Yes

141
Q

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 …

A

weak encapsulation

142
Q

Which elements compose the method signature?

A

The name and the parameter list

143
Q

Does the the method signature include the return type?

A

NO

144
Q

Will the finally clause still be executed if we have a labeled break inside the try? Will the break work?

A

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
Q

What is a byte’s range?

A

-128 to 127.

146
Q
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");
A

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
Q

What does Boolean(String) return and what are the conditions?

A

new Boolean(“true”) if the argument is not null and equalsIgnoreCase(“true”);

otherwise, new Boolean(“false”)

-> Object

148
Q

What does Boolean(boolean) return and what are the conditions?

A

new Boolean(“true”) / new Boolean(“false”) - obviously

149
Q

What does Boolean.parseBoolean(String) return and what are the conditions?

A

true, if the argument is not null and equalsIgnoreCase(“true”);

otherwise, false

-> Primitive

150
Q

What does Boolean.valueOf(String) return and what are the conditions?

A

Boolean.TRUE, if the argument is not null and equalsIgnoreCase(“true”);

otherwise, Boolean.FALSE

-> Static constant

151
Q

What does Boolean.valueOf(boolean) return and what are the conditions?

A

Boolean.TRUE / Boolean.FALSE

-> Static constant

152
Q

Will this work? Justify.

while(false) { int x = 4; };

A

No, because the body of the loop is seen by the compiler as unreachable code

153
Q

Is Throwable a class or an interface?

A

Class

154
Q

Will this work? Explain how the code is executed
int i;
int[] arr = new arr[5];
arr[i] = i = 3*10;

A

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
Q

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]) {}

A

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
Q

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)
    }
}
A

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
Q

What is the default datatype for integral literals?

A

int

158
Q

What is the default datatype for floating point literals?

A

double

159
Q

Which of these will work?

float f1 = 1.0;
float f2 = 43e1;
float f3 = -1;
float f4 = Ox123;
float f5 = 4;
A

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
Q
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
A

Yes. We have redundancy, but it will still work

161
Q

Does String have method .append()?

A

NO

162
Q

Which of these will be called when doing this: printSum(1, 2) , ? Justify.
printSum(double, double);
printSum(float, float) ;

A

printSum(float, float) , because int is closer to float than to double

163
Q

Would such a structure compile?

for(int i=0; i++<5; System.out.println(i));

A

YES

164
Q

Will this work? Justify.

String String = “String”;

A

Yes, because class names, even built-in ones, are not keywords, so they can be used

165
Q

Will this compile? Justify.
String String= “test”;
System.out.println(String.length());

A

Yes. When a local variable has the same name as a class, the local variable will be considered

166
Q

Can a static field be private?

A

Yes

167
Q

Do final fields get a default value?

A

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
Q

Can an import appear before a package statement?

A

NO

169
Q

True or false: All operands of type byte, char or short are promoted at least to an int before performing mathematical operations.

A

True

170
Q

Can charAt( ) take a char value as an argument? Justify.

A

Yes, because it will be implicitly promoted to int

171
Q

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).

A

False. It throws IndexOutOfBoundsException. It actually throws StringIndexOutOfBoundsException, but it seems that this is the correct answer on the exam

172
Q
Will this work?
class B extends A{
    public static void sM1() { }  
    public  void sM1() { }  
}
A

No

173
Q
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");
    }
} }
A

Yes. The block with “no params” will always be executed and it’s valid syntax

174
Q

Which will compile? Justify.

System.out.println(null + true); //1
System.out.println(true + null); //2
System.out.println(null + null); //3

A

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
Q

Which has bigger precendence: parantheses or arr[x]?

A

Parantheses