Java - Assert (Inline code Assertion)

Java Conceptuel Diagram

Java - Assert (Inline code Assertion)

About

The assert keyword in Java is a inline assertion.

Example

// TypeCode or Java Class must be present
assert !(columnMetadata.getColumnTypeCode() == null && columnMetadata.getColumnTypeJava() == null) : "The column (" + columnMetadata.getColumnName() + ") has its type code and java type Null";
java.lang.AssertionError: The column (column1) has its type code and java type Null

	at net.bytle.table.database.Databases.getDataTypeOf(Databases.java:180)
	at net.bytle.table.database.Databases.getCreateTableStatementColumnsDefinition(Databases.java:129)
	at net.bytle.table.database.Databases.getCreateTableStatement(Databases.java:104)
	at net.bytle.table.TableLoader.TableLoader.<init>(TableLoader.java:110)
	at net.bytle.table.TableLoader.TableLoaderSqliteTest.dataLoadTest(TableLoaderSqliteTest.java:52)

Role/Usage

Its first role is to reduce the following code:

if(variable == null) {
    throw new RuntimeException("variable is null");
}

by this:

assert variable != null : "variable is null";

If the assertion fails, you get a java.lang.AssertionError:

java.lang.AssertionError: variable  is null

Syntax

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

Other assertion example

requireNonNull

this.session = java.util.Objects.requireNonNull(session, "session is null");







Share this page:
Follow us:
Task Runner