Cosmic Module
J
Qubits of DPK
March 15, 2026
Core Java
Java Naming Conventions
javascript
QUBITS OF DPK
java
QUBITS OF DPK
Anonymous Objects
An object created without assigning it to a reference variable. Used once and immediately garbage collected.
java
QUBITS OF DPK
When to Use Anonymous Objects
java
QUBITS OF DPK
️ Anonymous Object Traps
java
QUBITS OF DPK
Interview Answer
"Java naming conventions: classes and interfaces use PascalCase, methods and variables use camelCase, constants use UPPER_SNAKE_CASE, packages use lowercase. An anonymous object is created with new but not assigned to a reference variable — used once and immediately eligible for garbage collection. Common use cases: passing objects directly as method arguments, one-time method calls, and event listeners where storing the reference isn't needed."
Interview Questions & MAANG-Level Answers
Q1. What are Java naming conventions?
Classes and interfaces: PascalCase (BankAccount, Runnable). Methods and variables: camelCase (calculateInterest(), studentName). Constants (static final): UPPER_SNAKE_CASE (MAX_RETRY_COUNT, DB_URL). Packages: all lowercase, reverse domain (com.google.auth). These aren't enforced by the compiler but are industry-standard — MAANG companies enforce them strictly in code reviews.
Q2. What is an anonymous object?
An object created with new without assigning it to a reference variable. It is used immediately and is eligible for garbage collection right after use:
java
QUBITS OF DPK
Vs named object: Car myCar = new Car(); myCar.accelerate(); — myCar keeps the object alive for reuse.
Q3. When would you use an anonymous object over a named reference?
When you need to use an object exactly once: (1) Passing as a method argument: printInfo(new Student("Deepak", 101)). (2) Chaining methods in one expression: new StringBuilder("Hi").append(" Deepak").toString(). (3) Event listeners/callbacks where you implement and discard: button.addListener(new ClickListener() { ... }). (4) Testing one-off scenarios. If you need the object more than once, always use a named reference.
Q4. What happens to an anonymous object after it's used?
Since no reference variable holds it, the object immediately becomes unreachable. The Garbage Collector marks it as eligible for collection and will reclaim its heap memory in the next GC cycle. This is memory-efficient for truly one-time use — no reference kept alive unnecessarily. However, in a loop, creating many anonymous objects repeatedly adds GC pressure.
Q5. What is the convention for constants in Java?
Constants are declared static final and named in UPPER_SNAKE_CASE:
java
QUBITS OF DPK
Accessed via class name: MathConstants.PI. Placing related constants in an interface or enum is also common. In modern Java, prefer enums over static final int constants for type safety.