Java Tricky Questions Flashcards

(200 cards)

1
Q

Is there any difference between a = a + b and a += b expressions?

A

Yes. When adding byte or short variables Java promotes them to int first. a = a + b stores an int into a smaller type requiring explicit cast. a += b includes an implicit narrowing cast so it compiles without error

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

Why does a += b work for byte variables but a = a + b does not?

A

When adding byte or short variables Java promotes them to int first. a = a + b stores an int into a byte which needs an explicit cast. a += b has implicit casting built in so it compiles without error

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

MEMORY BOOSTER: a = a+b vs a += b

A

a = a + b = int promotion + may need explicit cast. a += b = same arithmetic + implicit cast back to variable type. For byte or short use += to avoid compile error. The += operator is a compound assignment that includes implicit narrowing cast

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

What happens when you put a return statement in a try or catch block - will finally execute?

A

Yes - finally executes even if there is a return in try or catch. The finally block always runs before the method actually returns

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

What happens when you call System.exit() from a try or catch block - will finally execute?

A

No - System.exit() terminates the JVM immediately so the finally block will NOT execute

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

MEMORY BOOSTER: finally block execution

A

finally ALWAYS runs EXCEPT when System.exit() is called. return in try/catch = finally still runs. System.exit() = JVM dies = finally skipped. Rule: finally runs unless the JVM itself stops

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

What does the expression 1.0 / 0.0 return in Java? Will there be a compilation error?

A

No compilation error and no ArithmeticException. It returns Double.INFINITY. Floating-point division by zero follows IEEE 754 rules and returns infinity

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

Why does integer division by zero throw an exception but floating point division does not?

A

Integers have no representation for infinity so int/0 throws ArithmeticException. Floating point follows IEEE 754 which defines special values: INFINITY - NaN and negative zero to handle these cases

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

MEMORY BOOSTER: Floating point division by zero

A

int / 0 = ArithmeticException. double / 0.0 = Double.INFINITY (no exception). 0.0 / 0.0 = Double.NaN. -1.0 / 0.0 = Double.NEGATIVE_INFINITY. IEEE 754 handles these gracefully for floating point

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

Can we use multiple main methods in multiple classes?

A

Yes - each class can have its own main method. JVM only looks for main in the class whose name is passed to the java command so there is no conflict

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

Can we have multiple methods named main in the same class?

A

Yes - but only one can have the signature public static void main(String[] args). JVM only recognizes that exact signature as the entry point. Other methods named main are just regular overloaded methods

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

MEMORY BOOSTER: Multiple main methods

A

Multiple classes can each have main() - no conflict. Same class can have multiple main() methods but JVM only calls: public static void main(String[] args). All others are regular overloaded methods ignored by JVM

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

Does Java allow you to override a private or static method?

A

No - private methods are not visible to subclasses so they cannot be overridden. Static methods can only be hidden not overridden. Creating a same-signature static method in a subclass is called method hiding not overriding

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

What is method hiding in Java?

A

Method hiding occurs when a subclass defines a static method with the same signature as a static method in the parent class. The method called depends on the reference type at compile time not the object type at runtime

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

MEMORY BOOSTER: Override private or static

A

private = not visible in subclass = cannot override. static = belongs to class = cannot override = can only hide (method hiding). Neither is true runtime polymorphism. Only instance non-private non-final methods can be overridden

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

What happens when you put a key object in a HashMap that is already present?

A

The old value is replaced by the new value. HashMap does not allow duplicate keys. The put() method returns the old value when replacing and stores the new value in the same bucket

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

MEMORY BOOSTER: Duplicate key in HashMap

A

put() with existing key = old value replaced + old value returned. HashMap never has duplicate keys. Same key = same hashCode = same bucket = equals() confirms match = value overwritten. put() return value is the OLD value (or null if new key)

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

How can you make sure that N threads can access N resources without deadlock?

A

Use resource ordering. Always acquire resources in the same fixed order and release them in reverse order across all threads. This eliminates circular wait which is one of the four conditions required for deadlock

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

MEMORY BOOSTER: Prevent deadlock with N resources

A

Resource ordering = all threads request resources in same fixed order. Thread A and B must both request Resource 1 then Resource 2 never in different orders. No circular wait = no deadlock. Simple but very effective technique

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

How can you determine if the JVM is 32-bit or 64-bit from a Java program?

A

Use System.getProperty(“sun.arch.data.model”) which returns 32 or 64 depending on the JVM bit size

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

MEMORY BOOSTER: Detect JVM bit size

A

System.getProperty(“sun.arch.data.model”) returns 32 or 64. Useful for code that behaves differently on 32-bit vs 64-bit JVM. Can also check at command line with java -d32 or java -d64

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

What is the right data type to represent Money in Java?

A

BigDecimal is the best choice. It supports decimal points and correct rounding. double can be used with predefined precision but floating point arithmetic can produce erroneous results for financial calculations

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

Why should you avoid using double for monetary calculations?

A

Floating point arithmetic with double is imprecise. For example 5 * 0.1 does not equal exactly 0.5 in Java due to binary representation of decimals. This imprecision is unacceptable for financial calculations

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

MEMORY BOOSTER: Money representation

A

