-3

I've been trying to Google it, but googling the key "?" doesn't really work out that good. I really want to know what it does and when to use it.

Thanks!

I've seen it a couple times, but here is an example of one I just saw

String name = perms.calculateRank().getColor() + player.getName();
//This is a custom ranking system ^
player.setPlayerListName(name.length() > 15 ? name.substring(0, 16) : name);
player.setDisplayName(name + ChatColor.RESET);
Chat.sendMessage(player, "Tab Name Set");
Beta Nyan
  • 25
  • 2
  • 7
    Posting the code that uses the symbol would help identify its meaning. – M A Oct 23 '14 at 19:17
  • ? = ????? "Whats your question?" – Thalaivar Oct 23 '14 at 19:19
  • 1
    I googled for "question mark operator java"---and guess what I found. – Marko Topolnik Oct 23 '14 at 19:23
  • @MarkoTopolnik OK, but if you're suggesting that the questioner should have just found their answer with Google--nothing in their question indicated that they knew it was called an "operator", and there are probably plenty of people out there who don't know that `?` is a "question mark". – ajb Oct 23 '14 at 19:30
  • @ajb If that's true, then I managed to teach OP three new things with four words :) – Marko Topolnik Oct 23 '14 at 19:50

4 Answers4

8

This is a ternary operator. In Java specifically, it is called the Conditional Operator. It is a way of writing short-hand simple if..else statements. For example:

if (a == b) {
   c = 123;
} else {
   c = 456;
}

is the same as:

c = a == b ? 123 : 456;
Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
7

It is also used for a wildcard generic.

public List<?> getBizarreList();
Jazzwave06
  • 1,883
  • 1
  • 11
  • 19
1

The ternary operator someBoolean ? x : y evaluates to x if someBoolean is true, and y otherwise.

mattm
  • 5,851
  • 11
  • 47
  • 77
1

It is called ternary operator and it is only operator that takes 3 operands. In better sense, it is conditional operator that represent shorter format

General Syntax :

boolean expression ? value1 : value2

your example:

 player.setPlayerListName(name.length() > 15 ? name.substring(0, 16) : name);

as same as

  if( name.length() > 15)
    player.setPlayerListName(name.substring(0, 16));
  else
    player.setPlayerListName(name);
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58