Search code examples
javastringassert

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


Solution

  • 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.