Part 3 has the small, exact questions that interviewers use to check your basics: what happens on integer overflow, how >> differs from >>>, how many bytes a character takes, which modifiers an inner class can have, and what state a finished thread is in. It also covers List, Vector, Iterator and a few AWT and event questions from older syllabi.
Many of these have one-line answers, but the follow-up is where people slip. For each question, give the short answer aloud, then ask yourself "why?" and answer that too. Run the code snippets yourself and change the numbers.
Q1. Which containers have FlowLayout as their default layout?
In AWT, Panel uses FlowLayout by default, and so did Applet, since it extends Panel. In Swing, JPanel also defaults to FlowLayout. FlowLayout places components in a row, left to right (centered by default), and wraps to the next row when it runs out of width. Applets are gone from modern Java, and new desktop UIs mostly use JavaFX, so this is mainly an exam question now.
Q2. What state is a thread in after it finishes running?
It is in the TERMINATED state (older books call it "dead"). This happens when run() returns normally or throws an uncaught exception. A terminated thread cannot be started again; calling start() a second time throws IllegalThreadStateException.
The full list in Thread.State is NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING and TERMINATED.
public class StateDemo {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {});
System.out.println(t.getState());
t.start();
t.join();
System.out.println(t.getState());
}
}
NEW
TERMINATED
Q3. What are the main parts of the Collections API?
Think of it in three layers. First the interfaces, which define the types: Collection, List, Set, Queue, Deque, Map and their sorted and sequenced variants. Second the implementations, which are the actual data structures: ArrayList, LinkedList, HashSet, LinkedHashSet, TreeSet, ArrayDeque, PriorityQueue, HashMap, TreeMap and the concurrent ones in java.util.concurrent.
Third the algorithms and helpers, mostly static methods in Collections and Arrays: sorting, binary search, shuffling, unmodifiable and synchronized wrappers. Explaining it in these three layers sounds much better than reciting a list of class names.
Q4. Which characters can appear in an identifier but not as its first character?
Digits. An identifier must start with a letter, an underscore or a currency symbol like $. After that it can also contain digits. So total2 is fine but 2total is not. Identifiers are case sensitive and cannot be a reserved keyword.
One modern detail: since Java 9 a single underscore _ on its own is a keyword and cannot be a name. Since Java 22 it is used for unnamed variables, as in catch (Exception _), when you do not need the value.
Q5. What is the List interface?
List is an ordered collection. Elements keep the position you put them in, you can access them by index with get(i) and set(i, value), and duplicates are allowed. The main implementations are ArrayList (array-backed, fast random access) and LinkedList (doubly linked, fast at the ends). List.of(...) gives you an unmodifiable list, and since Java 21 List also has getFirst(), getLast() and reversed().
Q6. What happens when an int calculation overflows in Java?
Nothing loud. Integer arithmetic on int and long wraps around silently, because the result keeps only the low-order bits that fit in the type (two's complement). So Integer.MAX_VALUE + 1 becomes Integer.MIN_VALUE. No exception is thrown. Underflow works the same way in the other direction.
If you need to detect it, use Math.addExact, multiplyExact and friends, which throw ArithmeticException. For bigger numbers use long or BigInteger. This bug often shows up in binary search when you write (low + high) / 2; low + (high - low) / 2 avoids it.
public class OverflowDemo {
public static void main(String[] args) {
int max = Integer.MAX_VALUE;
System.out.println(max + 1);
try {
Math.addExact(max, 1);
} catch (ArithmeticException e) {
System.out.println("addExact: " + e.getMessage());
}
}
}
-2147483648
addExact: integer overflow
Q7. What is the Vector class?
Vector is a growable array from Java 1.0, later fitted into the Collections framework as a List. Every public method is synchronized, so a single call is thread safe, but you pay for locking even in single-threaded code, and compound actions like "check then add" still need extra locking. When it runs out of space it doubles its capacity by default.
Today you use ArrayList for normal code, and CopyOnWriteArrayList or a synchronized wrapper when threads share a list. If you need a stack, use ArrayDeque instead of Stack, which extends Vector.
Q8. Which modifiers can a member inner class have?
A class declared directly inside another class (a member class) can use all four access levels: public, protected, package-private (no modifier) and private. It can also be static (making it a static nested class), abstract or final, and since Java 17 sealed or non-sealed.
Top-level classes can only be public or package-private. Local classes declared inside a method cannot have access modifiers or static.
Q9. How do you use the Iterator interface, and why use it instead of a for loop?
You get an Iterator from collection.iterator(), then loop with while (it.hasNext()) and read each element with it.next(). It works the same way for every collection, including sets that have no index.
Its real value is it.remove(). If you remove from an ArrayList inside a for-each loop, the list notices the change and throws ConcurrentModificationException on the next step. Removing through the iterator keeps it in sync. For simple cases, list.removeIf(x -> x < 0) (Java 8) does the same thing in one line.
Q10. What is the difference between >> and >>>?
Both shift bits to the right. >> is the signed (arithmetic) shift: it copies the sign bit into the empty positions on the left, so negative numbers stay negative. >>> is the unsigned (logical) shift: it always fills with zeros, so a negative number becomes a large positive one.
public class ShiftDemo {
public static void main(String[] args) {
int n = -16;
System.out.println(n >> 2);
System.out.println(n >>> 28);
System.out.println(16 >> 2);
}
}
-4
15
4
For positive numbers both give the same result. There is no <<<, because a left shift always fills with zeros anyway.
Q11. Which Component method sets both position and size?
setBounds(x, y, width, height). It is the same as calling setLocation(x, y) and setSize(width, height). It only has a lasting effect when the container's layout is null; otherwise the layout manager will reposition the component. Swing components inherit the same method.
Q12. How many bits do ASCII, Unicode, UTF-8 and UTF-16 use per character?
This question is often answered wrongly. ASCII is a 7-bit code (128 characters), usually stored in one 8-bit byte. Unicode is not an encoding with a fixed size. It is a character set with code points from U+0000 to U+10FFFF, which needs 21 bits to cover. The encodings decide how many bytes each character takes:
- UTF-8 uses 1 to 4 bytes. ASCII characters take 1 byte, so plain English text is unchanged.
- UTF-16 uses 2 bytes for most characters and 4 bytes (a surrogate pair) for characters outside the Basic Multilingual Plane, such as most emoji.
A Java char is a 16-bit UTF-16 code unit, so one emoji needs two chars and "😀".length() is 2. Since Java 18 the default charset is UTF-8 on every platform.
import java.nio.charset.StandardCharsets;
public class EncodingDemo {
public static void main(String[] args) {
String[] samples = {"A", "é", "₹", "😀"};
for (String s : samples) {
int bytes = s.getBytes(StandardCharsets.UTF_8).length;
System.out.println("UTF-8 bytes: " + bytes + ", chars: " + s.length());
}
}
}
UTF-8 bytes: 1, chars: 1
UTF-8 bytes: 2, chars: 1
UTF-8 bytes: 3, chars: 1
UTF-8 bytes: 4, chars: 2
The four samples are A, é, the rupee sign and a smiling-face emoji.
Q13. How is Thread.yield() different from Thread.sleep()?
Thread.sleep(ms) pauses the current thread for at least that long. Its state becomes TIMED_WAITING, it keeps any locks it holds, and it can be woken early by an interrupt, which throws InterruptedException.
Thread.yield() is only a hint to the scheduler that the thread is willing to let others run. The thread stays RUNNABLE and may be picked again immediately. The scheduler is free to ignore the hint, so never use yield for correctness. In practice you will almost never call it.
Q14. Which classes and interfaces in java.util support event handling?
java.util.EventObject is the base class for event objects. It holds the source of the event, available through getSource(). java.util.EventListener is a marker interface that every listener interface extends, such as AWT's ActionListener. AWT's own AWTEvent extends EventObject. If you build your own event system, following this pair keeps it familiar to other Java developers.
Q15. Is sizeof a keyword in Java?
No. Java has no sizeof operator at all, and the word is not reserved. C needs sizeof because type sizes vary by platform. In Java, primitive sizes are fixed by the language (an int is always 32 bits), and constants like Integer.BYTES give them to you.
The size of an object, on the other hand, depends on the JVM: header size, compressed references, alignment. If you really need it, use a tool such as JOL (Java Object Layout) or a heap profiler.
Quick revision
- A finished thread is
TERMINATEDand cannot be restarted. - int and long overflow wraps silently; use
Math.addExactto detect it. >>keeps the sign,>>>fills with zeros.- UTF-8 uses 1 to 4 bytes, UTF-16 uses 2 or 4, a Java char is one 16-bit UTF-16 unit.
- sleep keeps locks and moves to TIMED_WAITING; yield is a hint and the thread stays RUNNABLE.
- Vector is legacy; prefer ArrayList, and ArrayDeque over Stack.
Frequently asked questions
Why do interviewers ask tiny questions like the range of overflow or bit shifts?
They check whether you understand how numbers are stored, which matters in hashing, binary search and bit manipulation problems. One clear example, like Integer.MAX_VALUE + 1, usually satisfies them.
Should I learn thread states by heart?
Learn the six names and one real cause for each (for example, BLOCKED means waiting to enter a synchronized block). That is enough for most rounds and also helps you read thread dumps at work.
Is it worth learning AWT and Applet details for placements?
Only to the level of these short answers. Spend the saved time on collections, exceptions and multithreading, which carry far more weight.
Comments
Post a Comment