0

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

2
  • 2
    If the pre-condition for the method is: "any withdraw amount" then your use of assertion is not correct. It is correct if pre-condition is "<= balance" Commented Dec 25, 2012 at 0:23
  • You might also want to ensure that a negative amount or NaN is not withdrawn. Commented Dec 25, 2012 at 12:09

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

When you run the java command, add -enableassertions immediately after the java bit
Is there a way to configure eclipse?
@Fraz In eclipse: Run -> Run Configurations -> Arguments (tab) -> VM arguments -> type -ea or -enableassertions
You can also easily add to all JUnit tests by going to Java > JUnit in your Eclipse preferences and checking the "add -ea to VM arguments"
5

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

java -ea SomeClass 

2 Comments

@Hansanein.. I am using eclipse.. how do i enable it in eclipse?
from within eclipse, right click the class you want to run then choose run as > run configurations > arguments tab then inside the JVM options enter -ea

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.