CSE Roadmap

Common tier · about 2 hours · 7 parts

Part 6 of 7 · 1 min read

Habits that cost marks

Common Java traps in interview code.

Habits that cost marks

  • Public fields. They let any class change state. Use private and expose methods.
  • Mutable static state. A static list shared by every part of the program makes tests and threads hard. Pass objects in.
  • Returning null. Callers forget to check. Throw an exception, or return an Optional where absence is normal.
  • Comparing strings and ids with ==. Use equals.
  • Catching Exception and ignoring it. Catch the specific case, and say what happens.
  • God class. One Manager with 30 methods. Split by responsibility.
  • Instanceof chains. A long if (x instanceof A) ... else if (x instanceof B) is a sign that polymorphism (Level 1) is missing.

Common mistake

Writing the whole answer as one large main method. A reader cannot see the design in it.

Interview angle

Answer in your head first, then open it.

Why a record here?

The value never changes and equality is by content.

Why is this field private?

So that only the class can change its state and keep its rules.

Why not double for money?

Floating-point numbers cannot hold most decimal amounts exactly. Cents in an integer can.

Check yourself: 1. Why is mutable static state a problem? 2. What replaces == for comparing ids? 3. What does an instanceof chain suggest?

Words you will meet

Word Meaning
Intention-revealing name A name that tells what a thing is for
Record A short Java class for a value that does not change
Enum A fixed set of named values
Interface A promise that several classes can keep
Static state Data shared by the whole program, which is hard to test
Optional A Java box that may or may not hold a value