

{"id":13239,"date":"2018-04-12T07:14:30","date_gmt":"2018-04-12T07:14:30","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=13239"},"modified":"2026-05-20T11:12:08","modified_gmt":"2026-05-20T05:42:08","slug":"java-assert","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/java-assert\/","title":{"rendered":"Java Assert &#8211; Why We Use Assertion in Java"},"content":{"rendered":"<p>All of us know about if statements. Sometimes when we are programming large applications, it is difficult to write if statements because they take up a lot of space and cause clutter. Hence, it is always best to use assertions, which are the same thing as if statements, but they save a lot of space and provide the same functionality. Let&#8217;s learn about assert in Java.<\/p>\n<h3>Assertions in Java<\/h3>\n<p>As you might be thinking. assertions are just different from those of \u2018if\u2019 statements in Java.<\/p>\n<p>Sometimes we need to raise custom exceptions for ourselves to properly manage the flow of the program.<\/p>\n<p>The user should not face any hindrance because of that. Hence, we use assert statements in Java. Hence, we can say that the predictions which are made by the developer are checked by the assertions.<\/p>\n<p><strong>Syntax of assertions in Java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">assert &lt;expression&gt;\r\n<\/pre>\n<p>or<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">assert &lt;expression1&gt;:&lt;expression2&gt;\r\n<\/pre>\n<p>The second expression is generally the error message that gets thrown after the first expression returns false.<\/p>\n<p>Make sure that the first expression is a Boolean expression.<\/p>\n<p>You also have to enable the asserts in Java because they are disabled by default. This is done to get backwards compatibility in Java.<\/p>\n<p>Assertions got added to Java in version 1.4. Before then, it was perfectly normal to have variable and method names as \u2018assert\u2019.<\/p>\n<p>But after the assert keyword was introduced, a lot of these programs stopped working because they used a reserved keyword as variable names.<\/p>\n<p>To avoid these difficulties, assertions are generally disabled by default in Java.<\/p>\n<p><strong>To enable assertions in Java, you can use:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">java -ea &lt;Compiled Java File&gt;\r\n<\/pre>\n<p>or<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">java -enableassertions &lt;Compiler Java File&gt;\r\n<\/pre>\n<p><strong>You can also disable assertions explicitly by :<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">java -da &lt;Compiled Java File&gt;\r\n<\/pre>\n<p>or<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">java -disableassertions &lt;Compiled Java File&gt;\r\n<\/pre>\n<p>It is often easier to enable\/disable assertions for an entire package rather than doing it for each class.<\/p>\n<p>Up until now, you must know that the flag for enabling assertions is -ea, and the flag for disabling assertions is -da.<\/p>\n<p>In order to enable or disable assertions for packages, we need to understand a few notations.<\/p>\n<ul>\n<li><strong>\u201cnameofPackage\u2026\u201d<\/strong> &#8211; This will allow you to enable or disable packages for the mentioned package and its subpackages.<\/li>\n<li><strong>\u201c&#8230;\u201d<\/strong> &#8211; This will allow you to enable or disable assertions in the current package in the working directory. Use this if your package is unnamed.<\/li>\n<\/ul>\n<p>So, for example, if my current package is com.dataflair.assertions and I want to enable assertions for this entire package and all its subpackages, my command will be:<\/p>\n<p><strong>java -ea com.dataflair ProgramOne<\/strong><\/p>\n<p>where \u201cProgramOne\u201d is the name of the program that I want to execute.<\/p>\n<p>Enough theory, let us get our hands dirty and feet wet!<\/p>\n<p><strong>Java program to illustrate Assertions:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.dataflair.assertionsinjava;\r\npublic class AssertTest\r\n{\r\n    public static void main(String[] args) {\r\n        int a=20;\r\n        assert a&gt;=30:\"Wrong Value\";\r\n        System.out.println(\"This statement will execute only if the value of a is greater than or equal to 30 \");\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">java -ea AssertTest [17:13:10]Exception in thread &#8220;main&#8221; java.lang.AssertionError: Wrong Value<br \/>\nat AssertTest.main(AssertTest.java:5)<\/div>\n<p>As you can see the JVM raises the exception with the custom message I provided.<\/p>\n<p>This is useful for debugging scenarios or when a developer wants to know if a variable is really getting a value at a particular point or a method is getting called without having to print stuff to the machine.<\/p>\n<h3>Advantages of Using Assertions in Java<\/h3>\n<p>There are a ton of advantages of Assertions. Let us look at a few of them:<\/p>\n<ul>\n<li>Checks if a particular block of code is reachable or not.<\/li>\n<li>These can also be useful to check method invocations.<\/li>\n<li>Assertions can check if the control is reaching the beginning of a method.<\/li>\n<li>They can also check the state of an object.<\/li>\n<li>It checks the internal logic of the program.<\/li>\n<li>Assertion catches the error during the process of testing.<\/li>\n<li>Use an assertion where the particular condition is not given, which can raise an error.<\/li>\n<li>It has a faster capacity to track and solve errors.<\/li>\n<\/ul>\n<h3>When should you use Java Assertions?<\/h3>\n<ul>\n<li>If you have a switch case with no default case, then you might want to use assertions. This is because you might think that it is logically impossible for the variable to have any value other than your cases. You can use an assert to check if your logical assumption is correct.<\/li>\n<li>You can also use assert statements to check if the control flow is correct or not. For example, if you have a function that returns a value, you may want to put an assert statement. However, you may get a \u2018non-reachable\u2019 code error. Hence, it is always better to throw a \u2018newAssertionError()\u2019.<\/li>\n<li>You can also use them as arguments of a private method.<\/li>\n<\/ul>\n<h3>When should you not use Java Assertions?<\/h3>\n<ul>\n<li>You should not use assertions the same way you use exceptions. They should not replace error messages.<\/li>\n<li>When the errors are due to the user\u2019s invalid input or due to an error in the program itself, they should be handled by the error handling block and not by assertions.<\/li>\n<li>You should not use assertions on command-line arguments.<\/li>\n<\/ul>\n<h3>Difference between Java Assertions and Exceptions<\/h3>\n<p>The primary difference between assertions and exceptions is that assertions are disabled by default, but exceptions are enabled everywhere.<\/p>\n<p>Another important thing to note is that assertions are generally useful for checking some part of code that should be logically impossible to execute.<\/p>\n<p>For example, the line after a return statement in a function. You can think of these as sanity checks.<\/p>\n<p>However, exceptions are useful for keeping the flow of the program intact when the user supplies invalid input or when there are some invalid operations performed within the program.<\/p>\n<h3>Java Assertion Best Practices<\/h3>\n<p>There are some commonly used rules that are used when Java developers work with assertions.<\/p>\n<p>However, do remember that assertions are disabled by default, so there is no guarantee that your assertion will execute.<\/p>\n<ul>\n<li>You should not use assertions to check for valid parameters. Instead, use exceptions.<\/li>\n<li>You should assert for null values whenever you can.<\/li>\n<li>It is not a good practice to connect the method call directly with the assert method. One workaround is that you can store the return of that method in a local variable. You can use that variable to assert conditions.<\/li>\n<li>It is advisable to use assertions where the program might never reach. When the program performs abnormally, we check it.<\/li>\n<\/ul>\n<h3>Java Error Handling vs. Assertions<\/h3>\n<p>Understanding the distinction between assertions and exceptions is crucial. Assertions are primarily for development and debugging purposes, and they&#8217;re disabled by default. Exceptions, on the other hand, are enabled by default and designed to handle runtime errors gracefully. Use assertions to validate assumptions within your code&#8217;s logic, and rely on exceptions for error handling scenarios like invalid user input or unexpected program issues.<\/p>\n<h3>Summary<\/h3>\n<p>In this article, we got to know about Assertions in Java. We learned how to use it, when to use it, and when not to use it.<\/p>\n<p>Although assert is not a very popular topic, it can help reduce boilerplate code in Java. It also helps decrease the \u2018if-else\u2019 clutter in the code.<\/p>\n<p>Altogether, it is a cool tool to have in a Java developer&#8217;s toolkit.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>All of us know about if statements. Sometimes when we are programming large applications, it is difficult to write if statements because they take up a lot of space and cause clutter. Hence, it&#46;&#46;&#46;<\/p>\n","protected":false},"author":5,"featured_media":85696,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[1182,4138,6183,7386,7387,7388,7389,16102,16105,16192],"class_list":["post-13239","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-assertion-in-java","tag-enabling-and-disabling-assertions-in-java","tag-how-to-enable-assertion-in-java","tag-java-assert-example","tag-java-assert-statement","tag-java-assertion-example","tag-java-assertion-vs-normal-exception-handling","tag-where-not-to-utilize-assertion-in-java","tag-where-to-utilize-assertion-in-java","tag-why-use-java-assertions"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java Assert - Why We Use Assertion in Java - DataFlair<\/title>\n<meta name=\"description\" content=\"Learn What is Assertion in Java, Java assert Statement, Enabling &amp; Disabling Assertions in Java, Java Assertion vs Normal Exception Handling\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/java-assert\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Assert - Why We Use Assertion in Java - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Learn What is Assertion in Java, Java assert Statement, Enabling &amp; Disabling Assertions in Java, Java Assertion vs Normal Exception Handling\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/java-assert\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2018-04-12T07:14:30+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-05-20T05:42:08+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Java-Assert-1.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java Assert - Why We Use Assertion in Java - DataFlair","description":"Learn What is Assertion in Java, Java assert Statement, Enabling & Disabling Assertions in Java, Java Assertion vs Normal Exception Handling","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/java-assert\/","og_locale":"en_US","og_type":"article","og_title":"Java Assert - Why We Use Assertion in Java - DataFlair","og_description":"Learn What is Assertion in Java, Java assert Statement, Enabling & Disabling Assertions in Java, Java Assertion vs Normal Exception Handling","og_url":"https:\/\/data-flair.training\/blogs\/java-assert\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2018-04-12T07:14:30+00:00","article_modified_time":"2026-05-20T05:42:08+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Java-Assert-1.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/java-assert\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/java-assert\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823"},"headline":"Java Assert &#8211; Why We Use Assertion in Java","datePublished":"2018-04-12T07:14:30+00:00","dateModified":"2026-05-20T05:42:08+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-assert\/"},"wordCount":1159,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-assert\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Java-Assert-1.jpg","keywords":["Assertion in Java","Enabling and Disabling Assertions in Java","How to Enable assertion in Java","Java Assert example","Java assert statement","Java Assertion example","Java Assertion vs. Normal Exception Handling","Where not to utilize Assertion in Java","Where to utilize Assertion in Java","Why use Java Assertions"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/java-assert\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/java-assert\/","url":"https:\/\/data-flair.training\/blogs\/java-assert\/","name":"Java Assert - Why We Use Assertion in Java - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-assert\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-assert\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Java-Assert-1.jpg","datePublished":"2018-04-12T07:14:30+00:00","dateModified":"2026-05-20T05:42:08+00:00","description":"Learn What is Assertion in Java, Java assert Statement, Enabling & Disabling Assertions in Java, Java Assertion vs Normal Exception Handling","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/java-assert\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/java-assert\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/java-assert\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Java-Assert-1.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Java-Assert-1.jpg","width":1200,"height":628,"caption":"Java Assert"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/java-assert\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Java Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/java\/"},{"@type":"ListItem","position":3,"name":"Java Assert &#8211; Why We Use Assertion in Java"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam1\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/13239","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=13239"}],"version-history":[{"count":13,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/13239\/revisions"}],"predecessor-version":[{"id":148392,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/13239\/revisions\/148392"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/85696"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=13239"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=13239"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=13239"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}