Use BigDecimal for money - never double or float. BigDecimal = exact decimal arithmetic + controlled rounding. double = imprecise = dangerous for finance. 5*0.1 == 0.5 is FALSE in Java. BigDecimal uses more memory but correctness is worth it

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
How can you achieve multiple inheritance in Java?
Java supports multiple inheritance of type through interfaces - a class can implement multiple interfaces. Java 8 added multiple inheritance of behavior via default methods. Java does not support multiple inheritance of state (extending multiple classes)
26
MEMORY BOOSTER: Multiple inheritance in Java
Java: NO extending multiple classes. YES implementing multiple interfaces. Java 8: default methods in interfaces = multiple inheritance of behavior. C++ allows multiple class inheritance. Java avoids it to prevent Diamond Problem complexity
27
Is the ++ operation thread-safe in Java?
No - ++ is not atomic. It involves three steps: read the value + increment it + write back. A thread can be interrupted between any step causing race conditions. Use AtomicInteger.incrementAndGet() for thread-safe increment
28
MEMORY BOOSTER: ++ is not thread-safe
i++ = read + increment + write = 3 non-atomic steps = race condition risk. Fix: AtomicInteger from java.util.concurrent.atomic or synchronize the operation. Use atomicInt.incrementAndGet() for thread-safe counter
29
How can you access a non-static variable from a static context?
You cannot directly access a non-static variable from a static context. You must create an instance of the class first and access the instance variable through that reference
30
Why can we not access instance variables inside the main method directly?
main() is static. Instance variables are non-static. Static methods belong to the class not to any object so they have no access to instance state. You must create a new object instance first
31
MEMORY BOOSTER: Static vs non-static access
Static context = belongs to class = no object = cannot access instance variables. Fix: create new MyClass() then access via the reference. Classic beginner mistake: using this.field inside a static method - this does not exist in static context
32
Can we override a method that throws NullPointerException with a method that throws RuntimeException?
Yes - you can throw a broader unchecked exception (RuntimeException) in an overriding method because NullPointerException is unchecked. For checked exceptions the overriding method cannot throw new or broader exceptions
33
MEMORY BOOSTER: Override and checked vs unchecked exceptions
Unchecked exceptions: override can add or broaden freely. Checked exceptions: override can only throw same or narrower. NullPointerException extends RuntimeException = unchecked = can be replaced with any RuntimeException. This follows Liskov Substitution Principle
34
How can you mark an array volatile in Java?
You can mark the array reference volatile but it only makes the reference volatile not the individual array elements. Changes to array elements are not guaranteed to be visible to other threads
35
MEMORY BOOSTER: Volatile array
volatile int[] arr makes the REFERENCE volatile not the array contents. Thread sees new array if reference is reassigned. Thread does NOT automatically see changes to arr[0] arr[1] etc. For element-level visibility use AtomicIntegerArray instead
36
What is a thread local variable in Java?
A thread-local variable gives each thread its own independent copy of a variable. Changes in one thread do not affect other threads. Java provides ThreadLocal class for this. Always call remove() after use to prevent memory leaks especially in thread pools
37
MEMORY BOOSTER: Thread local variable
ThreadLocal = one variable + separate value per thread. set() stores for current thread. get() retrieves for current thread. remove() cleans up. Always call remove() to avoid memory leaks when threads are reused in a pool
38
What is the difference between sleep() and wait() in Java?
sleep() pauses the thread for a fixed time without releasing any locks. wait() releases the monitor lock and waits until notify() wakes it up. sleep() is in Thread class. wait() is in Object class and must be inside a synchronized block
39
MEMORY BOOSTER: sleep() vs wait()
sleep() = timed pause + keeps lock + no notify needed + Thread class. wait() = conditional pause + releases lock + needs notify() to resume + Object class + must be in synchronized block. sleep = timed rest. wait = cooperative waiting for a condition
40
Can you create an Immutable object that contains a mutable object?
Yes - but never expose the mutable object directly. Return a defensive copy from getter methods and create a copy of any mutable object passed to the constructor. This prevents external code from modifying the internal mutable state
41
MEMORY BOOSTER: Immutable with mutable member
Immutable class rule: never share reference to internal mutable object. Return copies not originals in getters. Take defensive copies in constructor. Example: return new Date(internalDate.getTime()) not return internalDate
42
How can you convert an array of bytes to a String in Java?
Use the String constructor: new String(byteArray - charset). Always specify the character encoding explicitly (like StandardCharsets.UTF_8) to avoid platform-dependent results
43
MEMORY BOOSTER: byte[] to String
new String(byteArray) = platform default charset (risky). new String(byteArray - StandardCharsets.UTF_8) = explicit safe conversion. Always specify charset. String.getBytes(charset) for the reverse. Wrong charset = garbled text
44
What is the key difference between CyclicBarrier and CountDownLatch?
CountDownLatch is single-use - once the count reaches zero it cannot be reset. CyclicBarrier is reusable - it automatically resets after all threads reach the barrier making it suitable for repeated synchronization points
45
MEMORY BOOSTER: CyclicBarrier vs CountDownLatch
CountDownLatch = one-time countdown + cannot reset. CyclicBarrier = reusable + resets after barrier + optional Runnable on completion. Use Latch for one-time start signal. Use Barrier for repeated rendezvous like game rounds or MapReduce iterations
46
What is the difference between StringBuffer and StringBuilder?
StringBuffer methods are synchronized making it thread-safe but slower. StringBuilder is not synchronized making it faster but not thread-safe. Use StringBuilder in single-threaded code. Use StringBuffer only when multiple threads share the same builder
47
MEMORY BOOSTER: StringBuffer vs StringBuilder
StringBuffer = synchronized = thread-safe = slower. StringBuilder = not synchronized = not thread-safe = faster. Java 5 added StringBuilder. Default choice: StringBuilder. Only use StringBuffer when multiple threads modify the same builder
48
Which class contains the clone() method - Cloneable or Object?
clone() method is defined in the Object class. Cloneable is a marker interface with no methods. A class must implement Cloneable to signal cloning is permitted otherwise clone() throws CloneNotSupportedException
49
MEMORY BOOSTER: clone() and Cloneable
clone() = in Object class. Cloneable = marker interface = no methods. To enable cloning: implement Cloneable + override clone() from Object. Without Cloneable: clone() throws CloneNotSupportedException. Marker interface = permission slip
50
Can you cast an int variable into a byte variable? What happens if the value is larger than byte?
Yes - you can explicitly cast int to byte. But int is 32 bits and byte is 8 bits. The upper 24 bits are discarded and only the lower 8 bits are kept. Values above 127 wrap around to negative numbers
51
MEMORY BOOSTER: int to byte cast
int = 32 bits. byte = 8 bits. Cast: (byte) myInt. Loses upper 24 bits. Values above 127 wrap around. Example: (byte)128 = -128 due to overflow. Narrowing cast = silent data loss possible
52
Can we store a double value in a long variable without explicit casting?
No - double has a larger range and includes decimal values. An explicit cast is required: (long) myDouble. The decimal part is truncated not rounded
53
MEMORY BOOSTER: double to long
double > long in range. double has decimals. long is integer only. Requires explicit cast: (long) myDouble. Decimal part is truncated. long l = 3.14 is a compile error - narrowing requires explicit cast
54
What does 5*0.1 == 0.5 return in Java?
false - floating point numbers cannot be represented exactly in binary. 5*0.1 produces a value very close to but not exactly 0.5. Never use == to compare floating point numbers. Use Math.abs(a - b) < epsilon instead
55
MEMORY BOOSTER: Floating point comparison
5*0.1 == 0.5 is FALSE. Floating point arithmetic is imprecise in binary. Never compare doubles with ==. Use Math.abs(a - b) < 0.0001 or BigDecimal for exact comparison. One of the most common Java gotchas
56
Out of int and Integer which one takes more memory?
Integer takes more memory. Integer is an Object with metadata overhead (object header approximately 16 bytes). int is a primitive with no overhead using only 4 bytes
57
MEMORY BOOSTER: int vs Integer memory
int = primitive = 4 bytes = no overhead. Integer = object = approximately 16 bytes = object header overhead. Prefer int when null is not needed and Collections are not involved. Integer required for Collections since generics do not support primitives
58
Can we use String in a switch case statement in Java?
Yes - from Java 7 onwards String can be used in switch case. Internally the hashCode() of the String is used for the switch mechanism followed by equals() to confirm the match
59
MEMORY BOOSTER: String in switch
String in switch = available since Java 7. Internally: hashCode() to find case + equals() to confirm. Case values must be String literals or constants. Java 21 switch pattern matching extends this to any type
60
When creating an abstract class is it a good idea to call abstract methods inside its constructor?
No - it is dangerous. The superclass constructor runs before the subclass is fully initialized. The abstract method will invoke the subclass override but subclass fields are not yet initialized which can cause NullPointerException or wrong values
61
MEMORY BOOSTER: Abstract method in constructor
Never call overridable methods from a constructor. Order: parent constructor first + then child fields initialized. If parent constructor calls abstract method it invokes child override before child is initialized. Result: NullPointerException or wrong behavior
62
How can you do constructor chaining in Java?
Use this() to call another constructor in the same class. Use super() to call a parent class constructor. Either call must be the first statement in the constructor. This avoids code duplication across overloaded constructors
63
MEMORY BOOSTER: Constructor chaining
this() = call another constructor in same class. super() = call parent constructor. Must be FIRST statement. Cannot use both in same constructor. Chain: specific constructor delegates to general constructor for DRY initialization
64
How can we find the memory usage of JVM from Java code?
Use Runtime class: Runtime.getRuntime().freeMemory() for free memory - totalMemory() for total allocated memory - maxMemory() for maximum heap size. All values are in bytes
65
MEMORY BOOSTER: JVM memory from code
Runtime.getRuntime().freeMemory() = available heap. totalMemory() = currently allocated. maxMemory() = maximum possible heap (set by -Xmx). Used memory = totalMemory() - freeMemory(). All values in bytes
66
What is the difference between x == y and x.equals(y) in Java?
x == y compares object references - true only if both point to the exact same object in memory. x.equals(y) compares logical equality based on the overridden equals() implementation which compares by value
67
MEMORY BOOSTER: == vs equals()
== = same object in memory (reference equality). equals() = same value (logical equality). Two new String objects with same text are NOT == but ARE equals(). Always use equals() for String comparison - never ==
68
Can you guarantee that garbage collection will take place in Java?
No - Java documentation explicitly states GC is not guaranteed. System.gc() is only a request that the JVM may ignore. GC runs at the JVM's discretion when memory is low
69
MEMORY BOOSTER: Garbage collection guarantee
System.gc() = request only = JVM may ignore. No guarantee of WHEN GC runs. To make object eligible for GC: set all references to null and ensure no other object holds a reference. GC is automatic and non-deterministic
70
What is the relation between hashCode() and equals() methods?
Contract: if x.equals(y) is true then x.hashCode() must equal y.hashCode(). But two objects with the same hashCode are not necessarily equal. Equal objects must have same hash. Same hash does not guarantee equality
71
MEMORY BOOSTER: hashCode/equals relation
equals true => hashCode same (mandatory). hashCode same => equals may be false (collision is ok). Break the contract = broken HashMap/HashSet. Always override both together. IDEs can auto-generate a consistent correct pair
72
What is a compile time constant in Java?
A compile time constant is a public static final variable whose value is known at compile time. The compiler replaces all references to it with the actual value inline making them faster than regular variables
73
MEMORY BOOSTER: Compile time constant
public static final int MAX = 100 = compile time constant. Compiler inlines the value everywhere MAX is used. Must be primitive or String with a literal value. Changing the constant requires recompiling all classes that use it
74
What is the difference between fail-fast and fail-safe iterators?
Fail-fast iterators throw ConcurrentModificationException if the collection is modified during iteration. They work on the original collection. Fail-safe iterators work on a copy and never throw this exception. ArrayList and HashMap are fail-fast. ConcurrentHashMap and CopyOnWriteArrayList are fail-safe
75
MEMORY BOOSTER: Fail-fast vs fail-safe
Fail-fast = original collection + ConcurrentModificationException on modification. Fail-safe = copy of collection + no exception. ArrayList/HashMap = fail-fast. ConcurrentHashMap/CopyOnWriteArrayList = fail-safe. Fail-fast detects bugs. Fail-safe prioritizes availability
76
Between a character array and a String which is more secure for storing sensitive data like passwords?
char[] is more secure. String is immutable and stays in the String pool until garbage collected - you cannot control when it clears. A char[] can be explicitly zeroed out immediately after use with Arrays.fill(password - '\0')
77
MEMORY BOOSTER: char[] vs String for passwords
String = immutable = stays in memory until GC = visible in memory dump. char[] = mutable = can be zeroed immediately after use. Best practice: use char[] for passwords and call Arrays.fill(pwd - '\0') when done. Java security APIs use char[] for this reason
78
Why do you use the volatile keyword in Java?
volatile guarantees that reads and writes to a variable always go directly to main memory. It prevents threads from caching the variable locally ensuring all threads always see the most current value
79
MEMORY BOOSTER: volatile keyword
volatile = always read/write from main memory + never cache locally. Solves visibility problem between threads. Does NOT solve atomicity (i++ is still not thread-safe with volatile). Use volatile for simple flags and status variables not compound operations
80
What is the difference between poll() and remove() methods of Queue?
Both remove and return the head of the Queue. When the Queue is empty: poll() returns null gracefully. remove() throws NoSuchElementException
81
MEMORY BOOSTER: poll() vs remove()
poll() = remove head + null if empty (safe). remove() = remove head + exception if empty (strict). Same pattern: peek() = look at head + null if empty. element() = look at head + exception if empty. poll/peek = polite. remove/element = strict
82
Can you catch an exception thrown by another thread in Java?
Yes - use Thread.UncaughtExceptionHandler. Set it on the thread with thread.setUncaughtExceptionHandler(handler). When an uncaught exception terminates the thread the JVM calls uncaughtException(thread - exception) on the handler
83
MEMORY BOOSTER: Catch exception from another thread
Thread.UncaughtExceptionHandler = catch uncaught exceptions from other threads. Set with thread.setUncaughtExceptionHandler(handler). Handler method: uncaughtException(Thread t - Throwable e). Also set globally: Thread.setDefaultUncaughtExceptionHandler()
84
When should you use a Static vs Non-static inner class in Java?
Use static nested class when it does not need access to outer class instance members or when instances may outlive the outer class to prevent memory leaks. Use non-static inner class when it needs direct access to outer class members
85
Why can non-static inner classes cause memory leaks?
Every non-static inner class instance holds a hidden reference to its outer class instance. If the inner class outlives the outer class the outer class cannot be garbage collected even if nothing else references it
86
MEMORY BOOSTER: Static vs non-static inner class
Non-static inner class = hidden reference to outer = risk of memory leak. Static nested class = no reference to outer = safer. Prefer static nested class when inner class does not need outer instance. Event handlers and callbacks are common leak sources
87
What are the different types of Classloaders in Java?
Bootstrap Classloader loads core Java API (rt.jar) from the JRE lib folder. Extension Classloader loads jars from lib/ext folder. System/Application Classloader loads jars from the CLASSPATH environment variable
88
What is the parent delegation model in Java Classloading?
When a classloader receives a request to load a class it delegates to its parent first. Only if the parent cannot find the class does the child attempt to load it. This ensures core classes are always loaded by Bootstrap classloader
89
MEMORY BOOSTER: Java Classloaders
3 types: Bootstrap (core Java rt.jar) > Extension (lib/ext jars) > System/Application (CLASSPATH jars). Parent delegation: child always asks parent first. Bootstrap = top parent = no parent itself. Classloaders form a hierarchy
90
In which situations should you choose HashSet over TreeSet?
HashSet is O(1) for add/remove/contains - faster for most use cases when order does not matter. TreeSet is O(log n) but maintains natural sorted order. Use TreeSet when you need sorted elements or range queries
91
MEMORY BOOSTER: HashSet vs TreeSet selection
HashSet = O(1) = fast = unordered. TreeSet = O(log n) = slower = always sorted. Default: use HashSet. Switch to TreeSet only when: sorted order needed OR range queries needed OR elements must be iterated in natural order
92
What is the use of method references in Java 8?
Method references allow methods and constructors to be used as lambdas. They improve code organization - clarity and terseness. Types: static method ref - instance method ref - instance method of arbitrary type - constructor ref
93
MEMORY BOOSTER: Method references
Method reference = shorthand for lambda calling a single method. list.forEach(System.out::println) vs list.forEach(s -> System.out.println(s)). 4 types: Class::staticMethod - instance::method - Class::instanceMethod - Class::new (constructor ref)
94
Are Java Enums more powerful than integer constants?
Yes - Enums are type-safe while integer constants are not. Enums can implement interfaces - have methods and carry metadata. They behave like final classes with a fixed set of instances. You can also define custom behavior per enum value
95
MEMORY BOOSTER: Java Enums vs integer constants
Enum wins: type-safe + can have methods + can implement interfaces + can carry data + switch support + IDE support. int constant: no type safety + no behavior + no metadata. Use Enums for any fixed set of related constants
96
Why do we use static initializers in Java?
Static initializers run once when the class is first loaded and finish before the class can be accessed. They are used for complex static initialization that cannot be done in a single field declaration. They are simpler than initializing static members in every constructor
97
MEMORY BOOSTER: Static initializers
static { } block = runs ONCE on class load + before any constructor + JVM thread-safe during class loading. Perfect for: complex static field initialization + loading native libraries + initializing static collections. Guaranteed to complete before any instance is created
98
Your code throws NoClassDefFoundError or NoSuchMethodError at runtime even though it compiled fine. What is the reason?
Version mismatch between compile-time and runtime libraries. A dependency was upgraded but the old version is still on the runtime classpath or a new version is missing a class or method that existed in the old version
99
MEMORY BOOSTER: NoClassDefFoundError vs NoSuchMethodError
Both = runtime class/method missing despite successful compilation. Root cause: library version mismatch. Compile with version A + run with version B = error. Fix: align compile-time and runtime classpath versions. Use Maven or Gradle to manage dependency versions
100
How can you check if a String is a number by using regular expression?
A numeric String contains only digits 0-9 with optional leading + or - sign. Use Pattern.compile and test with matches(). Example pattern for integers: "-?\\d+". For decimals add optional decimal part
101
MEMORY BOOSTER: Check if String is a number
Two approaches: 1) Regex pattern for digits with optional sign. 2) Try-parse: try Double.parseDouble(s) and return true - catch NumberFormatException and return false. Try-parse handles more edge cases including scientific notation
102
What is the difference between String s = "Temporary" and String s = new String("Temporary")?
String s = "Temporary" reuses an existing String from the pool if one exists. new String("Temporary") always creates a new object outside the pool even if an identical String already exists. The literal approach is more memory efficient
103
MEMORY BOOSTER: String literal vs new String()
Literal = uses String pool = reuses existing object = memory efficient. new String() = ALWAYS creates new object on heap = wasteful. Two literals with same value share one pool object. Always prefer literals. Use intern() to add a new String() to the pool if needed
104
In Java can two equal objects have different hash codes?
No - if two objects are equal according to equals() they must have the same hashCode. This is a mandatory contract. Violating it breaks HashMap - HashSet and all hash-based collections
105
MEMORY BOOSTER: Equal objects and hashCode
Equal objects MUST have equal hashCodes (mandatory contract). Equal hashCodes do NOT guarantee equal objects (collision is ok). Violating: equal objects may not be found in HashMap - duplicates appear in HashSet. Always override equals() and hashCode() together
106
How can we print an Array in Java?
Use Arrays.toString(array) for a one-dimensional array. Use Arrays.deepToString(array) for multi-dimensional arrays. Passing an array directly to System.out.println only prints the memory address reference not the contents
107
MEMORY BOOSTER: Print an array
Arrays.toString(arr) = [1 - 2 - 3]. Arrays.deepToString(arr2D) = [[1 - 2] - [3 - 4]]. System.out.println(arr) = useless memory address. Import: java.util.Arrays. List.toString() works because List overrides toString() but arrays do not
108
Is it ok to use random numbers in the implementation of hashCode() in Java?
No - hashCode() must always return the same value for the same object state. Using random numbers violates this contract. HashMap relies on consistent hashCodes to store and retrieve objects in the correct bucket
109
MEMORY BOOSTER: hashCode() must be consistent
hashCode() must return SAME value for same object state every time it is called. Random = inconsistent = broken HashMap. Contract: same object = same hashCode always. Mutable objects as HashMap keys can also break this if state changes after insertion
110
Between constructor injection and setter injection which is better?
Constructor injection is better for mandatory dependencies guaranteeing a fully initialized object at creation. Setter injection is better for optional dependencies providing flexibility. Best practice: constructor for required + setter for optional
111
MEMORY BOOSTER: Constructor vs setter injection
Constructor injection = mandatory dependencies = always valid after construction = better for testing. Setter injection = optional dependencies = flexible = object may be partially initialized. Spring supports both. Constructor injection generally preferred
112
What is the difference between DOM and SAX parser in Java?
DOM loads the entire XML into memory as a tree - fast for navigation and modification but uses lots of memory. SAX is event-based and processes XML sequentially without loading it all - better for large files but read-only and harder to use
113
MEMORY BOOSTER: DOM vs SAX parser
DOM = entire XML in memory = tree structure = fast search and modify = bad for large files. SAX = event-driven = stream-based = low memory = good for large files = read-only. Rule: large file = SAX. Small file needing modification = DOM
114
Between Enumeration and Iterator which one has better performance?
Enumeration has better performance - approximately twice as fast as Iterator and uses less memory. Iterator is safer because it is fail-fast and detects concurrent modification. Use Iterator in modern code for safety
115
MEMORY BOOSTER: Enumeration vs Iterator performance
Enumeration = faster (2x) + less memory + no remove() + not fail-fast. Iterator = slower + has remove() + fail-fast + safer. Trade-off: speed vs safety. Modern code: always use Iterator. Enumeration only in legacy code with Vector/Hashtable
116
What is the difference between pass by value and pass by reference?
Pass by value passes a copy of the value - changes do not affect the original. Pass by reference passes a reference to the actual object - changes affect the original. Java always passes by value but for objects passes a copy of the reference
117
Is Java pass by value or pass by reference?
Java is always pass by value. For primitives it passes a copy of the value. For objects it passes a copy of the reference. You can modify the object through the reference but cannot make the caller's reference point to a different object
118
MEMORY BOOSTER: Pass by value vs reference in Java
Java = ALWAYS pass by value. Primitive: copy of value = original unchanged. Object: copy of REFERENCE = can modify object contents = cannot change what caller's reference points to. Reassigning the parameter inside the method does not affect the caller
119
What are the different ways to sort a collection in Java?
Collections.sort(list) for natural order requiring Comparable. Collections.sort(list - comparator) for custom order. TreeSet or TreeMap for automatically sorted collections. Stream.sorted() for functional-style sorting
120
MEMORY BOOSTER: Sorting collections
Collections.sort(list) = natural order (needs Comparable). Collections.sort(list - comparator) = custom order. TreeSet/TreeMap = always sorted automatically. list.sort(comparator) = modern alternative. stream.sorted().collect() = functional style
121
Why does Collection interface not extend Cloneable and Serializable?
Collection is an abstract representation. Each concrete implementation should decide how it is cloned or serialized. Not all collections can be meaningfully cloned. Forcing it on the interface would be inappropriate since Collection is just a contract for grouping elements
122
MEMORY BOOSTER: Collection not Cloneable/Serializable
Collection = abstract contract = specifies WHAT not HOW. Cloning and serialization are implementation details. ArrayList is Serializable. Some custom collections may not be. Forcing it on Collection interface would violate design principles
123
What is the difference between a process and a thread in Java?
A process is an execution of a program with its own private memory space. A thread is a single execution sequence within a process. A process can contain multiple threads. Threads within a process share memory making them lightweight and fast to communicate
124
MEMORY BOOSTER: Process vs Thread
Process = own memory = heavyweight = isolated. Thread = shared memory within process = lightweight = fast communication. Process is like an app. Thread is like a task within that app. Multiple threads share the heap but each has its own stack
125
What are the benefits of using an unordered array over an ordered array?
Insertion into an unordered array is O(1) - just append to the end. Ordered array insertion is O(n) because elements must be shifted. Use unordered array when you have more writes than reads
126
MEMORY BOOSTER: Unordered vs ordered array
Unordered: insert O(1) + search O(n). Ordered: insert O(n) + search O(log n) via binary search. Rule: write-heavy = unordered. Read-heavy = ordered. Ordered array enables binary search making reads much faster at the cost of slower insertions
127
When does JVM call the finalize() method?
JVM instructs the Garbage Collector to call finalize() just before releasing an object from memory. It allows cleanup of resources. Note: finalize() is deprecated in Java 9 and removed in Java 18 - use try-with-resources or Cleaner API instead
128
MEMORY BOOSTER: finalize() method
finalize() = called by GC before object is collected = cleanup hook. Deprecated Java 9 - removed Java 18. Never rely on it for critical cleanup - GC timing is non-deterministic. Use try-with-resources or Cleaner API for resource cleanup
129
When would you use Serial GC or Throughput GC in Java?
Serial GC is for small applications with heap up to 100MB or single-threaded environments. Throughput GC (Parallel GC) is for medium to large Java applications where maximizing throughput is more important than pause time
130
MEMORY BOOSTER: Serial vs Throughput GC
Serial GC = single thread + small apps + heap up to 100MB. Throughput/Parallel GC = multiple threads + medium/large apps + maximize throughput. G1 GC = balanced latency and throughput (Java 9+ default). ZGC/Shenandoah = ultra-low pause times
131
If you set an object reference to null will the Garbage Collector immediately free the memory?
No - setting a reference to null only makes the object eligible for garbage collection. The GC runs at the JVM's discretion when memory is low. Memory is freed during the next GC cycle not immediately
132
MEMORY BOOSTER: null reference and GC
null = eligible for GC = NOT immediate collection. GC runs when JVM decides. Object must have NO strong references to be collected. Setting to null removes one reference but if other references exist the object stays alive until all references are gone
133
When do you use Exception or Error in Java?
Use Exception for conditions the program can handle or recover from. Use Error for serious unexpected situations the program cannot recover from like OutOfMemoryError or StackOverflowError. Both extend Throwable
134
MEMORY BOOSTER: Exception vs Error
Exception = recoverable = application-level = checked or unchecked. Error = non-recoverable = JVM-level problem = do not catch in application code. Throwable is parent of both. Examples: IOException (Exception) vs OutOfMemoryError (Error)
135
What is the advantage of PreparedStatement over Statement in Java?
PreparedStatement is precompiled making it faster especially when reused with different parameters. It also prevents SQL injection by parameterizing inputs. Statement does not offer these benefits and is vulnerable to SQL injection via string concatenation
136
MEMORY BOOSTER: PreparedStatement vs Statement
PreparedStatement = precompiled + parameterized + reusable + SQL injection safe + faster. Statement = compiled each time + string concatenation + injection risk + slower. Always use PreparedStatement for user input. Statement only for static queries with no user data
137
What is the difference between throw and throws keywords in Java?
throw explicitly raises an exception in code: throw new IOException(). throws in method signature declares what checked exceptions the method may throw. throws can list multiple exceptions. throw uses one exception at a time
138
MEMORY BOOSTER: throw vs throws
throw = action = raise exception now = in method body. throws = declaration = warns callers = in method signature. throw uses ONE exception. throws can list MULTIPLE. throw new Exception() vs public void method() throws IOException
139
What happens to the Exception object after exception handling is done?
After the catch block completes the Exception object goes out of scope and becomes eligible for garbage collection. It is collected in the next GC run like any other unreachable object
140
MEMORY BOOSTER: Exception object lifecycle
Exception = regular Java object = subject to GC. After catch block exits: Exception object unreachable = eligible for GC. No special cleanup needed. The exception message and stack trace are part of the object and also get collected
141
How do you find which client machine is sending a request to your servlet?
Use ServletRequest methods: getRemoteAddr() returns the IP address of the client machine and getRemoteHost() returns the hostname of the client machine
142
MEMORY BOOSTER: Client machine in Servlet
request.getRemoteAddr() = client IP address. request.getRemoteHost() = client hostname. getRemotePort() = client port. getServerName() = server hostname. All available via HttpServletRequest in any servlet
143
What is the difference between a Cookie and a Session in Java?
A Cookie is stored on the client and can be disabled by the client. A Session is stored on the server and cannot be disabled. Session can store any Java object. Cookie can only store small String values. Session always works regardless of client settings
144
MEMORY BOOSTER: Cookie vs Session
Cookie = client-side + can be disabled + String data only + size limited. Session = server-side + always available + any Java object + more secure. Session uses a JSESSIONID cookie to track the user but the actual data lives on the server
145
Which protocol do Browser and Servlet use to communicate?
HTTP protocol. The Browser and Servlet communicate with each other using the HTTP protocol
146
MEMORY BOOSTER: Browser-Servlet protocol
Browser and Servlet communicate via HTTP. Request from browser = HTTP request. Response from servlet = HTTP response. HTTPS for secure communication. This is the foundation of all Java web applications
147
What is HTTP Tunneling?
HTTP Tunneling is a technique where HTTP or HTTPS protocol encapsulates communications done by other protocols. It masks other protocol requests as HTTP requests. Commonly used to bypass firewalls that only allow HTTP traffic
148
MEMORY BOOSTER: HTTP Tunneling
HTTP Tunneling = wrap other protocols inside HTTP. Why: firewalls allow HTTP/HTTPS but block other ports. Example: SSH over HTTP - VPN over HTTPS. The inner protocol is invisible to the firewall. Used both legitimately and to bypass security
149
Why do we use JSP instead of Servlet in Java?
JSP pages are dynamically compiled into servlets and allow easy updates to presentation layer code. They can be pre-compiled for performance. JSP provides flexibility to combine HTML or XML templates. Programmers can change class logic without editing JSP pages
150
MEMORY BOOSTER: JSP vs Servlet
JSP = easier presentation layer = HTML with embedded Java = compiled to servlet automatically. Servlet = pure Java = more control = harder for HTML. JSP is better for view layer. Servlet is better for controller/business logic. MVC pattern uses both
151
Is an empty .java filename a valid source file name in Java?
Yes - you can create a class and store it in a file named .java (just a dot followed by java). It can be compiled and run successfully
152
MEMORY BOOSTER: Empty .java filename
A file named just .java (no name before the dot) is a valid Java source file. The class inside it can be compiled with javac .java and run. Unusual but valid - good trick question answer
153
How do you implement Servlet Chaining in Java?
Servlet Chaining passes the output of one Servlet as input to the next forming a pipeline. Use RequestDispatcher.forward() to pass the request from one servlet to another. The last servlet in the chain sends the final response to the client
154
MEMORY BOOSTER: Servlet Chaining
Servlet Chaining = pipeline of servlets. Servlet A output -> Servlet B input -> final response to client. Use RequestDispatcher.forward(request - response) to chain. Last servlet writes the final response. Similar to pipes in Unix command line
155
Can you instantiate a class that has the field A a = new A() inside it?
No - this results in infinite recursive constructor calls. Each new A() triggers the constructor which initializes the field by calling new A() again causing a StackOverflowError
156
MEMORY BOOSTER: Recursive instantiation
The field A a = new A() inside class A causes StackOverflowError on instantiation. Constructor triggers infinite recursion. Each A instantiation tries to create another A before the current one finishes. Fields initialize as part of constructor
157
Why does Java not support operator overloading?
Operator overloading would make the language more complex - require a more complex compiler and slow down JVM performance because the JVM would need to determine operator meanings at runtime. Java favors simplicity and readability
158
MEMORY BOOSTER: No operator overloading in Java
Java: method overloading YES - operator overloading NO. Reasons: simplicity + no complex compiler + better JVM performance + avoids confusion. C++ and Kotlin allow it. Java strings do use + but that is a built-in special case not user-definable
159
Why is String class Immutable and Final in Java?
String is immutable because String objects are cached in a pool and shared between clients. A mutable String would allow one client to affect another's access to the pool. String is Final to prevent subclasses from overriding and breaking immutability. String is also used in security-sensitive operations like network connections
160
MEMORY BOOSTER: Why String is Immutable and Final
Immutable = String pool sharing is safe. Final = no subclass can break immutability. Security: String used in class loading - network connections - file paths. Thread-safe: immutable objects are inherently thread-safe. Performance: pool caching reduces object creation
161
What is the difference between sendRedirect and forward methods in Servlets?
sendRedirect creates a new request making the client see a new URL and losing previous request scope objects. forward passes the same request to a new server resource preserving request scope objects and keeping the same client URL. forward is faster
162
MEMORY BOOSTER: sendRedirect vs forward
sendRedirect = new request + client URL changes + request scope lost + slower. forward = same request + client URL unchanged + scope preserved + faster. Use forward for internal server navigation. Use sendRedirect for external URLs or to prevent POST resubmission
163
How do you fix a Serializable class that contains a non-serializable member?
Mark the non-serializable member as transient. Transient fields are excluded from serialization and are set to their default values upon deserialization
164
MEMORY BOOSTER: transient keyword
transient = excluded from serialization. Non-serializable field must be transient or class throws NotSerializableException. After deserialization transient fields = default value (null for objects - 0 for numbers - false for boolean). Use for: passwords - DB connections - calculated fields
165
What is the use of runtime polymorphism in Java?
Runtime polymorphism allows an object's behavior to be determined at runtime based on its actual type. When a child class overrides a parent method the JVM calls the child's version even when accessed via a parent reference. This enables flexible extensible code
166
MEMORY BOOSTER: Runtime polymorphism
Runtime polymorphism = method override + parent reference + child object. Parent p = new Child() then calling p.method() invokes Child.method() at runtime. Determined by actual object type not reference type at compile time
167
What are the rules of method overloading and method overriding in Java?
Overloading: same method name + different parameter count/types/order + can have different return type + same class. Overriding: same name + same parameters + same or covariant return type + cannot throw new or broader checked exceptions + cannot override static/final/private methods
168
MEMORY BOOSTER: Overloading vs overriding rules
Overloading = same name + different signature = compile-time resolution. Overriding = same name + same signature = runtime resolution. Override rules: same params + same/narrower return + no new checked exceptions + not static/final/private. Overloading just needs a different parameter list
169
What is the difference between a class and an object in Java?
A class is a blueprint or template defining fields and methods. An object is an instance of a class with actual values in its fields. A class exists at compile time. An object exists at runtime. One class can produce many objects
170
MEMORY BOOSTER: Class vs Object
Class = blueprint = no data memory allocated. Object = instance = memory allocated = actual values. Class is like a house plan. Object is the actual house. new keyword creates an object from a class. One class = unlimited object instances
171
Can we create an abstract class that extends another abstract class?
Yes - an abstract class can extend another abstract class without implementing its abstract methods. The chain of abstraction continues until a concrete (non-abstract) class must implement all inherited abstract methods
172
MEMORY BOOSTER: Abstract extends abstract
Abstract A <- Abstract B <- Concrete C. Only C must implement all abstract methods from A and B. B can ignore A's abstract methods and add its own. The first concrete class must implement everything inherited from all abstract parents
173
Why do you use Upcasting or Downcasting in Java?
Upcasting (widening) casts a subclass to a superclass - always safe and implicit. Downcasting (narrowing) casts a superclass to a subclass - requires explicit cast and can throw ClassCastException if the object is not actually of the target type
174
MEMORY BOOSTER: Upcasting vs Downcasting
Upcasting = child to parent = widening = automatic = always safe. Downcasting = parent to child = narrowing = explicit cast = may throw ClassCastException. Use instanceof before downcasting to be safe
175
What is the reason to organize classes and interfaces in a package in Java?
Packages group related classes - prevent naming conflicts (namespace management) - enable access control via access modifiers and provide better organization making code easier to navigate and maintain
176
MEMORY BOOSTER: Packages in Java
Package = namespace + access control + organization. Prevents name collision (java.util.Date vs java.sql.Date). Package-private access = visible only within the same package. Naming convention: reverse domain name (com.company.project.module)
177
What is information hiding in Java?
Information hiding is an OOP concept achieved through encapsulation. Objects use access modifiers (private - protected - public) to hide internal details from other objects. This allows changing internal implementation without affecting external calling code
178
MEMORY BOOSTER: Information hiding
Information hiding = encapsulation = private fields + public methods. Hides HOW from the outside world. Exposes only WHAT is needed. Change internal implementation without breaking callers. private = hidden. public = exposed contract. protected = accessible to subclasses
179
Why does Java provide a default constructor?
Java provides a default no-arg constructor when no constructor is defined allowing object creation without arguments. It also initializes member variables to their default values (0 - null - false etc.)
180
Why should you define your own default constructor?
To control default initialization values - to make it private to prevent instantiation (Singleton pattern) - or to add specific logic that runs when an object is created without arguments
181
MEMORY BOOSTER: Default constructor
Java auto-generates default constructor IF no constructor is defined. Once you define ANY constructor Java no longer provides one. Private default constructor = prevents instantiation = Singleton or utility class. Define explicitly when you need controlled default behavior
182
What is the difference between super and this keywords in Java?
this refers to the current object instance and calls methods or accesses fields of the current class or calls another constructor in the same class via this(). super refers to the parent class and calls parent methods or constructor via super()
183
MEMORY BOOSTER: super vs this
this = current class = this.field + this() for same-class constructor call. super = parent class = super.method() + super() for parent constructor call. Both super() and this() must be the first statement in a constructor. Cannot use both in the same constructor
184
What is the advantage of using Unicode characters in Java?
Unicode supports a much larger character set than ASCII including Asian - Arabic and non-western European characters. Java uses Unicode natively making it suitable for internationalized applications. Most modern technologies and browsers support Unicode
185
MEMORY BOOSTER: Unicode in Java
Java uses Unicode (UTF-16) internally for all characters. char = 16-bit Unicode character. Supports 65536+ characters including all world scripts. Use StandardCharsets.UTF_8 for file I/O for consistency across platforms. Internationalization (i18n) support built in
186
Can you override an overloaded method in Java?
Yes - Java allows overriding an overloaded method as long as the method is not static or final
187
MEMORY BOOSTER: Override an overloaded method
Overloaded method = can be overridden if it is not static or final. Overloading and overriding are independent concepts. A class can have multiple overloaded versions and a subclass can override any or all of them
188
How can we change the heap size of a JVM?
Use -Xms to set the initial heap size and -Xmx to set the maximum heap size. Example: java -Xms512m -Xmx2g MyApp sets initial heap to 512MB and maximum to 2GB
189
MEMORY BOOSTER: JVM heap size parameters
-Xms = initial heap size. -Xmx = maximum heap size. -Xss = thread stack size. Example: java -Xms256m -Xmx1g MyApp. If heap exceeds -Xmx: OutOfMemoryError. Set -Xms equal to -Xmx to avoid heap resize overhead in production
190
How will you make an Object Immutable in Java?
Make all fields private and final. Provide no setter methods. Declare the class as final. Return defensive copies of mutable fields from getters. Make defensive copies of mutable objects passed to the constructor
191
MEMORY BOOSTER: Making an Immutable Object
5 rules: private+final fields + no setters + final class + defensive copy in constructor + return copies from getters. String and Integer are classic examples. Immutable objects are inherently thread-safe requiring no synchronization
192
How can you prevent SQL injection in Java code?
Use PreparedStatement with parameterized queries instead of string concatenation. PreparedStatement separates SQL structure from data so user input cannot alter the query logic
193
MEMORY BOOSTER: Prevent SQL injection
PreparedStatement = parameterized = SQL injection safe. String concat SQL = injection risk. Use prepStmt.setString(1 - userInput) not "SELECT * FROM t WHERE name='" + userInput + "'". Malicious input like ' OR '1'='1 cannot break PreparedStatement
194
Which two methods should always be implemented by a HashMap key object?
equals() and hashCode() must both be correctly implemented. hashCode() finds the bucket. equals() confirms the exact match within the bucket. Without both HashMap cannot reliably store or retrieve key-value pairs
195
Why should a HashMap key object be Immutable?
If a key object is mutable its hashCode may change after insertion into the HashMap. The map stored the entry in bucket X (old hash) but later searches bucket Y (new hash) and cannot find it. Immutable keys guarantee stable hashCodes
196
MEMORY BOOSTER: HashMap key requirements
Two requirements: equals() + hashCode(). Plus best practice: Immutable. Why immutable: changing key state changes hashCode = object becomes lost in wrong bucket. Use String - Integer or well-designed value objects as keys. Never use mutable objects as HashMap keys
197
How can you share an object between multiple threads?
Use BlockingQueue to safely pass objects between producer and consumer threads. Use Exchanger class for bidirectional object swapping between two threads. Shared volatile variables or synchronized access also work for simpler scenarios
198
MEMORY BOOSTER: Share object between threads
BlockingQueue = producer-consumer object passing. Exchanger = two threads swap objects bidirectionally. Shared volatile field = simple reference sharing. synchronized block = controlled mutable state access. Choose based on the complexity of sharing needed
199
How can you determine if your program has a deadlock?
Take a thread dump (kill -3 on Linux or jstack) and look for deadlock messages. Programmatically use ThreadMXBean.findDeadlockedThreads() which returns IDs of deadlocked threads. JConsole has a Detect Deadlock button on the Threads tab
200
MEMORY BOOSTER: Detect deadlock
3 methods: 1) Thread dump via kill -3 or jstack - look for deadlock text. 2) ThreadMXBean.findDeadlockedThreads() programmatically. 3) JConsole Threads tab > Detect Deadlock button. Thread dump is fastest for production issues. ThreadMXBean for automated monitoring