How to use ConfigCat's Feature Flags in Java
Published: 2022-11-21 11:17:59

description: Using feature flags in Java is easy when using the ConfigCat feature management system. This tutorial shows you exactly how to do that.
tags: [java, feature flags, sample app]
image: /assets/java-ff/cover.png

Java is one of the most widely used programming languages. Whether you've used it, know someone who has, studied it in university, or despise it, it's no surprise that many software products are developed in Java. So, keep reading if you want to learn how to quickly enable features in Java, with no redeployment and no fuss.

<!--truncate-->

## Feature Flags in a Nutshell

Sometimes, you want features to be easily turned on and off inside your application, but that can force you to redeploy - which leads to downtimes and a lot of headaches. Wouldn’t it be nice to have a variable that can enable things and that you can control from a distance? Well, it would - which is why there are feature flags.

Feature toggles, which are essentially remote-controlled boolean variables, can assist developers in improving workflows and resolving otherwise complex issues.
Simply wrap your code in a conditional statement with the flag, and you're good to go.

## Using Feature Flags in Java

As Java is regarded mostly as a backend language, in this tutorial we’re going to focus on functionality. So what will our app do? It's payday, and we'd like our management system to display each employee's pay. We want to give our employees a 10% bonus because we made a lot of money this quarter. It's not uncommon for our imaginary company to award bonuses, so we need a way to quickly enable this feature on an as-needed basis. In order to do that, I will use [ConfigCat’s](https://configcat.com/) feature flag management system. Let's get started.

**Note**: You can consult the sample app [here](https://github.com/configcat-labs/feature-flags-in-java-sample).

## Setting Up

The first step is creating a Java project. The SDK I'm using supports both Maven and Gradle, but in this tutorial, I'll be using the latter. I've chosen Intellij as an IDE and used it with the settings shown below. This process may differ slightly depending on the IDE you use.

![Setting up the project in Intellij](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z7hr3xgl7vbf4vllyvr9.png)

Once the project has been created, it’s time to create the flag. If you haven't already, go to [ConfigCat](https://app.configcat.com/) and sign up for a free account. Then, add a new feature flag to your dashboard, which we'll call "bonus."

![Adding a new feature flag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kc91nmzvjaixtr8l4i7i.png)

When the bonus flag is false, no bonus is added to the salary. When it’s turned on we’ll give each employee a 10% raise. It's that easy.
While we're here, locate your SDK key in the upper right-hand corner of the screen. You’re going to need this in just a moment.

![Locating the personal SDK key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rb8qh70zkxexacbue7la.png)

In order to connect the SDK to your local project, you need to edit the Gradle settings. This can sound intimidating if you haven’t done it before, but it’s actually quite simple. Go to gradle.settings and add the following lines in dependencies:

```java
dependencies {
    ...
    implementation group: 'com.configcat', name: 'configcat-java-client', version: '7.+'
    implementation group: 'org.slf4j', name: 'slf4j-simple', version: '1.+'
}
```

Now, go to `Main.Java` and add the following statement to import the ConfigCat library.

```java
import com.configcat.*;
```

**Hint**: You might need to refresh Gradle in order for the library to be imported.

## Adding the flag

Now, it’s time to start coding. First, create a ConfigCat client by pasting the code below.

```java
ConfigCatClient client = ConfigCatClient.newBuilder()
                .build("YOUR-SDK-KEY-HERE");
```

Then, let’s start by getting the value of our flag from the dashboard to check if everything is going according to plan.

```java
boolean bonus = client.getValue(Boolean.class, "bonus", false);
System.out.println("bonus' value from ConfigCat: " + bonus);
```

Running the program now should print “bonus’ value from ConfigCat: false”.

Great, the feature flag is connected! Let’s use it for something useful.
Add the section below and I’ll walk you through what it does.

```java
public class Main {
    public static void main(String[] args) {
        ...

        displaySalaries(bonus);

    }

    public static void displaySalaries(boolean bonus){
        String[] employees = {"Ada Lovelace", "Alan Turing", "Edsger Dijkstra", "Grace Hopper"};

        int[] salaries = {2500, 1700, 2450, 3500};

        if(bonus){
            for (int i =0; i<employees.length; i++)
            {
                System.out.println(employees[i] + ": " + (salaries[i] + 0.1*salaries[i]));
            }
        }
        else{
            for (int i =0; i<employees.length; i++)
            {
                System.out.println(employees[i] + ": " + salaries[i]);
            }
        }
    }
}
```

I’ve added some dummy data representing our employees and their salaries. The displaySalaries method then prints each person’s pay on the screen. As you can see, the flag is used in a conditional statement to determine whether or not a bonus is added.
Since the flag was turned off by default when we created it, if you run the program you should see the base salaries displayed.

![Result with bonus flag on and off](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t73xdfazbwghzfgb8z8e.png)

## Toggling the Flag

Head back to the dashboard, enable the flag and apply the changes. When you run the application again, you'll notice that the results have changed - the bonus has been added. There was no need to touch the code again for the flag’s value to change, making changing it the simplest thing ever. Pretty sweet, right?

![Toggling the feature flag on](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gy7q61ubbpsucp66311h.png)

## Key Takeaways

Even in Java, feature flags can be easily added to new projects and integrated into existing apps. 

In this article, I walked you through a simple application that toggles a functionality using feature flags. So, let's go over what you need to do to include these fantastic mechanisms in your own Java app.

- Create a Java application to handle your needs
- Create a ConfigCat account and a feature flag
- Add the SDK dependencies in Gradle
- Add the flag in a conditional statement to handle your feature
- Toggle the flag to see the updated result

Once your product has reached its intended users, making changes implies code redeployment, downtime, and the installation of updates on the users' end, which can result in issues or even revenue loss. By using feature flags, you can ensure a much smoother transition between versions. Plus, you can perform A/B testing, user segmentation based on various criteria, test your code in production, and perform canary releases.

If you want to learn more about the power of feature flags, check out [ConfigCat’s blog](https://configcat.com/blog/), as well as [Facebook](https://www.facebook.com/configcat), [Linkedin](https://www.linkedin.com/company/configcat/), and [Twitter](https://twitter.com/ConfigCat).