The availability of features may depend on your plan type. Contact your Customer Success Manager if you have any questions.
Dev guideRecipesAPI ReferenceChangelog
Dev guideAPI ReferenceRecipesChangelogUser GuideGitHubDev CommunityOptimizely AcademySubmit a ticketLog In
Dev guide

Example usage of the Java SDK

A brief code example of how to use the Optimizely Feature Experimentation Java SDK to evaluate feature flags, activate A/B tests, or feature tests.

After installing the Java SDK, import the Optimizely library, get your project's datafile, and create a client. Use the client to evaluate flag rules like A/B tests and flag deliveries.

This example walks through the following three key steps:

  1. Evaluate a flag with the key product_sort using the decide method. This also sends a decision event to Optimizely to record that the user was exposed to the experiment.

  2. Run code based on the flag result. The SDK evaluates your flag rules and determines which variation the user is in. You can either:

    • Check the flag's enabled state and read a configuration variable (sort_method) to determine which experience the user gets.
    • Check the flag variation directly and run the corresponding control or treatment code.
  3. Track a conversion event called purchased to measure the experiment's impact. The trackEvent method ties the purchase back to the A/B test and sends it to Optimizely so it displays on your Experiment Results page.

import com.optimizely.ab.Optimizely;
import com.optimizely.ab.OptimizelyFactory;
import com.optimizely.ab.OptimizelyUserContext;
import com.optimizely.ab.optimizelydecision.OptimizelyDecision;
import com.optimizely.ab.optimizelyjson.OptimizelyJSON;
import com.fasterxml.jackson.core.JsonParseException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

// Instantiate an Optimizely client    
public class App {
    public static void main(String[] args) {
        String sdkKey = "<Your_SDK_Key>";
        Optimizely optimizely = OptimizelyFactory.newDefaultInstance(sdkKey);
        
        // Create a user and decide a flag rule (such as an A/B test) for them
        Map<String, Object> attributes = new HashMap<>();
        attributes.put("logged_in", true);
        OptimizelyUserContext user = optimizely.createUserContext("user123", attributes);
        
        OptimizelyDecision decision = user.decide("product_sort");
        
        // Did the decision fail with a critical error?
        String variationKey = decision.getVariationKey();
        if (variationKey == null) {
            List<String> reasons = decision.getReasons();
            System.out.println("decision error: " + reasons);
            return;  // Exit if decision failed
        }
        
        // Execute code based on flag enabled state
        boolean enabled = decision.getEnabled();
        OptimizelyJSON variables = decision.getVariables();
        
        if (enabled) {
            String sortMethod = null;
            try {
                sortMethod = variables.getValue("sort_method", String.class);
                // Execute code for sort method value
                System.out.println("Sort method: " + sortMethod);
            } catch (JsonParseException e) {
                e.printStackTrace();
            }
        }
        
        // Or execute code based on flag variation
        if ("control".equals(variationKey)) {
            // Execute code for control variation
        } else if ("treatment".equals(variationKey)) {
            // Execute code for treatment variation
        }
        
        // Track an event
        user.trackEvent("purchased");
    }
}