frazman
frazman

Reputation: 33213

assert not working the way i thought in java

I am new to java.. so maybe thats why I am not getting the keyword right?

So.. I wrote a quick class from that bank customer example.. and one of the method is withdraw.

public void withdraw(double d){
        double diff = balance - d;
        assert (diff>=0 ) :" Insufficient funds!";
        balance = diff;
    }

So what I was intending was if the withdraw abount is greater than the balance.. then throw up an error... (which i think should be more like an exception .... but lets say i want to check this by assertion)...

But it doesnt do anything.. even though when diff is less than zero..

the code compiles fine.. whereas I was expecting it to throw up an error.

What am i doing wrong

Upvotes: 0

Views: 1908

Answers (2)

HackerMonkey
HackerMonkey

Reputation: 473

Assertions are not enabled by default, you need to explicitly enable them when you run your java application, e.g.

java -ea SomeClass

Upvotes: 5

Nathan Ryan
Nathan Ryan

Reputation: 13041

Assertions are disabled by default. You can enable all assertions by passing the -enableassertions flag when invoking the JVM.

[Edit]

You can find the Java Programming with Assertions guide here. Note the bit on enabling and disabling assertions.

Upvotes: 7

Related Questions