Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert the String has certain length (Java)

Is there any way to assert in a method that input String has certain length?

I tried assert stringName[4]; but seems like it doesn't work

like image 907
Miervatea Avatar asked Oct 26 '25 17:10

Miervatea


1 Answers

If you just want to use the Java's assert keyword and not any library like JUnit, then you can probably use:

String myStr = "hello";
assert myStr.length() == 5 : "String length is incorrect";

From the official docs:

The assertion statement has two forms. The first, simpler form is:

assert Expression1;

where Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message.

The second form of the assertion statement is:

assert Expression1 : Expression2 ;

where: Expression1 is a boolean expression. Expression2 is an expression that has a value. (It cannot be an invocation of a method that is declared void.)

You can use the following if you're using a testing library like JUnit:

String myStr = "hello";
assertEquals(5, myStr.length());

Update: As correctly pointed out in the comments by AxelH, after compilation, you run the first solution as java -ea AssertionTest. The -ea flag enables assertions.

like image 139
ayushgp Avatar answered Oct 29 '25 05:10

ayushgp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!