🐞 Bug in the JDK? A Curious Case with Enum.valueOf()
TL;DR:
Don’t worry, this won’t break your app. It’s a harmless quirk, but an interesting one I stumbled upon while preparing for the Java 21 certification.
While studying for the Java 21 Certification, I had to explore many corners of the language that I don’t usually touch in day-to-day development. It’s been an eye-opening journey — lots of learning, and plenty of hidden details that we often take for granted.
And then I ran into something… odd.
You probably know that Enum.valueOf()
throws an IllegalArgumentException
when the provided string doesn’t match any constant in the enum. Here’s a basic example:
enum Date {
DAY,
WEEK,
MONTH;
}
public class Main {
public static void main(String[] args) {
System.out.println(Date.valueOf("DAY")); // ✅ OK
System.out.println(Date.valueOf("Banana")); // ❌ Throws IllegalArgumentException: No enum constant Date.Banana
}
}
Makes sense, right?
But here’s where it gets weird. You can actually declare an enum
inside a method — and when you do, things behave differently.
public class Main {
public static void main(String[] args) {
enum Type {
DAY, WEEK, MONTH;
}
System.out.println(Type.valueOf("DAY")); // ✅ OK
System.out.println(Type.valueOf("Banana")); // ❌ IllegalArgumentException: No enum constant null.Banana
}
}
Wait — null.Banana
? 🤨
🤯 What’s going on?
Behind the scenes, all enums in Java extend the abstract java.lang.Enum
class, and the valueOf()
method is defined as:
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
This method relies on Class.getCanonicalName()
to include the enum’s full name in the error message. However, if the enum is declared inside a method, it doesn’t have a canonical name, so the result is null
.
Don’t believe me? Try this:
public class Main {
public static void main(String[] args) {
class A {}
System.out.println(A.class.getCanonicalName()); // Prints: null
}
}
🧠 Why does this matter?
Is this a real bug? Maybe. Is it a big deal? Probably not.
But it’s a great reminder that going deep into the language, especially while studying for certification, can expose behavior you wouldn’t normally encounter.
These little discoveries are part of what makes learning fun.
PS: Don’t write enums inside methods in production code. Seriously. 😄
Want to see more quirky corners of the JDK? Or have you stumbled upon something strange yourself?
Drop a comment and share it, I’d love to hear about it!