All topics
Methods
Static methods, parameters and return values, pass-by-value, overloading, recursion and the scope of local variables.
Sort:
4 questions
JuniorTheoryCommonWhat happens when the program is compiled and run?
JuniorTheoryCommon
What happens when the program is compiled and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
1: the compiler does not look at the callsign(5); it checks that every path throughsignreturns a value, andx == 0reaches the end with none. - ✗Expecting
0or a run-time error: a method gets no default result; a path withoutreturnstops the build withmissing return statement.
Follow-up questions
- →How would you change
signso that it compiles and returns 0 for zero? - →Why does a
voidmethod compile without anyreturn?
JuniorTheoryCommonWhat does the program print?
JuniorTheoryCommon
What does the program print?
intdoubleint
Open full question →Common mistakes
- ✗Expecting
intdoubledouble: with nof(char), the compiler takes the nearest widening, andcharwidens tointbeforedouble. - ✗Expecting a compile error: a missing exact match is not an error when widening the argument finds a version that fits.
Follow-up questions
- →Which version runs for
f(5L), and why? - →Why can two methods not differ only in their result type?
JuniorTheoryCommonWhat does the program print?
JuniorTheoryCommon
What does the program print?
1
Open full question →Common mistakes
- ✗Expecting
2: Java passes arguments by value, sonis a copy ofx, andn++changes only the copy, which vanishes whenincreturns. - ✗Expecting a compile error: a parameter is an ordinary local variable and may be changed; the change only never reaches the caller's variable.
Follow-up questions
- →How would you change
incso thatmaingets the new value? - →Does Java pass arguments by value or by reference?
JuniorTheoryCommonWhat does the program print?
JuniorTheoryCommon
What does the program print?
10
Open full question →Common mistakes
- ✗Expecting
0: the base case's 0 goes back tof(1), not tomain; each waiting call adds its ownn, so the answers grow to 1, 3, 6 and 10. - ✗Expecting a
StackOverflowError:nreaches 0, and the?:returns 0 there without another call, so the chain stops after five calls.
Follow-up questions
- →What happens if the program calls
f(-1)? - →How would you compute the same sum with a loop?