hacer98
hacer98

Reputation: 23

Java : incompatible types; int cannot be converted to string

Im just trying to send an integer from my server to my client via sockets.

public static DataOutputStream toClient = null;
public static int clients = 0;

public static void main(String args[]) throws IOException {

        ServerSocket serverSocket = new ServerSocket(1039);
        System.out.println("Server is running..");

        while (true) {
            Socket connsock = null;
            try {
                // accepting client socket
                connsock = serverSocket.accept();

                toClient = new DataOutputStream(connsock.getOutputStream());
                
                System.out.println("A new client is connected : " + connsock);

                clients = clients + 1;
                toClient.writeUTF(clients); //here, I get the incompatible types; int cannot be converted to string
            }
        }
    }
}

I get:

incompatible types; int cannot be converted to string

on the line with toClient.writeUTF(clients);.

what is wrong?

Upvotes: 2

Views: 2298

Answers (4)

Shubham Pathak
Shubham Pathak

Reputation: 155

The writeUTF method takes string arguments but your clients variable in your code is an integer type.

Here's the signature:

public final void writeUTF(String str) throws IOException {
    writeUTF(str, this);
}

Upvotes: 0

Glains
Glains

Reputation: 2863

The method writeUTF of DataOutputStream is expecting a String while you provided an int.

When you want to send an int, I would consider the following two options:

  • continue to use writeUTF(), but then you have to convert clients to an int using String.valueOf(clients).
  • use writeInt instead to send a plain int instead of a String.

Summary:

// convert to String
toClient.writeUTF(String.valueOf(clients));
// send a single plain int value
toClient.writeInt(clients);

Upvotes: 3

Saiful Islam
Saiful Islam

Reputation: 141

toClient.writeUTF(clients);

Here writeUTF(String str) takes string type parameter so you have to change clients integer to string type.

Upvotes: 0

sharad
sharad

Reputation: 56

That is because writeUTF in DataOutputStream doesnt have an overloaded method which accepts int. So you will need to convert your int to String : Integer.toString(i)

Upvotes: 1

Related Questions