Java Basics Chapter
Comments Interview Questions and Answers
Learn how Java comments work, from single-line and multi-line comments to Javadoc documentation, Javadoc tags, TODO/FIXME markers, and comment best practices.
Comments interview questions
Comments Interview Question 15 Questions
Click on any question to expand the answer.
Interview Answer
Comments are non-executable text added to Java source code to explain logic, document APIs, or leave maintenance notes. The compiler normally ignores comments during compilation. Good comments explain why the code exists rather than repeating what the code already shows.
Key Points
- Comments improve code readability.
- They help developers understand complex logic.
- Comments can document classes, methods, and fields.
- They are not executed by the JVM.
- They are normally excluded from generated bytecode.
- Outdated comments can mislead developers.
Example
public class DiscountCalculator {
public static void main(String[] args) {
double price = 1000.0;
// Premium customers receive a 10% discount.
double finalPrice = price - price * 0.10;
System.out.println(finalPrice);
}
}Output
900.0Interview Tips
- Explain that comments are for developers, not program execution.
- Prefer comments that explain business reasons or complex decisions.
- Avoid comments that simply repeat obvious code.
- Update comments whenever related code changes.
Summary
Java comments add explanations and documentation to source code. They improve maintainability but should remain accurate, concise, and useful.
Interview Answer
Java supports single-line comments, multi-line comments, and documentation comments. Single-line and multi-line comments are used for normal source-code explanations. Documentation comments are processed by the Javadoc tool to generate API documentation.
Key Points
- Single-line comments begin with //.
- Multi-line comments begin with /* and end with */.
- Documentation comments begin with /** and end with */.
- Javadoc comments support special documentation tags.
- Regular comments are ignored by the compiler.
- Each comment type serves a different purpose.
Syntax
// Single-line comment
/*
* Multi-line comment
*/
/**
* Documentation comment
*/Example
/**
* Demonstrates the main Java comment types.
*/
public class CommentTypes {
public static void main(String[] args) {
// Stores the application name.
String applicationName = "Java Portal";
/*
* Displays the application name
* on the console.
*/
System.out.println(applicationName);
}
}Output
Java PortalInterview Tips
- Name all three comment types.
- Mention that Javadoc comments generate API documentation.
- Do not confuse documentation comments with ordinary multi-line comments.
- Choose the comment type based on its purpose.
Summary
Java provides single-line, multi-line, and documentation comments. Regular comments explain implementation details, while Javadoc comments describe public APIs.
Interview Answer
A single-line comment describes content from // to the end of the current line. A multi-line comment can cover several lines between /* and */. A documentation comment uses /** and */ and can be processed by Javadoc to generate structured API documentation.
Key Points
- Single-line comments are suitable for short explanations.
- Multi-line comments are useful for longer internal notes.
- Documentation comments describe APIs.
- Javadoc comments support tags such as @param and @return.
- Regular comments do not generate API documentation.
- Documentation comments should appear before declarations.
Syntax
// Short explanation
/*
* Longer implementation explanation
*/
/**
* API documentation
*/Example
/**
* Calculates the sum of two numbers.
*
* @param first first number
* @param second second number
* @return sum of both numbers
*/
public class Calculator {
public static int add(int first, int second) {
// Return the calculated sum.
return first + second;
}
public static void main(String[] args) {
/*
* Calls the add method and
* displays the returned result.
*/
System.out.println(add(10, 20));
}
}Output
30Interview Tips
- Compare the three types by syntax and purpose.
- Mention that only documentation comments are processed by Javadoc.
- Use single-line comments for brief notes.
- Avoid large multi-line comments when clearer code can explain the logic.
Summary
Single-line and multi-line comments explain implementation details. Documentation comments describe Java APIs and can be converted into HTML documentation.
Interview Answer
A single-line comment starts with // and continues until the end of that line. It should be used for short explanations, temporary notes, or important reasons behind a statement. It is best suited for concise comments that do not require multiple lines.
Key Points
- A single-line comment begins with //.
- Everything after // on that line is treated as a comment.
- It may appear on its own line.
- It may also appear after a Java statement.
- It is useful for short implementation notes.
- Too many inline comments can reduce readability.
Syntax
// Comment text
int count = 10; // Inline commentExample
public class LoginPolicy {
public static void main(String[] args) {
int failedAttempts = 3;
// Lock the account after three failed login attempts.
boolean accountLocked = failedAttempts >= 3;
System.out.println(accountLocked);
}
}Output
trueInterview Tips
- Use single-line comments for short and focused explanations.
- Explain why the logic exists rather than describing obvious syntax.
- Avoid placing long comments at the end of code lines.
- Use TODO comments only when they include a clear pending task.
Summary
Single-line comments begin with // and end at the line break. They are ideal for short explanations and maintenance notes.
Interview Answer
A multi-line comment begins with /* and ends with */. It can span one or more lines and is commonly used for longer explanations. Java does not support nested multi-line comments because the first */ closes the entire comment.
Key Points
- Multi-line comments start with /*.
- They end with */.
- They can cover several source-code lines.
- They may also appear on one line.
- Multi-line comments cannot be nested.
- Attempting to nest them can cause compilation errors.
Syntax
/*
* Multi-line comment text
*/Example
public class MultiLineCommentExample {
public static void main(String[] args) {
/*
* The shipping charge is waived
* when the order total is at least 500.
*/
double orderTotal = 750.0;
boolean freeShipping = orderTotal >= 500.0;
System.out.println(freeShipping);
}
}Output
trueInterview Tips
- State clearly that block comments cannot be nested.
- Avoid commenting out large blocks of obsolete code.
- Use version control instead of keeping unused code in comments.
- Prefer readable code over lengthy implementation comments.
Summary
Multi-line comments are enclosed between /* and */ and can span multiple lines. They cannot be nested because the first closing delimiter ends the comment.
Interview Answer
Javadoc comments are special comments used to document Java APIs. They begin with /** and end with */ and can be processed by the javadoc tool. Regular comments explain implementation details but are not used to generate structured API documentation.
Key Points
- Javadoc comments begin with /**.
- They document classes, interfaces, fields, constructors, and methods.
- They support tags such as @param, @return, and @throws.
- The javadoc tool converts them into API documentation.
- Regular comments use // or /* */.
- Regular comments are intended mainly for developers reading the source code.
Syntax
/**
* Description of the program element.
*/Example
/**
* Provides basic mathematical operations.
*/
public class Calculator {
/**
* Adds two integer values.
*
* @param first first value
* @param second second value
* @return sum of both values
*/
public int add(int first, int second) {
return first + second;
}
}Interview Tips
- Explain the difference based on purpose and tool support.
- Mention that Javadoc describes APIs rather than internal implementation.
- Do not confuse /** */ with an ordinary /* */ block comment.
Summary
Javadoc comments create structured documentation for Java program elements. Regular comments only provide source-code explanations and are not normally included in generated API documentation.
Interview Answer
The javadoc tool reads Java source files, declarations, and Javadoc comments. It combines documentation text, tags, method signatures, inheritance details, and type information to generate linked API documentation, usually in HTML format. Command-line options control the output folder, visibility level, encoding, and other settings.
Key Points
- The tool reads Java source code.
- It identifies documented program declarations.
- It processes Javadoc descriptions and tags.
- It creates navigation links between related types and members.
- It can document packages and modules.
- Generated documentation normally includes HTML pages and indexes.
Syntax
javadoc -d docs Calculator.javaExample
/**
* Represents a customer account.
*/
public class CustomerAccount {
private final int accountId;
/**
* Creates a customer account.
*
* @param accountId unique account identifier
*/
public CustomerAccount(int accountId) {
this.accountId = accountId;
}
/**
* Returns the account identifier.
*
* @return account identifier
*/
public int getAccountId() {
return accountId;
}
}Interview Tips
- Mention that the tool reads both declarations and documentation comments.
- Remember that the output is generated from source code, not runtime objects.
- Explain that visibility options determine which members are documented.
- Use the -d option to specify the output directory.
Summary
The javadoc tool analyzes Java source declarations and Javadoc comments. It generates structured, linked API documentation that helps developers understand and use the code.
Interview Answer
Javadoc tags provide structured information about documented Java elements. @param describes method parameters or type parameters, @return explains the returned value, and @throws documents possible exceptions. @author identifies the author, while @since records the version in which the API was introduced.
Key Points
- @param documents parameters and generic type parameters.
- @return documents the method’s result.
- @throws documents an exception and its cause.
- @exception is an alternative to @throws.
- @author records author information.
- @since records the API introduction version.
- @return is not used for constructors or void methods.
Syntax
/**
* Description.
*
* @param parameterName parameter description
* @return returned value description
* @throws ExceptionType reason for the exception
* @author Author Name
* @since Version
*/Example
/**
* Provides division operations.
*
* @author Development Team
* @since 1.0
*/
public class DivisionService {
/**
* Divides one number by another.
*
* @param dividend value to divide
* @param divisor value used as the divisor
* @return division result
* @throws IllegalArgumentException if the divisor is zero
*/
public double divide(double dividend, double divisor) {
if (divisor == 0) {
throw new IllegalArgumentException("Divisor cannot be zero");
}
return dividend / divisor;
}
}Interview Tips
- Match every @param tag with an actual parameter.
- Document only meaningful exceptions with @throws.
- Describe the result rather than repeating the method name.
- Keep tag descriptions short and specific.
Summary
Javadoc tags organize parameter, return-value, exception, author, and version information. Correct tags make generated API documentation clearer and easier to use.
Interview Answer
A Javadoc comment should be placed immediately before the declaration it documents. It can document modules, packages, classes, interfaces, records, enums, fields, constructors, and methods. Javadoc comments placed inside method bodies do not document local statements or variables as API elements.
Key Points
- Place the comment directly before the declaration.
- Class documentation appears before the class declaration.
- Method documentation appears before the method declaration.
- Field documentation appears before the field declaration.
- Package documentation is commonly written in package-info.java.
- Module documentation is written before the module declaration in module-info.java.
- Avoid separating Javadoc from its declaration with unrelated code.
Example
/**
* Manages product information.
*/
public class ProductService {
/**
* Default product limit.
*/
public static final int DEFAULT_LIMIT = 20;
/**
* Finds a product by its identifier.
*
* @param productId product identifier
* @return formatted product information
*/
public String findProduct(int productId) {
// This regular comment explains internal implementation.
return "Product-" + productId;
}
}Interview Tips
- Say that Javadoc belongs immediately before the documented declaration.
- Use regular comments for statements inside method bodies.
- Mention package-info.java and module-info.java in advanced interviews.
- Document public APIs consistently.
Summary
Javadoc comments must appear directly before the declarations they describe. Package and module documentation use dedicated source files, while internal method logic normally uses regular comments.
Interview Answer
No, Java comments are not executable and are not translated into JVM instructions. The compiler removes or ignores comments while processing source code, so they do not affect runtime performance. Javadoc tools can read documentation comments from source files before compilation.
Key Points
- Comments exist only in source code.
- They are not executed by the JVM.
- They do not become bytecode instructions.
- They do not increase normal runtime memory usage.
- Javadoc comments may be processed by documentation tools.
- Text inside string literals is not treated as a comment.
Example
public class CommentExecutionExample {
public static void main(String[] args) {
// This comment is ignored during compilation.
int result = 10 + 20;
// Comment symbols inside a string are normal characters.
String text = "// This is string content";
System.out.println(result);
System.out.println(text);
}
}Output
30
// This is string contentInterview Tips
- State that comments are source-level information.
- Do not say comments are executed but produce no output.
- Distinguish real comments from comment symbols inside strings.
- Mention that comments do not affect normal application performance.
Summary
Java comments are ignored during compilation and are not executed by the JVM. They help developers and documentation tools but do not become runtime instructions.
Interview Answer
Yes, comments can appear between Java tokens inside statements, expressions, and method calls. The compiler treats the comment like whitespace, provided it does not break a token such as a keyword, identifier, number, or operator. Although legal, excessive inline comments can make code difficult to read.
Key Points
- Comments may appear between valid Java tokens.
- They can be placed inside expressions and argument lists.
- A comment cannot split a single identifier or keyword.
- Comment markers inside string literals are ordinary characters.
- Poorly placed comments can reduce readability.
- Normal spacing is usually clearer than embedded comments.
Example
public class InlineCommentExample {
public static void main(String[] args) {
int total = 10 /* first value */ + 20;
printMessage(
"Java", // First argument
total
);
}
public static void printMessage(String language, int value) {
System.out.println(language + ": " + value);
}
}Output
Java: 30Interview Tips
- State that comments behave like whitespace between tokens.
- Do not place comments where they interrupt natural code flow.
- Remember that comment symbols inside strings are not comments.
- Prefer readable variable names over explanatory inline comments.
Summary
Java permits comments inside statements, expressions, and method calls when they appear between tokens. They should be used carefully because unusual placement can reduce readability.
Interview Answer
Comments are processed at the source-code level and do not become executable bytecode instructions. Therefore, they normally do not affect runtime performance, memory usage, or the size of compiled class files. Very large comment blocks may slightly affect source processing time, but this is rarely significant.
Key Points
- Comments are ignored during normal compilation.
- They are not executed by the JVM.
- They do not create runtime objects.
- They do not add executable bytecode.
- They normally do not increase class-file size.
- Javadoc comments may be processed separately by documentation tools.
Example
public class CommentPerformanceExample {
public static void main(String[] args) {
// This explanation does not affect runtime execution.
int result = calculateTotal(10, 20);
System.out.println(result);
}
public static int calculateTotal(int first, int second) {
/*
* This block comment is not included
* as executable JVM instructions.
*/
return first + second;
}
}Output
30Interview Tips
- Explain that comments affect source readability, not runtime logic.
- Do not claim that comments slow down the running application.
- Distinguish source-file size from compiled class-file size.
- Mention that documentation tools can process Javadoc separately.
Summary
Comments have no meaningful effect on Java application performance or runtime memory. They increase only the source-file content and are normally excluded from compiled bytecode.
Interview Answer
Useful comments explain why a decision was made, describe complex business rules, document APIs, or warn about important limitations. Unnecessary comments simply repeat obvious code or describe outdated behavior. Good code should explain what it does, while comments should explain information that the code cannot express clearly.
Key Points
- Useful comments explain intent and reasoning.
- They may document unusual constraints or business rules.
- Unnecessary comments repeat obvious statements.
- Outdated comments are more harmful than missing comments.
- Clear names can often replace explanatory comments.
- Comments should remain concise and accurate.
Example
public class WithdrawalService {
private static final double DAILY_LIMIT = 50000.0;
public boolean canWithdraw(double requestedAmount) {
// Regulatory policy limits the total daily withdrawal amount.
return requestedAmount > 0 && requestedAmount <= DAILY_LIMIT;
}
public static void main(String[] args) {
WithdrawalService service = new WithdrawalService();
System.out.println(service.canWithdraw(20000.0));
}
}Output
trueInterview Tips
- Explain why instead of repeating what the statement does.
- Remove comments that no longer match the code.
- Improve naming before adding comments to simple logic.
- Document important business rules and non-obvious decisions.
Summary
Useful comments add context, intent, or important constraints. Unnecessary comments repeat clear code and create maintenance problems when they become outdated.
Interview Answer
TODO, FIXME, and NOTE are informal comment markers used to highlight pending work, known problems, or important information. TODO identifies future work, FIXME marks code that is incorrect or risky, and NOTE records information developers should remember. IDEs and static-analysis tools can detect and organize these markers.
Key Points
- TODO identifies unfinished or planned work.
- FIXME marks a known defect that requires correction.
- NOTE records important implementation information.
- Many IDEs display these comments in task lists.
- Markers should include clear and actionable details.
- Issue-tracker references improve traceability.
- Old markers should be reviewed and removed.
Example
public class PaymentService {
public void processPayment(double amount) {
// TODO: Add currency validation before release.
// FIXME: Replace this temporary rounding logic.
double roundedAmount = Math.round(amount * 100.0) / 100.0;
// NOTE: The payment gateway accepts two decimal places.
System.out.println(roundedAmount);
}
public static void main(String[] args) {
PaymentService service = new PaymentService();
service.processPayment(125.678);
}
}Output
125.68Interview Tips
- Do not use TODO as a replacement for proper task tracking.
- Include an issue number, owner, or clear action when possible.
- Use FIXME only for genuine defects or unsafe behavior.
- Regularly remove completed or obsolete markers.
Summary
TODO, FIXME, and NOTE comments help teams track pending work, defects, and important information. They are most useful when they are specific, actionable, and linked to development tasks.
Interview Answer
Common mistakes include writing comments that repeat the code, leaving outdated explanations, commenting out obsolete code, exposing sensitive information, and creating inaccurate Javadoc. Developers can avoid these problems by keeping comments focused on intent, reviewing them during code changes, and using version control instead of preserving dead code.
Key Points
- Avoid comments that explain obvious statements.
- Update comments whenever related behavior changes.
- Do not store passwords, tokens, or confidential data in comments.
- Remove commented-out code from production files.
- Keep Javadoc synchronized with method parameters and behavior.
- Avoid very long comments that hide the implementation.
- Use clear code and descriptive identifiers whenever possible.
Example
public class OrderValidator {
private static final double MINIMUM_ORDER_AMOUNT = 100.0;
/**
* Checks whether an order meets the minimum purchase requirement.
*
* @param orderAmount total order amount
* @return true when the order amount is valid
*/
public boolean isValid(double orderAmount) {
// The minimum protects against processing costs on very small orders.
return orderAmount >= MINIMUM_ORDER_AMOUNT;
}
public static void main(String[] args) {
OrderValidator validator = new OrderValidator();
System.out.println(validator.isValid(150.0));
}
}Output
trueInterview Tips
- Treat comments as code that must be maintained.
- Review Javadoc during every API change.
- Never expose credentials or private information in comments.
- Delete dead code and rely on version control for history.
- Prefer self-explanatory code over excessive comments.
Summary
Poor comments become misleading, insecure, or difficult to maintain. Effective comments remain accurate, explain non-obvious decisions, and support clear source code.