Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Java Module 2

Variables, types and operators interview questions

Interview questions on variables, types and operators: short warm-ups, then what each harder question tests, the first step of a good answer and its follow-ups.

30 questions: 10 warm-ups and 20 with model answers · Levels: Fresher to senior

Warm-up questions

Short questions with short answers, each answered in full.

  1. Fresher

    What are Java's eight primitive types, and why is String not one of them?

    Answered in the lesson Variables and the eight primitive types

  2. Fresher

    Why does -7 / 2 give -3 in Java and not -4?

    Answered in the lesson Integer arithmetic, division and overflow

  3. Fresher

    Why should money not be stored in a double?

    Answered in the lesson Floating point, rounding and BigDecimal

  4. Fresher

    Why does byte b = 10; b = b + 1; fail to compile while b += 1; works?

    Answered in the lesson char, boolean, casting and conversions

  5. Fresher

    What is the difference between & and && in Java?

    Answered in the lesson Operators, precedence and short-circuiting

  6. Fresher

    What is the difference between >> and >>> in Java?

    Answered in the lesson Bitwise operators, shifts and bit tricks

  7. Fresher

    Why can == say false for two strings that print the same text, and what should you use instead?

    Answered in the lesson Strings: first look and equality

  8. Fresher

    In printf("%8.2f", x), what do 8 and .2 mean, and what happens when the number needs more than 8 characters?

    Answered in the lesson Formatted output with printf and formatted

  9. Fresher

    What are autoboxing and unboxing, and what does the compiler turn Integer n = 5; int m = n; into?

    Answered in the lesson Wrapper classes, autoboxing and caching

  10. Fresher

    What kinds of comments does Java have, and which of them does javadoc read?

    Answered in the lesson Comments, Javadoc and naming conventions

Questions with model answers

