SteelReed

Search

Search posts, questions…

Java CoreQuestion 18 / 43

Junior

Why use an enum instead of String constants? Does an enum have a constructor, and how do you parse one from input?

Short answer

An enum is a fixed set of values (like order statuses) checked by the compiler. Each constant has exactly one object, so you compare with ==.

trim, toUpperCaseLocale.ROOTvalidIllegalArgumentExceptionInput: ' paid 'OrderStatus.valueOfOrderStatus.PAIDReturn 400with valid values

3 points to say:

  1. valueOf is case-sensitive and throws on a wrong name.
  2. Bad user input returns 400, not 500.
  3. Store the name or a code in the database, never ordinal().

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.