Defining new variable

Viewed 98

I'm quite new at programming in Java and I've encountered something I don't really understand:

if (Object.getSomething() != null) {
        Long Size= null != Object.getSomething().getSomething2()
            ? Object.Something().getSomething2() : null;

I've been looking for the answer but I can't understand this way of defining a new variable, I mean, the '?' and the ': null' are the things I can't understand.

5 Answers

Ternary conditionals take the following form:

condition ? value_if_true : value_if_false

Consider for instance the mathematical max function. Using regular conditional statements we could write:

int max = 0;
if (a > b) {
  max = a;
} else {
  max = b;
}

We can do the exact same thing using a ternary condition: max = a > b ? a: b;

This is a ternary operator in java. syntax is

result = testCondition ? value1 : value2

i.e if testcondition is true, put value1 in result, else put value2 in result.

if (Object.getSomething() != null)
    Long Size= null != Object.getSomething().getSomething2()
        ? Object.Something().getSomething2() : null;

This line is equivalent to the following :

if (Object.getSomething() != null)
    Long Size = null;
    if (null != Object.getSomething().getSomething2())
        Size = Object.Something().getSomething2();

See this about ternary operator.

Let's take a simple ternary operation:

Object object;
int i = object == null ? 1 : 2;

In Java code, it is the same as writing the standard if-else statement

Object object;
int i;

if (object == null) {
    i = 1;
} else {
    i = 2;
}

As you can see, the amount of lines it takes the traditional approach is much more. This is one of the main strengths of ternary operator.

In natural language, ternary operations read as: "Is object equals to null? Then 1 otherwise 2".

You are trying to use ternary operator here. Here is simplified version to assign the value to Size:

Long Size= null != object.getSomething() ? 10L : null;

If null != object.getSomething() is true then 10L will be assigned else null will be assigned.

Related