Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Assertion in java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 236
    Comment on it

    Assertion:

    Assertion is a statement used to test assumptions of the programmer about the program. While, executing assertion it is always true but in case , it fails, JVM will throw an error named AssertionError. Assertion is mainly used for testing purpose.

    Implementation of assertion:

    To implement assertion, "assert" keyword is used.

           Syntax: assert booleanExpression;
    

    Advantages of Assertion:

    1. Data validation.
    2. It helps to detect bug early in development cycle which is very cost effective
    3. It will help you to be better programmer and improve code quality.
    4. You can create new code and use assertion to compare output with old method.

    There are some situations where assertion should be avoid to use. They are:

    1. Assertion create a runtime exception while we check arguments in public methods e.g. IllegalArgumentException, NullPointerException etc.

    2. Do not use assertion, if you don't want any error in any situation.

        import java.util.Scanner;  
      
      
        class AssertionExample{  
        public static void main( String args[] ){  
      
      
         Scanner scanner = new Scanner( System.in );  
          System.out.print("Enter ur age ");  
           int value = scanner.nextInt();  
           assert value>=20:" Not valid";  
            System.out.println("value is "+value);  
                   }   
             }  
      

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: