Sobes.tech
Senior

How does valueOf differ from fromString?

sobes.tech AI

Answer from AI

In Java, the methods valueOf and fromString are often used to convert strings into objects, but they have different semantics and are used in different contexts.

  • valueOf(String) — is a standard static method that is usually present in wrapper classes (e.g., Integer.valueOf(String)) and enums (Enum.valueOf(Class<T>, String)). It converts a string into an object of the corresponding type, often with caching (e.g., for numbers within a range). In enums, valueOf strictly requires an exact match of the constant's name.

  • fromString(String) — is a custom or auxiliary method that is often implemented for more flexible or extended string parsing. For example, it may accept different formats, ignore case, handle errors, or return null instead of throwing an exception.

Example for enum:

public enum Status {
    NEW, IN_PROGRESS, DONE;

    public static Status fromString(String s) {
        if (s == null) return null;
        switch (s.toLowerCase()) {
            case "new": return NEW;
            case "inprogress": return IN_PROGRESS;
            case "done": return DONE;
            default: throw new IllegalArgumentException("Unknown status: " + s);
        }
    }
}

Here, valueOf requires an exact match with NEW, IN_PROGRESS, DONE, while fromString allows for more flexible input processing.

Thus, valueOf is a standard, strict conversion method, whereas fromString is a more flexible, often user-defined method for string conversion.