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.
59 questionsLast updated
Keep maxIndex instead of max, start it at 0, and in an index loop set maxIndex = i whenever a[i] > a[maxIndex]. The value is then a[maxIndex].
marks = new int[3];?Only the method's copy of the address changes. From then on the method works on its own new array, and the caller's array is not touched.
Lesson: Arrays and methodsNever write a fixed size inside it. Loop with a.length or use a for-each loop, so the method adapts to whatever array it is given.
int[][] a is an array whose elements are rows, and each row is an ordinary int[]. So a[1] is a whole row and a[1][2] one value in it.
Swap the loops: the outer loop goes over the columns and the inner loop over the rows, adding a[r][c]. The total is reset for every column.
Use Arrays.copyOf(a, a.length), or make a new array of the same length and copy each element in a loop. int[] b = a; only gives the same array a second name.
Make a bigger array that holds the old values, for example Arrays.copyOf(a, a.length + 1), then put the new value in the last box and use the new array from then on.
ArrayIndexOutOfBoundsException. It happens when the index is below 0 or not less than the length, most often from a loop that uses <=.
Keep two indexes, one at each end. Swap the two elements with a spare variable, move both indexes towards the middle, and stop when they meet.
Lesson: Common mistakes and practiceWhen every value belongs to a row and a column of the same kind, like marks of students in subjects. Two 1D arrays fit two different kinds of information about the same item, like names and prices.
Lesson: Common mistakes and practice'A' in single quotes is a char, one character and a primitive value. "A" in double quotes is a String that happens to hold one character, so it has methods like length().
charAt(10) on a short String compile but fail when it runs?The compiler only checks that the index is an int. The length of the text is known only when the program runs, so the check happens then and throws StringIndexOutOfBoundsException.
indexOf() and contains()?indexOf() tells you where the text is, as a number, or -1. contains() only tells you whether it is there, as true or false. If I need the position later, for example to cut there, I use indexOf().
Find the first one with indexOf(ch), then call indexOf(ch, first + 1), which starts the search just after it.
substring() leave out the end index?Then the length of the result is simply end - start, and cuts fit together: s.substring(0, 4) and s.substring(4) join back into s with nothing lost or repeated.
Find the @ with indexOf('@'), then take email.substring(0, at). If at is -1, there is no @, so I check that first.
substring() change the original String?No. It makes a new String with a copy of those characters. The original stays the same.
Lesson: Cut out part of a String with substring()isEmpty() and isBlank()?isEmpty() is true only for "". isBlank() is also true when the String has only spaces, which is what a form usually needs to check.
Clean and change it in one chain: name.trim().toLowerCase().replace(' ', '_'). Then store the result in a variable, because the original never changes.
== the right choice?For primitive values: numbers, char and boolean. For text I always use equals(), because a String is an object.
equals() or equalsIgnoreCase()?equals(). Capital letters are part of a password, so Kerala@2024 and kerala@2024 must count as different.
== fine for a char but not for a String?A char is a primitive value, so == compares the values. A String is an object, so == compares objects; for text I use equals().
A word that reads the same both ways, like madam. I build the reverse with a backward loop and compare it with the original using equals().
s.trim().split("\\s+").length. trim() removes the outer spaces so there is no empty first part, and \\s+ treats each group of spaces as one separator.
parseInt() when the text already looks like a number?"85" is still a String, so + joins it and maths is not possible. Integer.parseInt("85") gives the real int 85.
StringBuilder instead of +?When I build or change text many times, especially inside a loop. For a few joins on one line, + is fine and easier to read.
new StringBuilder(s).reverse().toString(). The String has no reverse() of its own.
Three things: is it compared with equals() and not ==, was every trim() or toLowerCase() result stored, and are there hidden spaces? Printing the value inside brackets, like "[" + s + "]", shows the spaces.
StringIndexOutOfBoundsException, and how do you avoid it?It stops the program when an index is outside 0 to length() - 1, in charAt() or substring(). I use length() - 1 for the last index, check indexOf() for -1, and check isEmpty() before charAt(0).
StringBuilder instead of String?When I build or change text many times, especially in a loop, or when I need reverse() or insert(). It changes one object instead of making a new String every time.
Java keeps a list of the methods that are running, one on top of the other, called the call stack. The report traces that list: the method where the problem happened is on top, and each line below is the method that called it.
Lesson: What is an exception?The first line gives the exception's name and message. Then I find the first at line with my own class name; its line number is where to start looking.
NullPointerException, and how do you avoid it?It happens when code calls a method on a variable that holds null, which means no object. I check != null before using a value that may be missing, like an optional form field.
The name tells you at once what went wrong, which makes a stack trace quick to read. It also lets a program handle each kind of problem in its own way, with a separate catch block for each.
Lesson: Common exceptions you will seeA crash ends the whole program because of one bad value, and the user sees a stack trace. With try-catch the program shows a clear message, skips or fixes that one value and carries on.
Lesson: Handle an exception with try and catchInside it, around the line that can fail. Then one bad input is handled and the loop goes on with the next one. Around the loop, the first bad input would end the whole loop.
Lesson: Handle an exception with try and catchNo. A catch belongs to the try block right above it; on its own, javac reports 'catch' without 'try'.
When two different exceptions need exactly the same handling, like printing "bad input" for both bad text and a 0. It avoids writing the same lines twice.
Lesson: Multiple catch blocksA line after the try-catch is skipped when no catch matches the exception, or when the try or catch block returns. A line in finally runs in all of those cases.
Lesson: The finally blockClean-up work that must happen even after an error, such as closing a Scanner or a file, or printing a closing line like "Take your card".
Lesson: The finally blockthrow and throws?throw is used to explicitly throw a single exception; it is written inside the method body: throw new IllegalArgumentException("Bad age");. throws is used in a method declaration to indicate that the method may throw one or more exceptions: static void readFile() throws FileNotFoundException. So throw throws one exception object now; throws only warns callers, and can list several types separated by commas.
Error and Exception?An Error is a serious problem in Java itself, like running out of memory, and programs do not catch it. An Exception is a problem the program can handle.
Yes. Exceptions Java already has, like ArithmeticException, are built-in exceptions. Ones you write yourself, such as InsufficientBalanceException, are user-defined (custom) exceptions. You make one by writing a small class that extends Exception or RuntimeException, which the OOP section covers.
while (true) looks like an endless loop. Why is it fine here?The only way out is the break that runs after a good value, so the loop repeats exactly as long as the input is bad. It is the natural shape for "ask until it is right".
Use a counted loop, for (int i = 1; i <= 3; i++), instead of while (true), and break on a good value. After the loop, a flag or the counter tells you whether all 3 tries failed, so the program can print a final message.
if check better than try-catch, and when is try-catch the better choice?When I can check the value cheaply in advance, like a count of 0 or an index past the end, an if is clearer. When the only real way to know is to try, like converting text a user typed, try-catch is the better tool.
Usually IllegalArgumentException with a clear message, such as Amount must be positive. It is unchecked, so callers are not forced to catch it, but the problem is reported at once instead of becoming a wrong result.
When the class is in another package and you have not imported it, or when two classes with the same short name are used in one file. The full name always points to exactly one class.
Lesson: Why do we need packages?A website name is unique in the world, so the package names built from it are unique too. Two companies can both have a Report class, and their full names still never clash.
For a one-file practice program, yes. In a real app, no: a class in the default package cannot be imported by classes in named packages, and nothing tells you what it belongs to.
Lesson: Create your own packageI check that the folder the file is in matches the package name, part by part. IDEs flag a package line that does not match the folders.
Lesson: Create your own packageimport java.util.*; or one import per class?One import per class, because a reader sees exactly which classes the file uses and two wildcards cannot bring in clashing names by surprise. A wildcard is fine for a quick practice program.
Lesson: Use classes from other packages with importOnly to compile it. javac turns every short name into the full name, so the class file already knows exactly which class it uses.
Lesson: Use classes from other packages with importjavac checks them when it compiles, so a broken rule never reaches a running program. The JVM checks them again when it loads classes.
Lesson: Access modifiers: public, private and defaultmain be private?It compiles, but the java command cannot start the program: it says Main method not found and asks for public static void main(String[] args). main must be public so the JVM can call it from outside the class.
I group classes by topic: books in one package, members and fines in another. A class belongs where the thing it is about belongs, and the class with main gets its own package.
I add a package such as com.library.members with its own classes, private data and only the public methods the app needs. Then LibraryApp imports them, and I add the new files to the javac command.
cannot find symbol and has private access?cannot find symbol means Java does not know the name at all, often because of a missing import. has private access means Java found it, but your class is not allowed to use it.
No. An import only lets you write the short name. What you may use is still decided by the access modifiers: only the public members are open to other packages.
Lesson: Common mistakes and practiceEach lesson has quizzes, practice and more interview questions on the same topic.
Open the first lesson