
{% callout type="note" %}
These docs cover the Java/Kotlin SDK in a multi-user, server-side context. For client-side Android applications, go to the [Android SDK](/client/Android) or one of the other client SDKs for your client-side applications.
{% /callout %}

This SDK is written in Kotlin, but exposes methods and overrides to Java based applications.

## Setup the SDK

{% steps %}
{% step title="Install the SDK" %}
`v1.X.X+` of the SDK is now published only to Maven Central.

To install the SDK, set the Maven Central repository in your `build.gradle`. You probably already have this for other dependencies.

```groovy
repositories {
    mavenCentral()
}
```

Then add the dependency:

```groovy
implementation 'com.statsig:serversdk:1.X.X' // replace with the most up to date version
// For >v1.24.0 If you are not using streaming and want to reduce the package size you can:
implementation 'com.statsig:serversdk:1.X.X' {
    exclude(group = "io.grpc", module = "*") 
}
```

You can find the versions in the github releases of the [open source sdk repository](https://github.com/statsig-io/java-server-sdk/releases), or from the [maven central repository](https://mvnrepository.com/artifact/com.statsig/serversdk).

### Jitpack deprecation

`v0.X.X` versions of the SDK are available from jitpack, but newer versions won't be published to jitpack.

{% callout type="note" %}
If you update Statsig to be pulled from Maven Central instead of jitpack, you can remove `maven { url 'https://jitpack.io' }` if Statsig was the only library you got from jitpack and you previously relied on v0.X.X of the SDK.
{% /callout %}
{% /step %}

{% step title="Initialize the SDK" %}
After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys).

{% callout type="warning" %}
Do NOT embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. However, if you accidentally expose it, you can create a new one in the Statsig console.
{% /callout %}

{% codetabs %}
```java Java
import com.statsig.sdk.Statsig;

StatsigOptions options = new StatsigOptions();
// Customize options as needed. For example:
// options.initTimeoutMs = 9999;
Future initFuture = Statsig.initializeAsync("server-secret-key", options);
initFuture.get();
```

```kotlin Kotlin
import com.statsig.sdk.Statsig

val options = StatsigOptions().apply {
        // Customize options as needed. For example:
        initTimeoutMs = 9999
}
async { Statsig.initialize("server-secret-key", options) }.await()
```
{% /codetabs %}

`initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independently of API calls.
{% /step %}
{% /steps %}

## Working with the SDK

## Checking a Feature Flag/Gate

After the SDK is initialized, you can check a [**Feature Gate**](/feature-flags/overview). Feature Gates create logic branches in code that can be rolled out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (`return false;`) by default.

All APIs require you to specify the user (refer to [Statsig user](#statsig-user)) associated with the request. For example, to check a gate for a user:

{% codetabs %}
```java Java
StatsigUser user = new StatsigUser("user_id");
Boolean isFeatureOn = Statsig.checkGateSync(user, "use_new_feature");

if (isFeatureOn) {
  // Gate is on, use new feature
} else {
  // Gate is off
}
```

```kotlin Kotlin
val user = StatsigUser("user_id");
val featureOn = Statsig.checkGateSync(user, "use_new_feature")

if (featureOn) {
  // Gate is on, use new feature
} else {
  // Gate is off
}
```
{% /codetabs %}

## Reading a Dynamic Config

Feature Gates work well for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use [**Dynamic Configs**](/dynamic-config/overview). The Dynamic Config API is similar to Feature Gates, but returns a full JSON object configured on the server, from which you can fetch typed parameters.

{% codetabs %}
```java Java
DynamicConfig config = Statsig.getConfigSync(user, "awesome_product_details");
String itemName = config.getString("product_name", "Awesome Product v1");
double price = config.getDouble("price", 10.0);
```

```kotlin Kotlin
val config = Statsig.getConfigSync(user, "awesome_product_details")
val itemName = config.getString("product_name", "Awesome Product v1")
val price = config.getDouble("price", 10.0)
```
{% /codetabs %}

## Getting a Layer/Experiment

Use **Layers/Experiments** to run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](/experiments/layers-overview) for faster iterations with parameter reuse.

{% codetabs %}
```java Java
// Values via getLayer
Layer layer = Statsig.getLayerSync(user, "user_promo_experiments");
String title = layer.getString("title", "Welcome to Statsig!");
double discount = layer.getDouble("discount", 0.1);

