Vijayakumar Chava
Vijayakumar Chava

Reputation: 69

Converted if statement to ternary operator - compiler complains that it is not a statement

package com.myname.zed;

import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;


public class MyTest
{

    AtomicInteger counter = new AtomicInteger(100);

    @Test
    public void testAtomic()
    {
        for (int i = 1; i < 610; i++) {
            if (counter.compareAndExchange(100, 0) == 100) {
                System.out.println("trace");
            }
            else {
                counter.getAndIncrement();
            }
        }
    }

/* converted if to ternary, it is not compiling now */

    @Test
    public void testAtomic1()
    {
        for (int i = 1; i < 610; i++) {
            counter.compareAndExchange(100, 0) == 100 ? System.out.println("trace") : counter.getAndIncrement();
        }

    }

}

I need to print a log line only once out of 100 times. It works as expected when I write using if statement. I converted "if" to ternary, compiler complains it is not a statement.

Am I missing something really simple thing here? And is there any other efficient way of writing this logic.

And I ended up doing similar to this to log trace once every 100th time(may not be very accurate, but it is fine with my needs):

    final private ThreadLocalRandom random = ThreadLocalRandom.current();
@Test
public void testTLR()
{
    if (50 == random.nextInt(100)) {
        System.out.println("trace");
    }
    else {
        System.out.println("no trace: ");
    }
}

Upvotes: 0

Views: 43

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 102872

The error message is on point; you need a statement there, and the ternary expression isn't one. Most things in java are either a statement or an expression; a select few things are both: method invocations (including 'weird' ones such as constructor invocations), assignments (a = 5, as well as a += 5), and unary operators such as a++).

I'm not sure what you mean by 'efficient'. An if statement as is fast, performance wise, as a ternary operator would be.

If you mean shorter, you don't need the braces:

if (counter.compareAndExchange(100, 0) == 100) System.out.println("trace"); else counter.getAndIncrement(); – that all fits on one line, but whether that fits your style preferences is your decision.

There is no magic 'allow me to treat any and all expressions as statements' option in java.

Upvotes: 2

Related Questions