| Primitive Types | byte, short, int, long, float, double, char, boolean |
| int range | -2,147,483,648 to 2,147,483,647 (32-bit signed) |
| long literal | Suffix L: long x = 100L; |
| float vs double | float: 32-bit, 7 digits; double: 64-bit, 15 digits |
| Widening | byte→short→int→long→float→double (automatic) |
| Narrowing | Requires explicit cast; may lose data |
| String pool | String literals stored in Heap's String Constant Pool |
| var (Java 10+) | Local variable type inference — compiler infers type |
Java Data Types Interview Questions & Answers
Q1. What are the 8 primitive data types in Java?
A: Java has 8 primitive types: byte (8-bit, -128 to 127), short (16-bit), int (32-bit), long (64-bit), float (32-bit IEEE 754), double (64-bit IEEE 754), char (16-bit Unicode, 0–65535), and boolean (true/false). Primitives are stored on the stack and hold values directly.
Q2. What is the difference between int and Integer in Java?
A: int is a primitive type stored on the stack; Integer is a wrapper class (reference type) stored on the heap. Java auto-boxes/unboxes between them. Integer can be null; int cannot. Use int for performance in calculations; use Integer when you need nullability or a collection element.
int a = 5;
Integer b = 5; // autoboxing
int c = b; // unboxing
Integer d = null; // valid
// int e = null; // COMPILE ERROR
Q3. What is autoboxing and unboxing?
A: Autoboxing is the automatic conversion of a primitive to its wrapper class (e.g., int → Integer). Unboxing is the reverse. Java compiler inserts the conversion calls. Beware: unboxing a null Integer throws NullPointerException.
List<Integer> list = new ArrayList<>();
list.add(42); // autoboxing: 42 → Integer.valueOf(42)
int x = list.get(0); // unboxing: Integer → int
Integer n = null;
int y = n; // NullPointerException!
Q4. What is widening and narrowing type conversion?
A: Widening (implicit) goes from smaller to larger type: byte→short→int→long→float→double. No data loss. Narrowing (explicit cast) goes from larger to smaller and may lose data or precision. Always requires explicit cast operator.
int i = 100;
long l = i; // widening — automatic
double d = l; // widening — automatic
double pi = 3.14;
int piInt = (int) pi; // narrowing — explicit cast, piInt = 3 (truncated)
Q5. Why should you avoid float/double for monetary values?
A: Floating-point types (float/double) use IEEE 754 binary representation which cannot exactly represent most decimal fractions (e.g., 0.1 is stored as 0.100000000000000005551…). Always use BigDecimal for financial calculations. Initialize from String constructor, not double, to avoid precision loss at creation.
System.out.println(0.1 + 0.2); // 0.30000000000000004 !!
BigDecimal a = new BigDecimal("0.1");
BigDecimal b = new BigDecimal("0.2");
System.out.println(a.add(b)); // 0.3 — correct
Q6. What is the default value of primitive types?
A: Class-level fields (instance/static) get default values: byte/short/int/long = 0, float/double = 0.0, char = '\u0000', boolean = false, and reference types = null. Local variables have NO default — using them uninitialized is a compile error.
Q7. What is the difference between == and .equals() for String?
A: == compares object references (memory addresses). .equals() compares content. String literals are interned in the String pool so two literals with the same content share a reference (== returns true). Strings created with new are separate objects on heap (== returns false even if same content).
String a = "hello";
String b = "hello";
String c = new String("hello");
System.out.println(a == b); // true (same pool object)
System.out.println(a == c); // false (c is new object)
System.out.println(a.equals(c)); // true (same content)
Q8. What is String interning?
A: String interning stores a canonical copy of each string in the String Constant Pool (part of heap in Java 7+). String.intern() returns the pooled instance. Two interned strings with equal content share the same reference. Interning reduces memory when the same string repeats many times (e.g., enum-like values).
Q9. What is a char and can it hold Unicode characters?
A: char is an unsigned 16-bit type holding a single UTF-16 code unit (range 0–65535 or '\u0000'–'\uFFFF'). It can hold Basic Multilingual Plane Unicode characters but NOT supplementary characters (code points above U+FFFF) — those need a surrogate pair (two chars) or use int code points via String.codePoints().
Q10. What is the difference between && and & operators?
A: && is the logical AND with short-circuit evaluation — if the left operand is false, the right is NOT evaluated. & is the bitwise AND (also works on booleans without short-circuit). Short-circuit is important when the right side has side effects or can throw exceptions.
String s = null;
if (s != null && s.length() > 0) { /* safe */ }
if (s != null & s.length() > 0) { /* NullPointerException! */ }
Q11. What is the ternary operator and when should you avoid it?
A: The ternary operator condition ? exprTrue : exprFalse is a compact if-else expression. Avoid nesting ternaries more than 1-2 levels deep — it hurts readability. Avoid when the expression has side effects, as it can confuse readers about what runs when.
Q12. What is integer overflow and how do you detect it?
A: Integer overflow happens when an arithmetic result exceeds the type's range — the value wraps around silently. Java does NOT throw an exception. Use Math.addExact(), Math.multiplyExact() etc. (Java 8+) which throw ArithmeticException on overflow. Or use long / BigInteger for large values.
int max = Integer.MAX_VALUE; // 2147483647
System.out.println(max + 1); // -2147483648 — overflow, no exception!
Math.addExact(max, 1); // throws ArithmeticException
Q13. What is the difference between prefix (++i) and postfix (i++) operators?
A: ++i increments i BEFORE the expression is evaluated; i++ returns the current value THEN increments. Both increment by 1, but the value returned differs. In standalone statements, both are equivalent. The distinction matters inside expressions like arr[i++].
Q14. What are bitwise operators in Java?
A: Java bitwise operators: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (signed right shift), >>> (unsigned right shift). Used in flags, permissions, hash functions, and low-level operations.
int flags = 0b0000;
int READ = 1 << 0; // 0001
int WRITE = 1 << 1; // 0010
flags |= READ; // set READ flag
boolean canRead = (flags & READ) != 0; // check flag
flags &= ~WRITE; // clear WRITE flag
Q15. What is the difference between >> and >>> operators?
A: >> is signed right shift — fills leftmost bits with the sign bit (preserves sign). >>> is unsigned right shift — fills with zeros regardless of sign. For negative numbers: -8 >> 1 = -4; -8 >>> 1 = 2147483644.
Q16. What is the var keyword introduced in Java 10?
A: var enables local variable type inference — the compiler infers the type from the initializer. Only valid for local variables, for-loop variables, and try-with-resources. Cannot be used for method parameters, return types, class fields, or when initializer is null.
var list = new ArrayList<String>(); // compiler infers ArrayList<String>
var map = Map.of("a", 1, "b", 2); // Map<String, Integer>
// var x = null; // COMPILE ERROR — cannot infer type
Q17. What is the difference between final, finally, and finalize?
A: final: keyword — makes variable constant, method non-overridable, class non-extendable. finally: block in try-catch that always executes (cleanup code). finalize(): deprecated Object method called by GC before object collection — avoid using it (use Cleaner or try-with-resources instead).
Q18. Can you reassign a final variable?
A: No — a final local variable or field can only be assigned once. For primitives, the value cannot change. For reference types, the reference cannot change but the object's state can be mutated. Blank final fields must be assigned in every constructor path.
Q19. What is the size of boolean in Java?
A: The JVM specification does not specify the exact byte size of boolean. In practice, the HotSpot JVM uses 1 byte for standalone boolean fields/variables and 1 bit in boolean arrays. Practically, treat it as undefined at language level — what matters is it holds true or false.
Q20. What is the difference between static and instance variables?
A: Static variables belong to the class (one copy shared by all instances, allocated in Metaspace). Instance variables belong to each object (allocated on the heap with the object). Static variables are initialized when the class is loaded; instance variables when the object is constructed.
Q21. What is the String.format() method?
A: String.format() creates a formatted string using format specifiers like %s (string), %d (integer), %f (float), %n (newline), %.2f (2 decimal places). Java 15+ also offers text blocks and Java 21+ adds string templates.
String msg = String.format("Hello %s, you are %d years old", "Raj", 30);
String price = String.format("Price: %.2f", 99.9); // "Price: 99.90"
Q22. What is type casting between numeric types?
A: Cast syntax: (targetType) value. Widening casts are implicit. Narrowing casts require explicit cast and may lose data: truncating for floating→integer, taking lower bytes for long→int. Double→int truncates (not rounds): (int) 3.9 = 3.
Q23. What happens when you divide an int by zero?
A: Integer division by zero throws ArithmeticException: / by zero at runtime. Floating-point division by zero does NOT throw — it returns Infinity (positive or negative) or NaN (0.0/0.0). Check with Double.isInfinite() or Double.isNaN().
// int x = 5 / 0; // ArithmeticException
double d = 5.0 / 0.0; // Infinity
double nan = 0.0 / 0.0; // NaN
System.out.println(nan == nan); // false! NaN != NaN
Q24. What is Integer cache in Java?
A: The JVM caches Integer objects for values -128 to 127. So Integer.valueOf(100) == Integer.valueOf(100) returns true (same cached object). For values outside this range, new objects are created, so == returns false. Always use .equals() to compare Integer values.
Integer a = 127, b = 127;
System.out.println(a == b); // true (cached)
Integer c = 128, d = 128;
System.out.println(c == d); // false (not cached)
System.out.println(c.equals(d)); // true
Q25. What are literals in Java?
A: Literals are fixed values in source code: integer (42, 0x1F hex, 0b1010 binary, 017 octal), long (100L), float (3.14f), double (3.14), char ('A'), boolean (true/false), String ("hello"), null. Java 7+ allows underscores in numeric literals: 1_000_000.
Q26. What is the difference between String, StringBuilder, and StringBuffer?
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Thread-safe | Yes (immutable) | No | Yes (synchronized) |
| Use case | Fixed text, keys | Single-thread string building | Multi-thread (rare, prefer StringBuilder + sync) |
Q27. What is the scope of a variable in Java?
A: Variable scope defines where it can be accessed. Local variables: from declaration to end of block {}. Instance variables: entire class (all methods). Static variables: entire class, accessible without an object. Method parameters: within that method only.
Q28. What is the difference between instance variable and local variable in memory?
A: Local variables are stored on the stack and garbage-collected when the method returns. Instance variables are stored on the heap as part of the object and GC'd when the object has no references. Stack access is faster but limited in size; heap is larger but slower.
Q29. Can you store a negative value in a char variable?
A: No — char is unsigned (0–65535). If you cast a negative int to char, it wraps around due to the unsigned nature: (char)(-1) = '\uFFFF'. Reading it back as int would give 65535, not -1. Never use char to store negative values.
Q30. What is the difference between local variable, instance variable, and class variable?
A: Local variables are declared inside methods/blocks, have no default value, and exist on the stack. Instance variables are non-static fields in a class, have default values, and exist in the heap (one per object). Class variables are static fields, have one copy per class, stored in Metaspace.
Q31. What is a constant in Java and how do you declare one?
A: Constants are declared with static final: public static final double PI = 3.14159;. By convention, constant names are UPPER_SNAKE_CASE. They must be initialized at declaration or in a static block. The compiler inlines simple constant values.
Q32. What is the difference between i++ and i += 1?
A: Functionally they increment by 1. However, i++ as an expression returns the pre-increment value. i += 1 also performs implicit narrowing cast if needed (e.g., byte b = 5; b += 1; compiles, but b = b + 1; does not without cast because arithmetic promotes to int).
Q33. What are wrapper classes and their use cases?
A: Wrapper classes (Integer, Double, Long, Float, Short, Byte, Character, Boolean) wrap primitives as objects. Use cases: storing in collections, null representation, utility methods (Integer.parseInt(), Integer.toBinaryString()), reflection, generics which don't support primitives.
Q34. What is the instanceof operator?
A: instanceof tests if an object is an instance of a class/interface. Returns false if the reference is null. Java 16+ adds pattern matching: if (obj instanceof String s) { s.length(); } — avoids explicit cast.
Q35. What happens to a local variable after its method returns?
A: The stack frame for that method is popped, and all local variables (including primitive values and references stored on stack) cease to exist. Objects referenced by those variables may still live on the heap until GC if other references point to them.
Q36. What is the difference between pass-by-value and pass-by-reference in Java?
A: Java is strictly pass-by-value. For primitives, the value is copied. For objects, the reference (memory address) is copied — so the callee can mutate the object but cannot make the caller's variable point to a different object. This distinction trips up many candidates.
void change(int x) { x = 10; } // caller's int unchanged
void modify(List<String> l) { l.add("hi"); } // caller's list IS modified
void replace(List<String> l) { l = new ArrayList<>(); } // caller's ref unchanged
Q37. What is the difference between null and undefined in Java?
A: Java has null (a reference type value meaning "no object") but no undefined (that's a JavaScript concept). In Java, uninitialized local variables cause compile-time errors. Instance/static fields default to null (for references) or 0/false (for primitives).
Q38. How does Java handle numeric type promotion in expressions?
A: In arithmetic expressions, byte and short are automatically promoted to int. If any operand is long, the result is long. If any is float, result is float. If any is double, result is double. This is why byte b1 = 1, b2 = 2; byte b3 = b1 + b2; fails (result is int).
Q39. What is the modulo operator and how does it work with negatives?
A: % returns the remainder. For positive operands it's straightforward (7 % 3 = 1). For negative values: the result sign matches the dividend in Java: -7 % 3 = -1, 7 % -3 = 1. Use Math.floorMod() for always-positive modulo (useful for circular arrays).
Q40. What is the difference between short-circuit and non-short-circuit operators?
A: && and || short-circuit: stop evaluating once result is determined. & and | evaluate both operands always. Use short-circuit for null checks (null guard before method call). Use non-short-circuit rarely, when both sides must run for side effects.
Q41. How does String concatenation work with + operator?
A: Java compiler replaces + concatenation with StringBuilder operations. Since Java 9, invokedynamic with StringConcatFactory is used — more efficient. Beware: concatenating in a loop still creates multiple temporary strings. Use StringBuilder.append() in loops.
// Bad: creates many intermediate strings
String result = "";
for (int i = 0; i < 1000; i++) result += i; // O(n^2)
// Good:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) sb.append(i);
String result = sb.toString(); // O(n)
Q42. What is a reference variable?
A: A reference variable holds the memory address (reference) of an object, not the object itself. Multiple reference variables can point to the same object. Setting one to null doesn't affect other references to the same object. References are stored on the stack; objects on the heap.
Q43. What is the difference between declaration, initialization, and assignment?
A: Declaration: int x; — reserves a name and type. Initialization: first assignment, typically at declaration: int x = 5;. Assignment: changing the value after initialization: x = 10;. Local variables must be initialized before use (compile error otherwise).
Q44. What is a literal null and can primitives be null?
A: null is a literal that represents "no object reference" — it can only be assigned to reference types. Primitives (int, double, boolean, etc.) cannot be null. Attempting to unbox a null wrapper to a primitive throws NullPointerException.
Q45. What is NaN and how do you test for it?
A: NaN (Not a Number) is a special double/float value resulting from undefined operations (0.0/0.0, sqrt(-1)). Key property: NaN != NaN (it's not equal to itself). Test with Double.isNaN(x) or Float.isNaN(x), never with ==.
Q46. What is the difference between int[] arr and int arr[]?
A: Both declare an integer array — they're functionally identical. The style int[] arr is preferred as it groups the type information together. The C-style int arr[] works but is discouraged in Java.
Q47. How do you convert a String to int?
A: Use Integer.parseInt("42") — returns primitive int, throws NumberFormatException on invalid input. Integer.valueOf("42") returns Integer object. new Integer("42") is deprecated. Catch NumberFormatException when parsing user input.
Q48. What is the diamond problem in Java and how does it relate to types?
A: Java avoids the diamond problem (ambiguous multiple inheritance) by not allowing multiple class inheritance. Interfaces can have default methods, and if a class implements two interfaces with the same default method, it must override it. Type resolution is always unambiguous.
Q49. What is the difference between char + char and String + String?
A: char + char performs arithmetic (chars are promoted to int): 'A' + 'B' = 65 + 66 = 131. String + String concatenates: "A" + "B" = "AB". Mixed: "" + 'A' + 'B' = "AB" (left-to-right), but 'A' + 'B' + "" = "131".
Q50. How does Java handle multiple variable declarations on one line?
A: Java allows int a = 1, b = 2, c = 3; for multiple declarations of the same type. Each can have its own initializer. This is legal but often discouraged for readability. For arrays: int[] a, b; declares two arrays, but int a[], b; declares one array and one int.
Q51. What is the difference between Object.equals() and ==?
A: == always compares references for objects. Object.equals() by default also compares references. Subclasses like String, Integer, LocalDate override equals() for value comparison. Always override both equals() AND hashCode() together.
Q52. What is the conditional (ternary) operator's type?
A: The ternary a ? b : c type is determined by numeric promotion if both branches are numeric, or the common supertype otherwise. If types differ, widening applies: true ? 1 : 2.0 evaluates to double 1.0. Beware of unboxing NPE: true ? null : 1 unboxes null → NPE.
Q53. What is the difference between Math.round(), Math.floor(), Math.ceil()?
A: Math.round(3.5) = 4 (rounds to nearest, ties go up). Math.floor(3.9) = 3.0 (largest integer ≤ value). Math.ceil(3.1) = 4.0 (smallest integer ≥ value). Math.round() returns int/long; floor/ceil return double.
Q54. Can you change the value of a String in Java?
A: No — String is immutable. Every "modification" (concat, replace, substring) creates a new String object. The original String object never changes. This immutability makes String thread-safe and suitable as HashMap keys. Use StringBuilder for mutable string building.
Q55. What are escape sequences in Java strings?
A: Common escape sequences: \n (newline), \t (tab), \\ (backslash), \" (double quote), \' (single quote), \r (carriage return), \uXXXX (Unicode). Java 13+ text blocks use triple quotes and avoid most escaping.
Q56. What is the difference between a compile-time constant and a runtime constant?
A: Compile-time constants (static final with literal initializer) are inlined by the compiler. Runtime constants are final but their value is computed at runtime (e.g., from a method call or constructor parameter). Compile-time constants allow use in switch cases; runtime constants do not.
Q57. What is the hexadecimal and binary literal syntax in Java?
A: Hex: prefix 0x or 0X — e.g., 0xFF = 255. Binary: prefix 0b or 0B (Java 7+) — e.g., 0b1010 = 10. Octal: prefix 0 — e.g., 017 = 15 (watch out for accidentally octal-formatting zero-padded numbers).
Q58. What is the unsigned right shift operator useful for?
A: >>> fills with zeros regardless of sign bit. Useful when treating an int as a 32-bit unsigned value, e.g., in hash functions: hash ^ (hash >>> 16) spreads high bits to low bits. Also used in binary search mid calculation: int mid = (lo + hi) >>> 1; avoids overflow.
Q59. What is the compound assignment operator?
A: Compound operators (+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>=) combine an operation with assignment AND perform implicit narrowing cast. byte b = 5; b += 3; compiles; b = b + 3; does not (would need explicit cast).
Q60. What is the strictfp keyword?
A: strictfp forces floating-point calculations to follow IEEE 754 strictly — important for cross-platform reproducibility. Before Java 17 it was needed on classes/methods. Since Java 17, all floating-point operations are strict by default (strictfp is now redundant but not removed).
Q61. What is the difference between Integer.MAX_VALUE and Long.MAX_VALUE?
A: Integer.MAX_VALUE = 2^31 - 1 = 2,147,483,647. Long.MAX_VALUE = 2^63 - 1 = 9,223,372,036,854,775,807. Use Long for IDs, timestamps (milliseconds since epoch), or any value that could exceed 2 billion. Java constants: Integer.MIN_VALUE, Long.MIN_VALUE, etc.
Q62. What are the numeric types' default values for instance fields?
A: Instance numeric fields default: byte/short/int = 0, long = 0L, float = 0.0f, double = 0.0d. boolean defaults to false. char defaults to '\u0000' (null char). Reference types default to null. LOCAL variables have NO default — compile error if used uninitialized.
Q63. What is operator precedence in Java?
A: Higher to lower (partial): postfix (x++), unary (+x, -x, ++x, !), multiplicative (* / %), additive (+ -), shift (<< >>), relational (< > instanceof), equality (== !=), bitwise (& ^ |), logical (&& ||), ternary (?:), assignment (= += etc.). Use parentheses for clarity.
Q64. What is the difference between Math.abs() and Math.signum()?
A: Math.abs(x) returns absolute value (always non-negative). Math.signum(x) returns -1.0 if x<0, 0.0 if x=0, 1.0 if x>0. Note: Math.abs(Integer.MIN_VALUE) = Integer.MIN_VALUE (overflow!) — use long for safety.
Q65. What is the difference between a constant pool and string pool?
A: The constant pool is a per-class structure in bytecode containing literals (strings, numerics) and symbolic references. The string pool (String Constant Pool) is a JVM-level heap region holding interned strings at runtime. String literals are automatically interned. The constant pool feeds the string pool at class loading.
Q66. How do you swap two variables without a temp variable?
A: Arithmetic method (for numbers): a = a + b; b = a - b; a = a - b; — beware overflow. XOR method: a ^= b; b ^= a; a ^= b; — works for ints, not objects. Best practice: use a temp variable for clarity and correctness.
Q67. What is the difference between Integer.parseInt() and Integer.valueOf()?
A: parseInt() returns primitive int. valueOf() returns Integer object (uses cache for -128 to 127). For performance in code that uses int: use parseInt(). For code expecting Integer objects: use valueOf(). Both throw NumberFormatException for invalid input.
Q68. Can you use a boolean as an int in Java?
A: No — unlike C/C++, Java's boolean is not compatible with numeric types. if (1) is a compile error. You cannot cast boolean to int. This is intentional design — prevents bugs from accidental assignments like if (x = 5) (which would be a compile error in Java since the result is int, not boolean).
Q69. What is the difference between == for primitives vs == for objects?
A: For primitives, == compares values: 5 == 5 is true. For objects, == compares heap addresses: two different String objects with value "hello" return false with ==. Always use .equals() for object value comparison. For autoboxed integers in range -128 to 127, == may accidentally return true due to caching.
Q70. What are the rules for Java identifier (variable) naming?
A: Identifiers must start with a letter, underscore (_), or dollar sign ($). Subsequent characters can include digits. Case-sensitive. Cannot be reserved words (int, class, etc.). Conventions: camelCase for variables/methods, PascalCase for classes, UPPER_SNAKE for constants, prefixing with underscore discouraged.
Q71. What is the difference between char arithmetic and String concatenation?
A: 'a' + 1 = 98 (char promotes to int, result is int). "a" + 1 = "a1" (String + int concatenates). To concatenate chars as a string: wrap in String.valueOf() or use StringBuilder. Classic interview trick: System.out.println('a' + 'b') prints 195, not "ab".
Q72. What is the difference between new Integer(5) and Integer.valueOf(5)?
A: new Integer(5) always creates a new heap object (deprecated since Java 9, removed in Java 17). Integer.valueOf(5) uses the Integer cache for -128..127 (returns cached object). Always prefer Integer.valueOf() or autoboxing for performance.
Q73. What is the size of each primitive type?
| Type | Size | Range |
|---|---|---|
| byte | 8 bits (1 byte) | -128 to 127 |
| short | 16 bits (2 bytes) | -32,768 to 32,767 |
| int | 32 bits (4 bytes) | -2.1B to 2.1B |
| long | 64 bits (8 bytes) | -9.2 quintillion to 9.2Q |
| float | 32 bits (4 bytes) | ~±3.4e38, 7 decimal digits |
| double | 64 bits (8 bytes) | ~±1.7e308, 15 decimal digits |
| char | 16 bits (2 bytes) | '\u0000' to '\uFFFF' |
| boolean | JVM-dependent (~1 byte) | true / false |
Q74. What is the difference between % and Math.floorMod()?
A: % uses truncated division: result sign = dividend sign. Math.floorMod() uses floor division: result sign = divisor sign. For positive operands they're identical. For negative: -7 % 3 = -1 but Math.floorMod(-7, 3) = 2. Use floorMod for circular/index calculations.
Q75. What is type inference and where is it used in Java?
A: Type inference lets the compiler determine a type from context. Used in: generic method calls (compiler infers type parameters), diamond operator <> (new ArrayList<>()), lambda parameter types, and var (Java 10+). Makes code less verbose without losing type safety.
Q76. What happens when you compare two enum values with ==?
A: It's safe and correct to use == to compare enums in Java because each enum constant is a singleton — only one instance exists per constant. Both == and .equals() work for enums, but == is preferred because it's null-safe and clearer.
Q77. What is the difference between Math.pow() and the ** operator?
A: Java has no ** operator (unlike Python). Use Math.pow(base, exponent) which returns double. For integer powers, be aware of double precision issues for large integer results — consider custom integer power methods or BigInteger.pow().
Q78. What is the difference between = and == in Java?
A: = is assignment: stores a value. == is equality comparison: tests if two values are equal, returns boolean. Common bug from C: if (x = 5) — Java prevents this because the assignment result (5, an int) is not a boolean, so it's a compile error (unlike C where it's silently true).
Q79. What is the transient keyword?
A: transient marks a field to be excluded from Java serialization. When an object is serialized, transient fields are not included (they get their default values upon deserialization). Use for: passwords, cached values, non-serializable objects, or data that can be recomputed.
Q80. What is the volatile keyword for variables?
A: volatile ensures visibility of changes across threads — a write to a volatile variable is immediately visible to all threads (bypasses CPU cache). It does NOT provide atomicity for compound operations like i++. Use for simple flags, but prefer AtomicInteger for compound ops.
Q81. Can you declare a variable with the same name in an inner block?
A: In Java, you cannot shadow a local variable with another local variable in an inner block (unlike C/C++). However, you can shadow an instance variable with a local variable. The compiler will issue an error if you try to declare a variable with the same name in a nested block.
Q82. What is the difference between object identity and object equality?
A: Identity: two references pointing to the same heap object (== returns true). Equality: two objects with equivalent state (equals() returns true). You can have equality without identity (two separate String objects with same content). Classes should override equals() to define meaningful equality.
Q83. What is the significance of the underscore in numeric literals (Java 7+)?
A: Underscores can be placed between digits in numeric literals for readability: 1_000_000, 0xFF_EC_D1, 0b0001_0101. Rules: cannot be at beginning/end, before/after decimal point, before f/L suffix, or before/after 0x/0b prefix. Underscores are ignored by compiler.
Q84. How does Java handle overflow for long type?
A: Long overflow also wraps silently: Long.MAX_VALUE + 1 = Long.MIN_VALUE. Use Math.addExact() for checked arithmetic or BigInteger for arbitrarily large integers. Long is sufficient for most IDs and timestamps but not for arbitrary-precision math.
Q85. What is the difference between local class and anonymous class?
A: A local class is a named class declared inside a method, used multiple times within that method. An anonymous class is a nameless class defined inline when creating an object, used once. Both can access effectively final local variables. Both are rarely used in modern Java — prefer lambdas for functional interfaces.
Q86. What is the difference between int[] a and int a[]?
A: Both declare an integer array. The Java-style int[] a is preferred because the type (int array) is kept together. The C-style int a[] splits the type information across declaration. Both compile identically. The difference matters with multiple declarations: int[] a, b declares two arrays; int a[], b declares one array and one int.
Q87. What are checked vs unchecked numeric exceptions?
A: Java has no checked numeric exceptions — ArithmeticException (division by zero), NumberFormatException, ArrayIndexOutOfBoundsException, and NullPointerException (from unboxing) are all unchecked (RuntimeException subclasses). The Java Math class methods like addExact throw ArithmeticException for overflow.
Q88. What is the difference between Character.isDigit() and Character.isLetter()?
A: Character.isDigit(c) returns true for Unicode digits (0-9 and equivalents in other scripts). Character.isLetter(c) returns true for Unicode letters. Character.isLetterOrDigit(c) for either. Character.isAlphabetic(c) is Unicode-aware. Use these instead of manual range checks for internationalization support.
Q89. How do you convert between different numeric types?
A: Widening: automatic (int x = 5; long l = x;). Narrowing: explicit cast (long l = 100L; int i = (int) l;). Number to String: String.valueOf(42), Integer.toString(42), "" + 42. String to number: Integer.parseInt("42"), Double.parseDouble("3.14").
Q90. What is the difference between = and := (does := exist in Java)?
A: := does NOT exist in Java (it's used in Pascal, Kotlin, Go for declaration+assignment). Java uses = for assignment. If you see := in a Java context, it's a syntax error. Java 10's var provides type inference but the assignment operator remains =.
Q91. What is the difference between Integer.compare() and Integer subtraction for comparison?
A: Never use subtraction a - b as a comparator — it overflows for extreme values (e.g., Integer.MIN_VALUE - 1). Always use Integer.compare(a, b) which returns negative, zero, or positive safely. Same applies to Long.compare(), Double.compare().
Q92. What are the rules for floating-point special values?
A: Special double values: Infinity (positive/negative), NaN (Not a Number). Operations: any finite value / 0.0 = ±Infinity; 0.0 / 0.0 = NaN; Infinity - Infinity = NaN; NaN propagates through all arithmetic. Test with Double.isInfinite() and Double.isNaN().
Q93. What is the maximum recursion depth in Java?
A: Depends on JVM stack size (-Xss flag, default typically 256KB-1MB) and stack frame size (number of local variables). Typically 1000-10000 recursive calls before StackOverflowError. Increase with -Xss4m or refactor to iterative with explicit stack. Tail-call optimization is NOT performed by JVM.
Q94. What is the difference between Math.max() and the ternary operator for finding max?
A: Both work. Math.max(a, b) is cleaner and handles special cases (NaN for doubles). Ternary a > b ? a : b works fine for primitives. For multiple values, Math.max(Math.max(a,b), c) or Stream.of(a,b,c).max(Integer::compareTo).
Q95. What is octal notation in Java and what's the risk?
A: Integer literals starting with 0 (not 0x or 0b) are octal: 010 = 8, 017 = 15. This is a common trap — zero-padded integers in source code are interpreted as octal. Never zero-pad integer literals. 012345 = 5349 in decimal, not 12345!
Q96. What is the difference between charAt() and codePointAt()?
A: charAt(i) returns the char (UTF-16 code unit) at index i. For supplementary characters (> U+FFFF), one character occupies two chars (surrogate pair). codePointAt(i) returns the full Unicode code point, handling surrogate pairs correctly. Use codePointAt for full Unicode support.
Q97. What is the purpose of the assert keyword?
A: assert condition : message; throws AssertionError if condition is false (when assertions are enabled with -ea JVM flag). Disabled by default for performance. Used for developer-facing invariants and postconditions — NOT for production input validation (use exceptions for that).
Q98. What is operator associativity in Java?
A: Most operators are left-associative: a - b - c = (a - b) - c. Assignment operators are right-associative: a = b = 5 means a = (b = 5) (both get 5). Ternary is right-associative. Knowing associativity prevents bugs in complex expressions.
Q99. What is the difference between static initializer block and instance initializer block?
A: Static initializer block (static { ... }) runs once when the class is loaded, for initializing static variables. Instance initializer block ({ ... }) runs every time an instance is created, before the constructor body. Both are used when initialization logic is too complex for a single expression.
class Example {
static final Map<String, Integer> CODES;
static { // static initializer
CODES = new HashMap<>();
CODES.put("A", 1);
}
int id;
{ id = generateId(); } // instance initializer (runs before constructor)
}
Q100. What is the difference between ++i and i = i + 1 in terms of bytecode?
A: For local int variables, ++i compiles to the iinc bytecode instruction (increment local variable in-place — faster, no load/store). i = i + 1 compiles to iload + iconst_1 + iadd + istore (multiple bytecodes). In practice the JIT optimizer eliminates this difference, but ++i is idiomatic.
Q101. How do you find if a number is a power of 2 using bitwise operations?
A: n > 0 && (n & (n - 1)) == 0. Powers of 2 have exactly one bit set: n = 8 = 1000, n-1 = 7 = 0111, n & (n-1) = 0. Must check n > 0 since 0 would pass otherwise. Also: Integer.bitCount(n) == 1.
boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
// 8: 1000 & 0111 = 0 → true
// 6: 0110 & 0101 = 0100 ≠ 0 → false
Q102. What is the difference between Integer.toBinaryString() and String.format("%b")?
A: Integer.toBinaryString(n) returns the binary representation of n as unsigned. String.format("%b", obj) returns "true"/"false" based on boolean context (not a binary string). For binary: use toBinaryString(). For hex: Integer.toHexString(). For octal: Integer.toOctalString().
Q103. What is the Collections.nCopies() method?
A: Collections.nCopies(n, obj) returns an immutable List containing n copies of the same object reference. All elements point to the SAME object. Mutating elements (e.g., if obj is mutable) through one index affects all. Use for initialization but understand the shared-reference semantics.
Q104. What is the difference between Java's & operator on int vs boolean?
A: On integers: & is bitwise AND, operates bit-by-bit. On booleans: & is non-short-circuit logical AND, evaluates both operands. && short-circuits. All are valid in Java depending on operand type — but be intentional about which you use.
Q105. What are the implications of using float vs double in calculations?
A: Float (32-bit): faster on some platforms, less precise (~7 significant digits), sufficient for graphics/games. Double (64-bit): default for floating-point in Java, ~15 digits precision, used in scientific calculations. Java defaults to double for literals (3.14 is double; 3.14f is float). Never use either for money — use BigDecimal.
Post a Comment
Add