---
source_url: https://www.pubnub.com/docs/sdks/java
title: Java API & SDK Docs 13.4.0
updated_at: 2026-05-29T11:10:59.316Z
sdk_name: PubNub Java SDK
sdk_version: 6.4.5
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Java API & SDK Docs 13.4.0

PubNub Java SDK, use the latest version: 6.4.5

Install:

```bash
Add PubNub dependency to your build@6.4.5
```

:::warning Breaking changes in v9.0.0
PubNub Java SDK version 9.0.0 unifies the codebases for Java and [Kotlin](https://www.pubnub.com/docs/sdks/kotlin) SDKs, introduces a new way of instantiating the PubNub client, and changes asynchronous API callbacks and emitted [status events](https://www.pubnub.com/docs/sdks/java/status-events). These changes can impact applications built with previous versions (< `9.0.0`) of the Java SDK.
For more details about what has changed, refer to [Java/Kotlin SDK migration guide](https://www.pubnub.com/docs/sdks/kotlin/migration-guides/kotlin-v9-migration-guide).
:::

This guide walks you through a simple "Hello, World" application that demonstrates the core concepts of PubNub:

* Setting up a connection
* Sending messages
* Receiving messages in real-time

## Overview

This guide helps you get up and running with PubNub in your Java application. The Java software development kit (SDK) provides a simple interface for integrating PubNub real-time messaging. You'll learn how to set up PubNub, configure event listeners, subscribe to channels, and publish messages in a Java environment.

:::note Chat applications
If you want to create a mobile chat application with PubNub, refer to [Kotlin Chat SDK](https://www.pubnub.com/docs/chat/kotlin-chat-sdk) for details on all available chat features.
:::

## Prerequisites

Before we dive in, make sure you have:

* A basic understanding of Java
* An IDE like IntelliJ IDEA or Eclipse
* Java 8 or later installed
* A PubNub account (we'll help you set this up!)

## Setup

### Get your PubNub keys

First, get your PubNub keys:

* [Sign in](https://admin.pubnub.com/#/login) or [create an account](https://admin.pubnub.com/#/signup) on the PubNub Admin Portal.
* Create an app (or use an existing one).
* Find your publish and subscribe keys in the app dashboard.

When you create an app, PubNub automatically generates a keyset. You can use the same keyset for development and production, but we recommend separate keysets for each environment to improve security and management.

### Install the SDK

:::note SDK version
Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.
:::

You can install the PubNub Java SDK in several ways:

#### Maven

Add the following dependency to your `pom.xml`:

```xml
<dependency>
  <groupId>com.pubnub</groupId>
  <artifactId>pubnub-gson</artifactId>
  <version>13.4.0</version>
</dependency>
```

#### Gradle

Add the following to your `build.gradle` file:

```gradle
implementation group: 'com.pubnub', name: 'pubnub-gson', version: '13.4.0'
```

#### Source code

Clone the [GitHub repository](https://github.com/pubnub/kotlin):

```bash
git clone https://github.com/pubnub/kotlin
```

## Steps

### Initialize PubNub

In your Java application, create a new class (e.g., `App.java`) and initialize PubNub.

Make sure to replace the demo keys with your app's publish and subscribe keys from the Admin Portal.

```java
// Initialize PubNub
PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "demo");
// publishKey from Admin Portal (only required if publishing)
configBuilder.publishKey("demo");
configBuilder.secure(true);
PubNub pubnub = PubNub.create(configBuilder.build());
```

:::warning PNConfiguration class in Java
From version 10.0.0 of the Java SDK onward, the correct import for the `PNConfiguration` class is `com.pubnub.api.java.v2.PNConfiguration`.
:::

For more information, refer to the [Configuration](https://www.pubnub.com/docs/sdks/java/api-reference/configuration) section of the SDK documentation.

### Set up event listeners

Listeners help the application react to events and messages. You can implement custom app logic to respond to each type of message or event.

There are two main types of listeners you'll need to set up:

* Status listener - for connection state changes and operational events
* Event listener - for messages and presence events

Add listeners to handle connection status and incoming messages:

```java
// Add status listener to monitor connection state
pubnub.addListener(new StatusListener() {
    @Override
    public void status(PubNub pubnub, PNStatus status) {
        if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
            // This event happens when radio/connectivity is lost
            System.out.println("Connection lost");
        } else if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
            // Connect event. You can do stuff like publish, and know you'll get it.
            // Or just use the connected event to confirm you are subscribed for
            // UI / internal notifications, etc
            System.out.println("Connected to PubNub");
```

For more information, refer to the [Listeners](https://www.pubnub.com/docs/sdks/java/api-reference/configuration#event-listeners) section of the SDK documentation.

### Create a subscription

To receive messages sent to a particular channel, you need to subscribe to it. This allows you to receive messages published to that channel in real time:

```java
// Create a channel using the PubNub instance
Channel channel = pubnub.channel(channelName);

// Create a subscription for the channel
Subscription subscription = channel.subscription();
```

You can also subscribe to multiple channels at once using a subscription set:

```java
import java.util.Set;
import java.util.Collections;
import com.pubnub.api.java.v2.subscriptions.SubscriptionSet;
import com.pubnub.api.java.v2.subscriptions.EmptyOptions;

// Create a subscription set with multiple channels
SubscriptionSet subscriptionSet = pubnub.subscriptionSetOf(
    Set.of("channel1", "channel2", "channel3"), 
    Collections.emptySet(), 
    EmptyOptions.INSTANCE);

// Subscribe to all channels in the set
subscriptionSet.subscribe();
```

For more information, refer to the [Subscribe](https://www.pubnub.com/docs/sdks/java/api-reference/publish-and-subscribe#subscribe) section of the SDK documentation.

### Publish messages

When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel.

A message can be any type of JavaScript Object Notation (JSON)-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.

To send a message to a channel, use the `publish()` method on your channel object:

```java
// Create message payload using Gson to be sent when connected
final JsonObject messageJsonObject = new JsonObject();
JsonElement jsonElement = new JsonPrimitive("Hello World");
messageJsonObject.add("msg", jsonElement);

System.out.println("Message to send: " + messageJsonObject.toString());

// Publish the message when connected
channel.publish(messageJsonObject)
        .customMessageType("text-message")
        .async(result -> {
            result.onSuccess(res -> {
                // Message successfully published to specified channel.
                System.out.println("Message published successfully with timetoken: " + res.getTimetoken());
            }).onFailure(exception -> {
                // Request processing failed.
                // Handle message publish error
                System.out.println("Publish failed: " + exception.getMessage());
            });
        });
```

You can also publish messages with additional options:

```java
channel.publish(messageJsonObject)
    .customMessageType("text-message") // Add a custom message type
    .shouldStore(true) // Store the message in history
    .meta(metadataObject) // Add metadata for filtering
    .async(result -> {
        // Handle results
    });
```

For more information, refer to the [Publish and Subscribe](https://www.pubnub.com/docs/sdks/java/api-reference/publish-and-subscribe) section of the SDK documentation.

### Run the app

To run your Java application:

1. Save your complete code in a file like `App.java`.
2. Compile the file: `javac -cp "path/to/dependencies/*" App.java`.
3. Run the application: `java -cp ".:path/to/dependencies/*" App`.

You should see output similar to:

```text
PubNub initialized successfully
Subscribed to channel: myChannel
Connected to PubNub
Message to send: {"msg":"Hello World"}
Message successfully published with timetoken: 16789012345678901
Received on channel: myChannel
Received message: {"msg":"Hello World"}
The content of the message is: Hello World
```

Since you're both publishing and subscribing to the same channel in this example, you'll receive the messages you publish.

Add a delay to prevent the application from exiting immediately:

```java
// Add a delay so the program doesn't exit immediately
// This gives time to receive published messages
try {
    System.out.println("Waiting for messages. Program will exit in 60 seconds...");
    Thread.sleep(60000); // 60 seconds
} catch (InterruptedException e) {
    e.printStackTrace();
}

// Clean up before exiting
pubnub.disconnect();
System.out.println("Disconnected from PubNub");
```

## Complete example

```java
package com.pubnub.docs.basicUsage;

// snippet.basicPubSubApp
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.pubnub.api.PubNubException;
import com.pubnub.api.UserId;
import com.pubnub.api.enums.PNStatusCategory;
import com.pubnub.api.java.PubNub;
import com.pubnub.api.java.v2.PNConfiguration;
import com.pubnub.api.java.v2.callbacks.StatusListener;
import com.pubnub.api.java.v2.entities.Channel;
import com.pubnub.api.java.v2.subscriptions.Subscription;
import com.pubnub.api.models.consumer.PNStatus;

public class BasicUsageApp {
    public static void main(String[] args) throws PubNubException {
        // snippet.initializePubNub
        // Initialize PubNub
        PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "demo");
        // publishKey from Admin Portal (only required if publishing)
        configBuilder.publishKey("demo");
        configBuilder.secure(true);
        PubNub pubnub = PubNub.create(configBuilder.build());
        // snippet.end

        // Define a channel name
        final String channelName = "myChannel";

        // snippet.createChannel
        // Create a channel using the PubNub instance
        Channel channel = pubnub.channel(channelName);

        // Create a subscription for the channel
        Subscription subscription = channel.subscription();
        // snippet.end

        // snippet.setupEventListeners
        // Add status listener to monitor connection state
        pubnub.addListener(new StatusListener() {
            @Override
            public void status(PubNub pubnub, PNStatus status) {
                if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
                    // This event happens when radio/connectivity is lost
                    System.out.println("Connection lost");
                } else if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
                    // Connect event. You can do stuff like publish, and know you'll get it.
                    // Or just use the connected event to confirm you are subscribed for
                    // UI / internal notifications, etc
                    System.out.println("Connected to PubNub");

                    // snippet.publishMessage
                    // Create message payload using Gson to be sent when connected
                    final JsonObject messageJsonObject = new JsonObject();
                    JsonElement jsonElement = new JsonPrimitive("Hello World");
                    messageJsonObject.add("msg", jsonElement);

                    System.out.println("Message to send: " + messageJsonObject.toString());

                    // Publish the message when connected
                    channel.publish(messageJsonObject)
                            .customMessageType("text-message")
                            .async(result -> {
                                result.onSuccess(res -> {
                                    // Message successfully published to specified channel.
                                    System.out.println("Message published successfully with timetoken: " + res.getTimetoken());
                                }).onFailure(exception -> {
                                    // Request processing failed.
                                    // Handle message publish error
                                    System.out.println("Publish failed: " + exception.getMessage());
                                });
                            });
                    // snippet.end
                }
                // Handle other categories as needed
            }
        });
        // snippet.end

        // snippet.setupMessageListener
        // Set up a message listener for the subscription
        subscription.setOnMessage(pnMessageResult -> {
            // Handle new message stored in message.message
            System.out.println("Received on channel: " + pnMessageResult.getChannel());

            JsonElement receivedMessageObject = pnMessageResult.getMessage();
            System.out.println("Received message: " + receivedMessageObject.toString());

            // Extract desired parts of the payload, using Gson
            String msg = pnMessageResult.getMessage().getAsJsonObject().get("msg").getAsString();
            System.out.println("The content of the message is: " + msg);
        });
        // snippet.end

        // snippet.subscribeToChannel
        // Subscribe to the channel to start receiving messages
        subscription.subscribe();
        System.out.println("Subscribed to channel: " + channelName);
        // snippet.end

        // snippet.addDelay
        // Add a delay so the program doesn't exit immediately
        // This gives time to receive published messages
        try {
            System.out.println("Waiting for messages. Program will exit in 60 seconds...");
            Thread.sleep(60000); // 60 seconds
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Clean up before exiting
        pubnub.disconnect();
        System.out.println("Disconnected from PubNub");
        // snippet.end
    }
}
// snippet.end 
```

### Troubleshooting

If you don't see the expected output, here are some common issues and how to fix them:

| Issue | Possible Solutions |
| --- | --- |
| No connection message | Check your internet connection., Verify your publish and subscribe keys are correct., Make sure you're not behind a firewall blocking PubNub's connections. |
| Message not received | Double-check that you're subscribed to the correct channel., Verify that the message was actually sent (check for any error messages)., Make sure you're waiting long enough for the message to be delivered., Ensure your message listener is properly set up. |
| Build errors | Ensure you've added the PubNub dependency correctly., Check that you're using a compatible version of Java (Java 8+)., Make sure all imports are correct., Verify you're using the right package names (v2 classes). |
| Gson deserialization errors | Check that your message structure matches what you're trying to extract., Use try/catch blocks when processing messages to handle potential JSON parsing exceptions. |
| Thread exceptions | Avoid blocking the main thread with long-running operations., Handle InterruptedException properly when using Thread.sleep()., Consider using an executor service for complex applications. |

:::tip More troubleshooting tips
Refer to the [Troubleshooting](https://www.pubnub.com/docs/sdks/java/troubleshooting) section for more information.
:::

## Next steps

Great job! 🎉 You've successfully created your first PubNub Java application. Here are some exciting things you can explore next:

### Advanced features

* Try out [Presence](https://www.pubnub.com/docs/sdks/java/api-reference/presence) to track online/offline status.
* Implement [Message Persistence](https://www.pubnub.com/docs/sdks/java/api-reference/storage-and-playback) to store and retrieve messages.
* Use [Access Manager](https://www.pubnub.com/docs/sdks/java/api-reference/access-manager) to secure your channels.
* Explore [Channel Groups](https://www.pubnub.com/docs/sdks/java/api-reference/channel-groups) to organize your channels.

### Real examples

* Explore our [GitHub repository](https://github.com/pubnub/kotlin) for more code samples.

### More help

* Check out the [SDK reference documentation](https://www.pubnub.com/docs/sdks/java/api-reference/configuration) for detailed API information.
* Visit the [support portal](https://support.pubnub.com/) for additional resources.
* Ask the AI assistant (the looking glass icon at the top of the page) for help.

## Terms in this document

* **Publish Key** - A unique identifier that allows your application to send messages to PubNub channels. It's part of your app's credentials and should be kept secure.
* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.
* **Subscribe Key** - A unique identifier that allows your application to receive messages from PubNub channels. It's part of your app's credentials and should be kept secure.