
Amplitude Data supports tracking analytics events from JRE programs written in Java (6 and higher).

## Quick start

1. [Install the Amplitude SDK](#install-the-amplitude-sdk)

   ```java
   implementation 'com.amplitude:java-sdk:[1.8.0,2.0)'
   implementation 'org.json:json:20201115'
   ```

2. [Install the Ampli CLI](#install-the-ampli-cli)

   ```shell
   npm install -g @amplitude/ampli
   ```

3. [Pull the Ampli Wrapper into your project](#pull)

   ```shell
   ampli pull [--path ./src/main/java/com/amplitude/ampli]
   ```

4. [Initialize the Ampli Wrapper](#load)

   ```java
   import com.amplitude.ampli.*;

   Ampli.getInstance().load(new LoadOptions()
     .setClient(new LoadClientOptions().setApiKey(AMPLITUDE_API_KEY))
   );
   ```

5. [Identify users and set user properties](#identify)

   ```java
   Ampli.getInstance().identify("user-id",
      Identify.builder().userProp("A user property").build()
   );
   ```

6. [Track events with strongly typed methods and classes](#track)

   ```java
   Ampli.getInstance().songPlayed("user_id",
     SongPlayed.builder().songId("song-1").build()
   );
   Ampli.getInstance().track("user_id",
     SongFavorited.builder().songId("song-2").build()
   );
   ```

7. [Flush events before application exit](#flush)

   ```java
   Ampli.getInstance().flush()
   ```

8. [Verify implementation status with CLI](#status)

   ```shell
   ampli status [--update]
   ```

## Install the Amplitude SDK

If you haven't already, install the core Amplitude SDK dependencies.

{% tabs tabs="Java, Kotlin" %}
{% tab name="Java" %}
Inside `<dependencies>` add:

```xml
<dependency>
    <groupId>com.amplitude</groupId>
    <artifactId>java-sdk</artifactId>
    <version>[1.8.0,2.0)</version>
</dependency>
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20201115</version>
</dependency>
```

{% /tab %}
{% tab name="Kotlin" %}

```bash
implementation 'com.amplitude:java-sdk:[1.8.0,2.0)'
implementation 'org.json:json:20201115'
```

{% /tab %}
{% /tabs %}

## Install Ampli CLI

Install the [Ampli CLI](/docs/sdks/ampli/ampli-cli) from Homebrew or npm.

{% code-group %}
```bash Homebrew
brew tap amplitude/ampli
brew install ampli
```

```bash npm
npm install -g @amplitude/ampli
```
{% /code-group %}

### Pull the Ampli Wrapper into your project

Run the Ampli CLI `pull` command to log in to Amplitude Data and download the strongly typed Ampli Wrapper for your tracking plan. Run Ampli CLI commands from the project root directory.

```bash
ampli pull
```

## Load

Initialize Ampli in your code. The `load()` method accepts configuration option arguments:

{% code-group %}
```java Java
import com.amplitude.ampli.*;

Ampli.getInstance().load(new LoadOptions()
    .setClient(new LoadClientOptions().setApiKey(AMPLITUDE_API_KEY))
);
```

```kotlin Kotlin
import com.amplitude.ampli.*

ampli.load(LoadOptions(
    client = LoadClientOptions(apiKey = AMPLITUDE_API_KEY)
))
```
{% /code-group %}

| Arg               | Description                                                                                                                                                     |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `LoadOptions`     | Required. Specifies configuration options for the Ampli Wrapper.                                                                                                |
| `disabled`        | Optional. Specifies whether the Ampli Wrapper does any work. When true, all calls to the Ampli Wrapper are no-ops. Useful in local or development environments. |
| `client.instance` | Required if `client.apiKey` isn't set. Specifies an Amplitude instance. By default Ampli creates an instance for you.                                           |
| `client.apiKey`   | Required if `client.instance` isn't set. Specifies an API Key. This option overrides the default, which is the API Key configured in your tracking plan.        |

## Identify

Call `identify()` to set user properties.

Ampli creates types for user properties, the same way it creates types for events and their properties.

The `identify()` function accepts an optional `userId`, optional user properties, and optional `options`.

For example, your tracking plan contains a user property called `userProp`. The property's type is a string.

{% code-group %}
```java Java
Ampli.getInstance().identify("user-id", Identify.builder()
    .userProp("A user property")
    .build()
);
```

```kotlin Kotlin
ampli.identify("user-id", Identify(
    userProp = "A trait associated with this user"
))
```
{% /code-group %}

The `options` argument lets you pass [Amplitude fields](/docs/apis/analytics/http-v2#event-array-keys) for this call, such as `deviceId`.

{% code-group %}
```java Java
Ampli.getInstance().identify(
    userId,
    Identify.builder().userProp("A trait associated with this user").build(),
    new EventOptions().setDeviceId(deviceId).setUserId("some-user"),
);
```

```kotlin Kotlin
ampli.identify(userId, Identify(
    userProp = "A trait associated with this user",
    )
    EventOptions(deviceId = "device-id"),
)
```
{% /code-group %}

## Group

Call `setGroup()` to associate a user with their group (for example, their department or company). The `setGroup()` function accepts a required `groupType`, and `groupName`.

{% code-group %}
```java Java
Ampli.getInstance().setGroup("user-id", "GroupType", "GroupName");
```

```kotlin Kotlin
ampli.setGroup("user-id", "GroupType", "GroupName");
```
{% /code-group %}

Amplitude supports assigning users to groups and running queries on those groups, such as Count by Distinct. If at least one member of the group performs a specific event, the count includes the group.

For example, to group users by organization, use an `orgId`. Joe is in `orgId` `10`, and Sue is in `orgId` `15`. Sue and Joe both perform a certain event. You can query their organizations in the Event Segmentation Chart.

When you set groups, define a `groupType` and `groupName`. In the previous example, `orgId` is the `groupType` and `10` and `15` are the values for `groupName`. Another example of a `groupType` is `sport` with `groupName` values like `tennis` and `baseball`.

Setting a group also sets `groupType:groupName` as a user property, and overwrites any existing `groupName` value for that user's `groupType` and the corresponding user property value. `groupType` is a string. `groupName` can be a string or an array of strings, which indicates that a user is in multiple groups.

For example, if Joe is in `orgId` `10` and `20`, the `groupName` is `[10, 20]`.

Your code might look like this:

{% code-group %}
```java Java
Ampli.getInstance().setGroup("user-id", "orgID", ["10", "20"]);
```

```kotlin Kotlin
ampli.setGroup("user-id", "orgId", ["10", "20"]);
```
{% /code-group %}

## Track

To track an event, call the event's corresponding function. Every event in your tracking plan has its own function in the Ampli Wrapper. The call uses this structure:

{% code-group %}
```java Java
Ampli.getInstance().track(String userId, Event event, EventOptions options, MiddlewareExtra extra)
```

```kotlin Kotlin
ampli.track(userId: String, event: Event, options: EventOptions, extra: MiddlewareExtra)
```
{% /code-group %}

The `options` argument lets you pass [Amplitude fields](/docs/apis/analytics/http-v2#event-array-keys), like `price`, `quantity`, and `revenue`. The `extra` argument lets you pass data to middleware.

For example, in the following code snippet, your tracking plan contains an event called `songPlayed`. The event has two required properties: `songId` and `songFavorited`. The property type for `songId` is string, and `songFavorited` is a boolean.

The event defines one [Amplitude field](/docs/apis/analytics/http-v2#event-array-keys): `deviceId`. The event also defines one MiddlewareExtra: `extra`. For more information, refer to [Middleware](/docs/sdks/sdk-middleware).

{% code-group %}
```java Java
MiddlewareExtra extra = new MiddlewareExtra();
extra.put("extra-key", "extra-value");

Ampli.getInstance().songPlayed("user-id",
    SongPlayed.builder()
    .songId('songId') // String
    .songFavorited(true) // Boolean
    .build(),
    new EventOptions().setDeviceId(deviceId),
    extra
);
```

```java Kotlin
ampli.songPlayed("user-id",
    SongPlayed(
    songId = 'songId', // String,
    songFavorited = true, // Boolean
    ),
    options = EventOptions(deviceId = "device-id"),
    extra = MiddlewareExtra(mapOf("extra-key" to "extra-value")
));
```
{% /code-group %}

Ampli also generates a class for each event.

{% code-group %}
```java Java
SongPlayed event = SongPlayed.builder()
    .songId('songId') // String
    .songFavorited(true) // Boolean
    .build()
```

```kotlin Kotlin
val myEventObject = SongPlayed(
    songId = 'songId', // String,
    songFavorited = true, // Boolean
);
```
{% /code-group %}

Send Event objects using the generic track method.

{% code-group %}
```java Java
Ampli.getInstance().track("user-id", SongPlayed.builder()
    .songId('songId') // String
    .songFavorited(true) // Boolean
    .build()
);
```

```kotlin Kotlin
ampli.track("user-id", SongPlayed(
    songId = 'songId', // String,
    songFavorited = true, // Boolean
));
```
{% /code-group %}

## Flush

The Ampli Wrapper queues events and sends them at an interval based on the configuration.

Call `flush()` to immediately send any pending events.

The `flush()` method returns a promise you can use to confirm that Ampli has sent all pending events before continuing. Call `flush()` before the application exits.

Ampli flushes buffered events automatically when it reaches `flushQueueSize` or `flushInterval`.

Ampli sends events automatically without calling `flush()`. Use `flush()` when you need to send events before the application exits.

## Ampli CLI

### Pull

The `pull` command downloads the Ampli Wrapper code to your project. Run the `pull` command from the project root.

```bash
ampli pull
```

Ampli prompts you to log in to your workspace and select a source.

```bash
➜ ampli pull
Ampli project is not initialized. No existing `ampli.json` configuration found.
? Create a new Ampli project here? Yes
? Organization: Amplitude
? Workspace: My Workspace
? Source: My Source
```

### Status

Verify that your code implements all tracking-plan events with the `status` command:

```bash
ampli status [--update]
```

The output displays the status and shows which events are missing.

```bash
➜ ampli status
✘ Verifying event tracking implementation in source code
 ✔ Song Played (1 location)
 ✘ Song Stopped Called when a user stops playing a song.
Events Tracked: 1 missed, 2 total
```

Learn more about [`ampli status`](/docs/sdks/ampli/ampli-cli#status).
