ChoiceFormat

ChoiceFormat is a subclass of NumberFormat used to map numeric ranges to custom strings. It is ideal when a numeric value should be translated into a human-readable category, such as converting scores to grades, salary ranges to designations, or item quantities to messages like “few”, “many”, etc.

Key Features

  • Maps numerical ranges to specific strings.
  • Supports boundary-based choices (e.g., x ≤ value < y).
  • Used for categorization based on number values.

Common Used Methods 

Simple Program

import java.text.ChoiceFormat;

public class SimpleChoiceFormatExample {
    public static void main(String[] args) {
        double[] limits = {0, 50, 70, 90};
        String[] grades = {"Poor", "Average", "Good", "Excellent"};

        ChoiceFormat choiceFormat = new ChoiceFormat(limits, grades);

        double[] scores = {45, 55, 75, 95};

        for (double score : scores) {
            String result = choiceFormat.format(score);
            System.out.println("Score: " + score + " => Grade: " + result);
        }
    }
}
/*
Score: 45.0 => Grade: Poor
Score: 55.0 => Grade: Average
Score: 75.0 => Grade: Good
Score: 95.0 => Grade: Excellent
*/

Problem Statement

Paani and Mahesh are developing an HR reporting system. One requirement is to generate performance review comments based on employee ratings:

import java.text.ChoiceFormat;

public class PerformanceReviewSystem {

    public static void main(String[] args) {
        double[] limits = {0, 3, 5, 7, 9};
        String[] reviews = {
            "Unsatisfactory",
            "Needs Improvement",
            "Meets Expectations",
            "Exceeds Expectations",
            "Outstanding"
        };

        ChoiceFormat reviewFormat = new ChoiceFormat(limits, reviews);

        // Sample employee ratings for demonstration
        double[] employeeRatings = {2.5, 3.7, 5.8, 7.2, 9.9};

        System.out.println("----- Employee Performance Review -----");
        for (int i = 0; i < employeeRatings.length; i++) {
            String result = reviewFormat.format(employeeRatings[i]);
            System.out.println("Employee " + (i + 1) + " Rating: " + employeeRatings[i] + " => Review: " + result);
        }
    }
}
/*
----- Employee Performance Review -----
Employee 1 Rating: 2.5 => Review: Unsatisfactory
Employee 2 Rating: 3.7 => Review: Needs Improvement
Employee 3 Rating: 5.8 => Review: Meets Expectations
Employee 4 Rating: 7.2 => Review: Exceeds Expectations
Employee 5 Rating: 9.9 => Review: Outstanding
*/

The ChoiceFormat class provides an efficient and elegant way to map numeric ranges to custom strings in Java. It is particularly useful in situations where numerical values represent categories such as grades, performance levels, or descriptions.

Scroll to Top