Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
Often times, the need to verify the conditions present in our program arises. The assert keyword in Java allows the users to verify or test the assumptions made during the program. This article will introduce you to Assertion In Java.
Following pointers will be covered in this article,
So let us get started with this article
The assert statement is used alongside a Boolean expression and can be declared as follows:
assert expression;
Another way to declare the assertion is as follows:
assert expression1 : expression2;
Example
import java.util.Scanner; public class Test { public static void main( String args[] ) { int value = 18; assert value >= 20 : " Eligible"; System.out.println("Value: "+value); } }
Output
Value: 18
The output after enabling assertions will be as follows:
Exception in thread “main” java.lang.AssertionError: Eligible
Moving on with this Assertion In Java Article,
It must be noted that, assertions are disabled by default.
The syntax for enabling the assertion statement is as follows:
java –ea Test
Another method for enabling assertions:
java –enableassertions Test
Moving on, let us see how to disable assertions,
The assertion statements can be disabled as follows:
java –da Test
Another method for enabling assertions:
java -disableassertions Test
Reasons For Using Assertions
There are various reasons as to why a user might want to use assertions:
Moving on with this Assertion In Java Article
Moving on to the final bit of this Assertion In Java Article
import java.util.Scanner; public class Test { public static void main( String args[] ) { Scanner scanner = new Scanner( System.in ); System.out.print("Enter the ID "); int value = scanner.nextInt(); assert value>=15:" Invalid"; System.out.println("Value "+value); } }
Output
Enter the ID
Exception in thread “main” java.lang.AssertionError: Invalid
To make sure that the assumptions made during the program are correct, assertions prove to be an important keyword.
Thus we have come to an end of this article on ‘Assertion In Java in Java’. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.
Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.
Course Name | Date | Details |
---|---|---|
Java Course Online | Class Starts on 1st March,2025 1st March SAT&SUN (Weekend Batch) | View Details |
edureka.co