user1050619
user1050619

Reputation: 20856

Java assertion error does not throw error

Why doesn't my assert statement yield any result? I think the first assert statement should fail, but I don't see anything being displayed on Eclipse.

I'm using Eclipse to run this program.

package java.first;

public class test {
  public static void main(String[] args) throws Exception {
    String s = "test1";
    assert (s == "test");
    s = "test";
    assert (s == "test");
  }
} 

Upvotes: 15

Views: 10695

Answers (5)

arshajii
arshajii

Reputation: 129497

You have to enable assertions with the -ea argument (short for -enableassertions).

In Eclipse:

  • Right-click on the project, then "Run As""Run Configurations..."
  • Select the "Arguments" tab
  • Put -ea in the "VM arguments" field.
  • Select "Apply"

Now, running should cause an AssertionError.

Upvotes: 13

Tim Perry
Tim Perry

Reputation: 3096

You need to turn assertion checking on at runtime. The Oracle documentation for Java states:

To enable assertions at various granularities, use the -enableassertions, or -ea, switch. To disable assertions at various granularities, use the -disableassertions, or -da, switch.

Full details on the Oracle website at http://docs.oracle.com/javase/1.4.2/docs/guide/lang/assert.html#enable-disable

To change the run-time options for programs run inside Eclipse you will need to modify the parameters Eclipse runs your program with. How to do this will vary depending on your version of Eclipse, but here's how it works in Eclipse Europa...

  • Open the Run Dialog (this should be an option under the "Run" menu).
  • Click on the tab, "(x)= Arguments."
  • In the field for "VM arguments," enter -ea to enable assertions.
  • Click on the "Apply" button.

Answer "borrowed" from http://www.coderanch.com/t/416987/vc/enable-Assertions-eclipse

Upvotes: 4

Saj
Saj

Reputation: 18702

You have to enable it by using -ea argument.

Upvotes: 1

rgettman
rgettman

Reputation: 178253

By default, Java disables assertions. They must be enabled for them to work, with the -ea option when running your program.

Upvotes: 5

Dave Newton
Dave Newton

Reputation: 160181

You need to set the -ea (Enable Assertions) in your JVM options.


Unrelated, but you almost always want string1.equals(string2) rather than ==.

Upvotes: 30

Related Questions