// or, via getExperiment
DynamicConfig experiment = Statsig.getExperimentSync(user, "new_user_promo");
String expTitle = experiment.getString("title", "Welcome to Statsig!");
double expDiscount = experiment.getDouble("discount", 0.1);
```

```kotlin Kotlin
// Values via getLayer
val layer = Statsig.getLayerSync(user, "user_promo_experiments")
val title = layer.getString("title", "Welcome to Statsig!")
val discount = layer.getDouble("discount", 0.1)

// or, via getExperiment
val experiment = Statsig.getExperimentSync(user, "new_user_promo")
val expTitle = experiment.getString("title", "Welcome to Statsig!")
val expDiscount = experiment.getDouble("discount", 0.1)
```
{% /codetabs %}

## Logging an Event

To track custom events and measure how features or experiment groups affect those events, call the Log Event API. Specify the user and event name to log, and optionally provide a value and metadata object:

{% codetabs %}
```java Java
Statsig.logEvent(user, "add_to_cart", "SKU_12345", 
    Map.of("price", "9.99", "item_name", "diet_coke_48_pack"));
```

```kotlin Kotlin
Statsig.logEvent(user, "add_to_cart", "SKU_12345", 
    mapOf("price" to "9.99", "item_name" to "diet_coke_48_pack"))
```
{% /codetabs %}

For more about identifying users, group analytics, and best practices, go to the [logging events guide](/guides/logging-events).

## Retrieving Feature Gate Metadata

When you need more than a boolean value from a gate evaluation, use the Get Feature Gate API, which returns a FeatureGate object with additional evaluation metadata:

{% codetabs %}
```java Java
FeatureGate gate = Statsig.getFeatureGateSync(user, "use_new_feature");
boolean value = gate.getValue();
String ruleId = gate.getRuleID();
EvaluationDetails details = gate.getEvaluationDetails();
```

```kotlin Kotlin
val gate = Statsig.getFeatureGateSync(user, "use_new_feature")
val value = gate.getValue()
val ruleId = gate.getRuleID()
val details = gate.getEvaluationDetails()
```
{% /codetabs %}

## Statsig User

When calling APIs that require a user, pass as much information as possible to take advantage of advanced gate and config conditions (like country or OS/browser level checks), and to correctly measure the impact of your experiments on your metrics/events. At least one identifier (userID or customID) is required to provide a consistent experience for a given user. Refer to [userID requirements](/sdks/user#why-is-an-id-always-required-for-server-sdks) for more detail.

In addition to `userID`, `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion` are available as top-level fields on StatsigUser. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them.

Typing on the `StatsigUser` object is lenient: you can pass numbers, strings, arrays, objects, and even enums or classes. However, evaluation operators only work on primitive types, mostly strings and numbers. The SDK attempts to cast custom field types to match the operator, but evaluation results for other types are not guaranteed. For example, an array set as a custom field is only compared as a string: there is no operator to match a value within that array.

### Private Attributes

To keep sensitive user PII data out of logs, use the `privateAttributes` field on the StatsigUser object. This field accepts an object/dictionary of private user attributes. Any attribute set in `privateAttributes` is used only for evaluation/targeting and is removed from all logs before Statsig sends them to its servers.

For example, if a feature gate should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user.

## Shutdown

To gracefully shutdown the SDK and ensure all events are flushed:

{% codetabs %}
```java Java
Statsig.shutdown();
```

```kotlin Kotlin
Statsig.shutdown()
```
{% /codetabs %}
