O operador ternário
é um modo de fazer um teste condicional simples substituído o if. Exemplo:
int meuInt = 2;
int meuIntB = 3;
int meuIntC = 4;
meuInt = meuIntB>meuIntC ? meuIntB : meuIntC;
A expressão que
fica ao lado esquerdo do ? é avaliada (meuIntB>meuIntC), se meuIntB maior que meuIntC então meuInt = meuIntB
senão meuInt é igual meuIntC, está operação poderia ser substituída por:
if (meuIntB>meuIntC){
meuInt = meuIntB;
}else {
meuInt = meuIntC;
}
Vamos à prática:
class OperadorTernario{
public
static void main(String args[]){
int
meuInt = 2;
int
meuIntB = 3;
int
meuIntC = 4;
meuInt
= meuIntB>meuIntC ? meuIntB : meuIntC;
System.out.println("meuInt
= " + meuInt);
String
retorno;
int
meuPrimeiro = 20;
int
meuSegundo = 23;
retorno
= (meuPrimeiro % 2 == 0) ? "Par" : "Impar";
System.out.println("meuPrimeiro
e " + retorno);
retorno
= (meuSegundo % 2 == 0) ? "Par" : "Impar"; System.out.println("meuSegundo
e " + retorno);
}
}
Até o próximo post.
Muito legal, pois vim do php que também tem o operador ternário.
ResponderExcluir