What is the meaning of this line in Java?

2

I did not understand the following line of code below:

ret += this.elem[i]+(i!=this.ultimo?", ":"");

What is the meaning of these operators i! , ? and :

{
    String ret = "{";

    for (int i=0; i<=this.ultimo; i++)
        ret += this.elem[i]+(i!=this.ultimo?", ":"");

    return ret+"}";
}
    
asked by anonymous 20.09.2016 / 03:33

2 answers

8

The != operator means different, or compares if i is different from this.ultimo . Example:

//i = 5
//j = 4

boolean exemplo = (i == j) //false
boolean exemplo = (j != i) //true

The operator ? is a simplified if, for example this if ..

String exemplo = "";
if (i == 1){
  exemplo = "Igual a 1"
} else{
  exemplo = "Diferente de 1"
}

can be simplified by:

String exemplo = (i == 1 ?   "Igual a 1" :  "Diferente de 1")

In other words, the operator? Tests the comparison, if true returns the value before : , if false, returns later ..

    
20.09.2016 / 03:42
3

The name of this type of conditional is If ternary ( ternary operator )

Simplifying:

? == if

:  == else
  

So if i != this.ultimo , concatene “ , “ , otherwise concatene “:”

    
20.09.2016 / 13:31