How to get all online players

I want to get all online players (/player’s names). I used this code:
for (Player onlinePlayer : sender.getServer().getOnlinePlayers()) {
String onlinePlayerName = onlinePlayer.getDisplayName();
if (onlinePlayerName == playerToName) {
playerToExists = true;
}
}
The code is basically supposed to check if the player in a command, for example:
/command player dosomething
Actually exists and is online. Sadly this isn’t quite working. Anyone know, what the problem is?

1 Like

In Java, == tests for reference equality (same object), which will never be the same for two strings. Instead, for strings, you should use .equals, which checks if the value is the same. To compare the player names, you’d want to change your if statement to:

if (onlinePlayerName.equals(playerToName) {

By the way, you might want to use Player#getName instead of Player#getDisplayName if you want to compare only the in-game name of the player.

For reference:

1 Like

Thanks for this info. I wasn’t aware of it.
The plugin does now work.

Btw: I am getting one of the two playernames from a command input. Can I still use player.getDisplayName or should I use player.getName?

Player#getDisplayName returns a “friendly” display name, which may include color codes or other changes made by plugins. Player#getName returns the player’s name, without any possible modifications. If you’re using the player name as a command argument, e.g. /fly NoahvdAa, you’ll probably want to use it.

1 Like

Ok thanks for the help!

If you just want to check if a player specified in a command like /command player is online just use:

final Player target = Bukkit.getPlayer(args[0]);

if(target == null || !target.isOnline()){

// whatever / target is not online

return false;
}

And you can get a collection of online players by using Bukkit.getOnlinePlayers()