Simon
Simon

Reputation: 9365

Java: Question on assert-behaviour

I have this code snippet

import java.util.ArrayList;
import java.util.List;

public class AssertTest {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        assert(list.add("test")); //<-- adds an element

        System.out.println(list.size());
    }
}

Output:

0 

Why is the output list empty? How does assert behave here? Thank you in advance!

Upvotes: 0

Views: 808

Answers (6)

developer
developer

Reputation: 9488

assert method that checks whether a Boolean expression is true or false. If the expression evaluates to true, then there is no effect. But if it evaluates to false, the assert method prints the stack trace and the program aborts. In this sample implementation, a second argument for a string is used so that the cause of error can be printed.

Upvotes: 0

Gursel Koca
Gursel Koca

Reputation: 21300

You should enable assertion with -ea flag... such as;

java -ea -cp . AssertTest

Also using assertion is worst place for side effects..

Upvotes: 5

Ralph L&#246;we
Ralph L&#246;we

Reputation: 424

Assertions needs to be enabled. Enable them using the -ea switch.

See the Java application launcher docs.

Upvotes: 0

pauljwilliams
pauljwilliams

Reputation: 19225

Incidental to your question - assertions should not contain code that is needed for the correct operation of your program, since this causes that correct operation to be dependent on whether assertions are enabled or not.

Upvotes: 0

Erik
Erik

Reputation: 91330

Never assert on anything with side effects. When you run without asserts enabled (enabled with -ea), list.add("test") will not be executed.

It's a good habit to never assert anything but false, as follows:

if (!list.add("test")) {
  assert false;
  // Handle the problem
}

Upvotes: 5

GuruKulki
GuruKulki

Reputation: 26428

you have to enable assert. ie run as java -ea AssertTest

Upvotes: 0

Related Questions