What is the meaning of this line in Java?

Asked

Viewed 1,439 times

2

I did not understand the following line of the code below:

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

What are 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+"}";
}
  • 1

    It is not i! And yes != , There in front I think q is not an operator but rather the name of the object q was created with a ? , And the : are cocatenated the information

  • "i!" is not an operator, "i" is a variable (which was defined within the "for"), "!=" is the logical operator "different from"; and "?:" is the ternary operator, is basically a simplified "if" before the "?" is a logical test, if true returns the value before ":", if false, returns the value after the ":".

2 answers

8


The operator != means different, or compares if the 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")

Ie the operator ? Tests the comparison, if true returns the value before the :, if false, returns later..

3

The name of this type of parole is If ternary ( Ernary Operator )

Simplifying :

? == if

:  == else

( ( i != this.ultimo) ? ", " : "");

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.