Loading...
Loading...
Java interview guide
Syntax, data types, operators, control flow, methods, arrays and strings. Every answer is short enough to say aloud, and every question links to the lesson that teaches it.
61 questionsLast updated
Java stops at the first true condition. If a wide check like marks >= 35 comes first, it also catches 95, and the stricter checks below never run. So the strictest check goes first.
Some path through the ladder does not give the variable a value, and Java will not print an empty variable. Add a final else that sets it, or give it a starting value.
&& runs the block only when both conditions are true. || runs it when at least one is true, and skips it only when both are false.
Whenever you mix && and ||. Java joins && first, which may not be what you mean, and brackets also make the rule easy to read.
Yes, when the inner if has no else: the block runs only when both are true. Nesting is better when each failed check needs its own message.
An else belongs to the nearest if above it in the same block. Braces decide the blocks, and indentation makes them visible.
A variable lives only inside the block where it is created. Declare it before the if when you need it afterwards.
It is when Java runs on into the next case because break is missing. Usually it is a bug, but it is useful when several cases should share one block, like Saturday and Sunday.
Choose switch when one value is matched against fixed choices, like a menu number. Use a ladder for ranges or for checks on different variables.
It is a switch that gives back a value, which you can store or print, like int price = switch (plan) { ... };. Each arrow gives the value for its case.
Yes. Put the statements in braces: case 6, 7 -> { ... }. Only that block runs, and there is still no fall-through.
x = 5 stores 5 and gives an int. An if needs true or false, and Java will not turn a number into one, so it reports an error. Write x == 5.
The semicolon is an empty statement that becomes the whole body of the if. The block below is then just a normal block, so it runs every time.
Use switch when one value is matched against fixed choices, like a menu number or an operator. Use a ladder for ranges or for checks on different variables.
A start value for the counter, a condition that is checked before each round, and an update that changes the counter after each round. Without the update the loop never ends.
Lesson: Why loops?Java has for, while and do-while. Use for when you know the number of rounds, while to repeat until something happens, and do-while when the body must run at least once.
The start runs once. Then Java checks the condition; if it is true, the body runs, then the update, then the condition again. The loop ends at the first false check.
Lesson: The for loopYes. Start at the high value, use a condition like i >= 1 and update with i-- to count down. Use i += 2 (or any step) to jump.
It is a table with one row per step of a loop and a column for every variable. Filling it in shows exactly what the loop does, so it is the quickest way to find why a loop gives a wrong answer.
Lesson: Tracing a loop: totals and countsA variable declared inside the body is created again every round, so it would lose the running total. It would also not exist after the loop, where we print it.
Lesson: Tracing a loop: totals and countsLoop from 1 to 100 and keep a count that starts at 0. In each round check i % 2 == 0 && i % 3 == 0 and add 1 when it is true; the answer is 16.
When the number of rounds is not known before the loop starts, for example reading input until a stop value or removing digits until the number is 0. for suits a count known in advance.
Whether the body changes the variable in the condition, and in the right direction. If i should grow towards 10 but is never updated, or goes down, the condition stays true forever.
No. It stops only the loop (or switch) it is written in. The lines after that loop still run.
It saves work and makes the intent clear: once a search finds what it needs, there is no reason to keep going. In a search over a million values, that can save almost all the rounds.
Lesson: break and continueA loop written inside the body of another loop. For each round of the outer loop, the inner loop runs from start to finish.
Lesson: Nested loops and star patternsYes, and that is how triangles work: j <= i gives row i exactly i items. The inner loop can read i but should not change it.
I ask what decides the number of rounds. A count known before the loop means for; repeating until something happens means while; and if the body must run at least once, like a menu, do-while.
I look at the variable in the condition and check that every round changes it towards making the condition false. A missing update, an update in the wrong direction or a continue that skips the update are the usual causes.
for (…) compile but do the wrong thing?A lone ; is a valid empty statement, so it becomes the loop body. The loop repeats nothing, and the block in braces below it runs once, as normal code.
main?Java itself: when you run the program, the JVM calls main first. You never call main yourself; from main you call your own methods.
When the same lines appear in two or more places, or when a group of lines does one clear job that a name can describe, like printBill.
main?No. Java finds every method in the class, and the program always starts at main. Most programmers put main first so the reader sees the plan before the details.
When it makes a call, Java remembers the place of the call. When the method ends, it returns there and runs the next line. That memory is the call stack, covered in Local variables and scope (opens in a new tab).
Lesson: Define and call a methodEach parameter is a separate variable, and Java needs the type of every variable. (int a, int b) is correct; (int a, b) does not compile.
A parameter makes one method work for many values. printTable(int n) prints any table; a method with 7 typed inside prints only the 7 times table.
Return it when other code may need the value, for example to add GST to a price. A returned value can still be printed, but a printed value cannot be used again.
Lesson: Return a value from a methodvoid method use return?Yes, as return; with no value. It ends the method early, for example when there is nothing left to do.
It lives in the frame of the method call that made it, on the call stack. When that call ends, the frame is removed and the variable is gone.
Lesson: Local variables and scopeIt is the pile of frames for the method calls that are still running. A new call goes on top, the top call finishes first, and main is at the bottom.
It swaps only its own copies, which are thrown away when it ends. The variables in main are never touched, and a method cannot return two values to put back.
Write two methods, one for each value, and store each result, like smaller(a, b) and larger(a, b). Later modules show other ways, such as returning an array.
When it compiles. The compiler looks at the argument types in the call and fixes which version will run, so a wrong call is caught before the program starts.
Lesson: Method overloadingFor small jobs like factorial, a loop is often simpler and uses less memory, because recursion keeps a frame for every waiting call. Recursion is clearer for problems that split into smaller copies of themselves.
Lesson: Recursion: a method that calls itselfn?The calls are all waiting at the same time, each for a different value. Each call has its own frame on the call stack, so n is 3 in one, 2 in the next and 1 in the last.
Each method should do one job that a short verb name can describe, like gst or isPrime. If lines repeat, or a block needs a comment to explain what it does, it is a good candidate for its own method.
main calls a method that calls another?Each call puts a new frame with its own local variables on top of the call stack. The top method runs and finishes first; its frame is removed and Java continues in the method below.
Lesson: Common mistakes and practiceisPrime?Call it with values whose answers I know, including the edge cases: 0, 1, 2, a small prime like 7, and a square like 9. A simple loop version wrongly says 1 is prime unless it checks n < 2 first.
The index tells how many steps an element is from the start. The first element is 0 steps away, so its index is 0.
Lesson: What is an array?The element is the value stored, like 85. The index is its position number, like 1.
Lesson: What is an array?Use braces, int[] a = {1, 2, 3};, when you know the values while writing the code. Use new int[n] when you know only the size and the values come later, from a calculation or the user.
null mean?null means "no value yet". A new String[] has null in every box until you put text in.
int marks[] the same as int[] marks?Yes, both declare an int array. int[] marks is the common style because the whole type, int[], stays together.
No. The index is often a variable whose value is known only while the program runs, so the code compiles and Java checks the index when the line runs.
Lesson: Reading and changing array elementsYes, any int expression works, such as a[i], a[i + 1] or a[n - 1]. It must be an int: a[2.0] does not compile.
a.length in the loop instead of a number?The loop then works for any size. If you add values to the array later, the loop does not need to change, and it can never run past the end.
Lesson: Looping through an arrayMake the array with new, then loop over it and write a[i] = sc.nextInt(); in each round.
When you need the index, want to go backwards or skip elements, or want to change the elements.
Lesson: The for-each loopThere is no index and no condition, so you cannot make an off-by-one mistake or go outside the array.
Lesson: The for-each loopStore the first element in max. Then loop through the array and replace max whenever an element is bigger. After the loop, max holds the largest value.
Checking the elements one by one, from the start, until you find the value or reach the end. It works on any array, sorted or not.
Lesson: Sum, average, largest and searchEach lesson has quizzes, practice and more interview questions on the same topic.
Open the first lesson