What each question tests, the first step of a good answer and the follow-ups to expect.

  1. Fresher to mid

    A teammate wants var banned from the code base because it "makes Java dynamically typed". Explain what var really does, where it cannot be used, and how you would decide in a code review whether a particular var helps or hurts.

    What it tests
    Static typing with local type inference, the limits the language puts on var, and judging readability in a review.
    First step
    Show that the type is fixed when the code compiles: after var total = 10; the line total = 9_000_000_000L; is rejected with a lossy-conversion error, exactly as it would be after int total = 10;. Nothing about the type is decided at run time.
    Follow-ups

    From the lesson Variables and the eight primitive types

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page.

    Opening the model answers with your pass…

    Model answers open with any MySmartCoPilot pass.

    • Pro pass · 1 week₹79$2.99
    • 30 days₹179$5.99
    • 1 year₹1,699$45

    One payment; a pass never renews. The price shown is the total you pay: no fees or charges are added at checkout.

    It also opens every other in-depth part in Learn and every Pro tool. Sales are final, except where the law gives you a right to withdraw, for example in the EU and the UK (refund policy).

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  2. Mid to senior

    A service stores order IDs as int, and the business expects about 5 million new orders a day. When does this break, what will users and logs show when it does, and what has to change besides the Java type?

    What it tests
    Estimating when a counter overflows, how int overflow shows up in a running system, and planning a type change across code, storage and APIs.
    First step
    An int counts up to 2,147,483,647, so at 5 million orders a day the positive IDs last about 429 days, a little over a year. Growth shortens that: at 10 million a day it is about 215 days.
    Follow-ups

    From the lesson Variables and the eight primitive types

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  3. Mid to senior

    A router picks one of 5 shards with Math.abs(key.hashCode()) % 5. Almost all requests work, but a few fail with ArrayIndexOutOfBoundsException: Index -3 out of bounds for length 5. Explain exactly how, and fix it.

    What it tests
    Math.abs of Integer.MIN_VALUE, the sign rule of %, and choosing floorMod or a mask to turn a hash into an index.
    First step
    Look for a key whose hashCode() is Integer.MIN_VALUE. Math.abs cannot negate it, so it stays -2,147,483,648, and a negative dividend gives a negative remainder: -2,147,483,648 % 5 is -3.
    Follow-ups

    From the lesson Integer arithmetic, division and overflow

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  4. Fresher to mid

    A nightly job adds up a day's sales in cents and, for the first time, reported a negative total. The developer changed the total from int to long, but the next busy day was wrong again. What is going on, and how do you fix it for good?

    What it tests
    Recognising int overflow from its symptoms, the int-times-int trap, and choosing long, the Exact methods or BigDecimal.
    First step
    A negative sum of positive amounts means a value passed 2,147,483,647 cents, about 21.5 million in the currency, and wrapped. Since the total is now a long, look for an int expression computed before it is added, such as price * quantity on two ints.
    Follow-ups

    From the lesson Integer arithmetic, division and overflow

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  5. Mid to senior

    Prices are BigDecimal values read from several suppliers. A deduplication step puts them in a HashSet and keeps both 19.9 and 19.90, while a TreeSet of the same prices keeps one. Explain, and say how you would store and compare prices.

    What it tests
    BigDecimal's value and scale, equals and hashCode against compareTo, and normalising money where it enters a system.
    First step
    BigDecimal.equals compares the value and the scale: 19.9 has scale 1 and 19.90 scale 2, so equals is false and the hash codes differ. TreeSet orders with compareTo, which compares values only, so it sees one price.
    Follow-ups

    From the lesson Floating point, rounding and BigDecimal

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  6. Mid to senior

    A metrics job adds ten million readings of 0.1 with a double in a for loop and gets 999999.9998389754 instead of 1,000,000. Explain where the error comes from, how it grows, and how you would get the right total.

    What it tests
    How rounding error accumulates in long sums, compensated summation, and when BigDecimal or whole units are the right tool.
    First step
    Every addition rounds its result to the nearest double. Once the total is large, the gap between neighbouring doubles near the total is much wider than near 0.1, so each 0.1 is added with an error of up to half that gap, and the errors add up.
    Follow-ups

    From the lesson Floating point, rounding and BigDecimal

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  7. Fresher to mid

    A checksum adds the bytes of a file with int sum = 0; for (byte b : data) sum += b;. For some files it disagrees with the checksum another program computes for the same file. Find the bug, fix it, and say which files expose it.

    What it tests
    Signed bytes, sign extension when a byte is widened, masking with & 0xFF, and overflow of the running sum.
    First step
    A Java byte is signed, so the byte 0xFF is -1, not 255, and widening it to int keeps the -1. Every byte from 0x80 to 0xFF is added as a negative number: the bytes 01 FF 80 sum to -128 instead of 384.
    Follow-ups

    From the lesson char, boolean, casting and conversions

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  8. Fresher to mid

    Prices arrive from a JSON feed as doubles and are turned into cents with (int) (price * 100). Some totals come out one cent short. Explain why, say how many prices are affected, and design a conversion that is always right.

    What it tests
    Narrowing casts that cut toward zero, binary floating-point error, and converting money with rounding or BigDecimal.
    First step
    Try 0.29: the double nearest 0.29 times 100 is 28.999999999999996, and the cast drops the fraction, giving 28 cents. The cast cuts toward zero, so any product that lands just below the whole number loses a cent.
    Follow-ups

    From the lesson char, boolean, casting and conversions

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  9. Mid to senior

    Integer count = cached ? cache.get(key) : 0; throws NullPointerException when the key is missing, although count is an Integer and could hold null. Explain why, and give two fixes.

    What it tests
    How the type of a conditional expression is chosen, unboxing, and reading a helpful NullPointerException message.
    First step
    Work out the type of the whole conditional before the assignment: one branch is an Integer and the other the int 0, so it is a numeric conditional of type int, and Java unboxes the Integer from cache.get(key). A null cannot be unboxed.
    Follow-ups

    From the lesson Operators, precedence and short-circuiting

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  10. Mid to senior

    A teammate wrote index = index++ + 1; and values[i] = i = 4; and says the results depend on the compiler, as in C. Is that right? Explain what Java guarantees, what each statement does, and how you would rewrite them.

    What it tests
    Java's left-to-right evaluation guarantee, the value of a postfix increment, assignment evaluation, and writing side effects readably.
    First step
    Java defines the order, unlike C: the left operand is evaluated before the right, a postfix ++ yields the old value, and an assignment picks its target before evaluating the right side. Both statements therefore have one result on every JVM.
    Follow-ups

    From the lesson Operators, precedence and short-circuiting

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  11. Fresher to mid

    Permissions are bits of a long, granted with perms |= 1 << p.ordinal(). With 40 permissions defined, granting the one with ordinal 35 grants ordinal 3 instead, and ordinal 31 seems to grant many at once. Explain both and fix them.

    What it tests
    The int type of the literal 1, masked shift distances, sign extension from int to long, and choosing between a long, EnumSet and BitSet.
    First step
    1 is an int, so 1 << p.ordinal() is an int shift. For an int only the low 5 bits of the distance count, so 35 acts as 3, and the int result is widened to long only for the |=.
    Follow-ups

    From the lesson Bitwise operators, shifts and bit tricks

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  12. Fresher to mid

    You enumerate every subset of n items with an int mask in a coding round. Up to which n does the code work at all, what goes wrong first as n grows, and how do you estimate the running time before writing it?

    What it tests
    Shift limits of int and long masks, counting 2ⁿ subsets, estimating time and memory, and knowing when to change the algorithm.
    First step
    The loop for (int mask = 0; mask < 1 << n; mask++) needs 1 << n to be a positive int, which holds up to n = 30. At n = 31, 1 << 31 is negative and the loop runs zero times. Then count the work: 2ⁿ masks times about n steps each.
    Follow-ups

    From the lesson Bitwise operators, shifts and bit tricks

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  13. Fresher to mid

    A check if (status == "PAID") passes every unit test, which build orders from string literals, but fails in production, where the status is read from a database. Explain why the tests pass, why production fails, and how you would fix the code and keep the bug from coming back.

    What it tests
    Reference equality against equals, interning of literals and constant expressions, null-safe comparison, and preventing a whole class of bug rather than one instance of it.
    First step
    == compares references. In the tests both sides are the literal "PAID", and literals are interned, so they are the same object. A status read from a database is a new String made at run time, so == is false even when the text is equal. Compare the content instead: "PAID".equals(status).
    Follow-ups

    From the lesson Strings: first look and equality

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  14. Mid

    Customer IDs pasted from a spreadsheet look identical to the IDs in your database, yet equals returns false and strip() changes nothing. How do you find out what is different, and how would you clean such input safely?

    What it tests
    Debugging text that looks identical: inspecting code points, trim against strip against no-break spaces, zero-width and look-alike characters, and a cleaning rule that cannot corrupt real data.
    First step
    Print what the strings are made of instead of what they look like: the length() of each and every code point in hexadecimal. A length longer than the visible text, or a code point such as U+00A0 (no-break space), U+200B (zero-width space) or U+2011 (non-breaking hyphen), shows exactly what equals sees.
    Follow-ups

    From the lesson Strings: first look and equality

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  15. Mid

    A nightly job writes amounts into a CSV file with String.format("%.2f", amount). It ran correctly for months. After a move to a new server, the importer rejects the file because every line now has an extra column. What happened, how do you fix it, and how do you make sure it cannot happen again?

    What it tests
    The JVM's default locale and how it changes number formatting, Locale.ROOT for machine-readable output, and finding the other calls in a code base that depend on the default locale.
    First step
    String.format without a Locale uses the JVM's default format locale, which comes from the server's settings. If the new server runs with a German or French locale, 3.5 is written as 3,50, and that comma splits one field into two. Anything another program reads should be formatted with Locale.ROOT.
    Follow-ups

    From the lesson Formatted output with printf and formatted

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  16. Mid to senior

    An invoice prints each line with String.format("%.2f", price * qty). For one line of 1 x 1.005 it prints 1.01, while the accounting system, which uses BigDecimal, books 1.00. Explain both results, and decide how the invoice and the books should round.

    What it tests
    How %.2f rounds, the exact value a double holds, building BigDecimal values and choosing rounding modes, and where rounding belongs in money calculations.
    First step
    Find out what each side rounds. The formatter rounds the digits that Double.toString shows, 1.005, half up, which gives 1.01. The double itself holds 1.00499999999999989…, which is what new BigDecimal(double) captures, and rounding that gives 1.00. One amount is being rounded twice, by two different rules.
    Follow-ups

    From the lesson Formatted output with printf and formatted

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  17. Fresher to mid

    A word-count method crashes with a NullPointerException at counts.put(word, counts.get(word) + 1). Explain exactly why, give two correct fixes, and say what changes when several threads count into the same map.

    What it tests
    Unboxing null, Map.get returning null for a missing key, reading a helpful NullPointerException message, getOrDefault and merge, and atomic updates in ConcurrentHashMap.
    First step
    counts.get(word) returns null the first time a word is seen, and + 1 needs an int, so Java unboxes the null by calling intValue() on it. The message says exactly that: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null.
    Follow-ups

    From the lesson Wrapper classes, autoboxing and caching

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  18. Mid to senior

    To allow "no id yet", a team changed int getId() to Integer getId() on an entity. Everything compiled, every test passed, and a week later duplicate checks such as a.getId() == b.getId() began failing in production. Explain why it compiled, why the tests passed, and how you would find and fix every affected comparison.

    What it tests
    Boxing changing what == means, the -128 to 127 cache hiding the bug in tests, comparing nullable values, and finding changes of meaning that the compiler cannot report.
    First step
    With int, == compared numbers. With Integer on both sides, == compares references, and it still compiles. Integer.valueOf caches -128 to 127, so test data with small ids compared the same cached objects and passed; production ids above 127 are separate objects, so equal ids compared as different.
    Follow-ups

    From the lesson Wrapper classes, autoboxing and caching

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  19. Mid to senior

    In a code review you find // cap applies only to new users \u000d limit = 0; in a pricing class, and the author says it is only a comment. What does the compiler do with it, why does it matter for code review, and how would you stop such lines reaching the main branch?

    What it tests
    The order of lexical translation in the language specification, Unicode escapes ending comments, why reviewers miss them, and automatic checks that catch such source tricks.
    First step
    Unicode escapes are translated before comments are recognised. \u000d is a carriage return, which is a line terminator, so the comment ends there and limit = 0; is compiled as ordinary code. javac gives no warning, even with -Xlint:all.
    Follow-ups

    From the lesson Comments, Javadoc and naming conventions

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 4 minutes
  20. Mid to senior

    Your team publishes a small Java library. What must the Javadoc of a public method say, and how do you keep the documentation from drifting away from the code as the library changes?

    What it tests
    Javadoc as a contract: parameters, results, exceptions, null, units and thread safety; doclint and -Werror; tests that keep documentation honest; choosing between /// and /** */ comments.
    First step
    Treat the comment as the method's contract, written for a caller who cannot see the code: what it returns, what each parameter means and which values are allowed, what happens with null, which exceptions it throws and when, units and side effects. Then let the build check what it can: javadoc -Xdoclint:all -Werror fails on missing comments and tags.
    Follow-ups

    From the lesson Comments, Javadoc and naming conventions

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 4 minutes

All Java interview questions · The Java track

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.