assert keyword(added in J2SE 1.4)

An assertion has a Boolean expression that, if evaluated as false, indicates a bug in the code. This mechanism provides a way to detect when a program starts falling into an inconsistent state. Assertions are excellent for documenting assumptions and invariants about a class. Here is a simple example of assertion:

BankAccount acct = null;
// ...
// Get a BankAccount object
// ...
// Check to ensure we have one
assert acct != null;

This asserts that acct is not null. If acct is null, an AssertionError is thrown. Any line that executes after the assert statement can safely assume that acct is not null.
Using assertions helps developers write code that is more correct, more readable, and easier to maintain. Thus, assertions improve the odds that the behavior of a class matches the expectations of its clients.

Assert describes a predicate (a true–false statement) placed in a java-program to indicate that the developer thinks that the predicate is always true at that place. If an assertion evaluates to false at run-time, an assertion failure results, which typically causes execution to abort. Optionally enable by ClassLoader method.the Java runtime system throws an AssertionError.

Note:Assertions may be declared using the following syntax:

➯ assert expression1 [: expression2];

expression1 is a boolean that will throw the assertion if it is false. When it is thrown, the assertion error exception is created with the parameter expression2 (if applicable).

Simple Example of Java assert Keywords:


	import java.util.Scanner;

public class MainClass
{
    public static void main(String[] args) 
    {
        System.out.println("Enter your Age");
         
        Scanner in = new Scanner(System.in);
         
       int Age  = in.nextInt();
         
        assert Age > 35 : "Yes";
        System.out.println("your Current Age is:"+Age);
		 
    }
}
	

Assertions are usually used as a debugging aid. They should not be used instead of validating arguments to public methods, or in place of a more precise runtime error exception.

Simple Java assertion Program


import java.util.Random;

public final class assertkywd {

  public static void main(String args[]) {
    final assertkywd asrt = new assertkywd("Tultip", 1);
    asrt.grow();
    asrt.grow();
    System.out.println(asrt);

    asrt.randomGrowOrWither();
    System.out.println(asrt);

    asrt.wither();
    asrt.wither();
    System.out.println(asrt);
  }

  
  public assertkywd(final String aexpression, final int aInitialLength) {
    
    if (!isValidexpression(aexpression)) {
      throw new IllegalArgumentException("expression must have content.");
    }
    if (!isValidLength(aInitialLength)) {
      throw new IllegalArgumentException("Initial length must be positive.");
    }

    fexpression = aexpression;
    fLength = aInitialLength;

    
    assert hasValidState(): "Construction failed - not valid state.";
  }

  public boolean isMature() {
    return fLength > 5 ;
 
  }

   
  public void grow(){
     
    final int oldLength = fLength;
    fLength += getLengthIncrease(fLength);
 
    assert fLength > oldLength;
 
    assert hasValidState(): this;
  }

   
  public void wither(){

    
    class OriginalState {
      OriginalState() {
        fOriginalLength = fLength;
      }
      int getLength() {
        return fOriginalLength;
      }
      private final int fOriginalLength;
    }
    OriginalState originalState = null;
     
    assert (originalState = new OriginalState()) != null;

    if (fLength > 1) {
      --fLength;
    }

   
    assert fLength <= originalState.getLength();

    //check the class invariant
    assert hasValidState(): this;
  }

   
  public void randomGrowOrWither() {
     
    Random generator = new Random();
    int action = generator.nextInt(3);
     
    if (action == 0) {
       
    }
    else if (action == 1) {
      grow();
    }
    else if (action == 2) {
      wither();
    }
    else {
      
      throw new AssertionError("Unexpected value for action: " + action);
    }
    
    assert hasValidState(): this;
  }

   
  public String toString(){
    final StringBuilder result = new StringBuilder();
    result.append(this.getClass().getName());
    result.append(": expression=");
    result.append(fexpression);
    result.append(" Length=");
    result.append(fLength);
    return result.toString();
  }

   
  private final String fexpression;
  private int fLength;
 
  private boolean hasValidState(){
    return isValidexpression(fexpression) && isValidLength(fLength);
  }

 
  private boolean isValidexpression(final String aexpression) {
    return aexpression != null && aexpression.trim().length()>0;
  }

   
  private boolean isValidLength(final int aLength) {
    return aLength > 0;
  }

  
  private int getLengthIncrease(int aOriginalLength) {
    
    assert aOriginalLength > 0: this;
    int result = 0;
    if (aOriginalLength > 10) {
      result = 2;
    }
    else {
      result = 1;
    }
    assert result > 0 : result;
    return result;
  }
}
 
 

Download Source code 'assert keyword Java Program'

Output here in cmd Window

References By: oracle wikipedia

« Privious Post » share on :        :  

Love to hear your Views / Guidance / Recommendations on this Post…

Explore the Technology World

Computer Programming Terminologies Computer Programming Terminology is a general word for the group of specialized words or meanings relating to Computer Programming, and also the study of such t ...Read MoreNew features in JDK 12 with IntelliJ IDEADeveloped by JetBrains (formerly known as IntelliJ) ,IntelliJ IDEA is a Java integrated development environment (IDE) for developing computer software. It is av ...Read MoreGoogle Pay API Implementation Demo for AndroidIn this youtube Channel by Android Developers ,Learn how to implement the Google Pay API for Android with just a few lines of code and how it works with your ex ...Read MoreUnit Testing in .NET Core and Azure Devops pipelineUnit testing is a software testing method by which individual units of source code, usage procedures,sets of one or more computer program modules together with ...Read MoreThe mind behind Linux & GIT : Linus TorvaldsLinus Torvalds transformed technology twice — first with the Linux kernel, which helps power the Internet, and again with Git, the source code management ...Read MoreTensorflow and deep learningWith Tensorflow ,deep machine learning transitions from an area of research into mainstream software engineering. ...Read MoreJava program to return all possible permutations from collection of distinct numbersexample of Java program to return all possible permutations from collection of distinct numbers ...Read MoreReal Time Analytics with Spring Application Development FrameworkSpring is the most popular application development framework for enterprise Java.Millions of developers use Spring to build simple, truly portable, fast and fle ...Read MorePath Setting in Java When an application is launched from command prompt Windows OS searches for the executable program in the current working directory. The prompt throws an error ...Read MoreFacebook | whatsapp|Github | Twitter | LinkedIn | Youtube| reddit About | Cookies-Policy | Disclaimer | Site Map | Contact

Call / Visit for New Batch

Services

Why Join Us

  • ➯ Free Demo Classes
  • ➯ No Registration Fee
  • ➯ Interview Questions
  • ➯ Study Materials
  • ➯ Softwares
  • ➯ Aptitude & Reasoning
  • ➯ Placement Assitance

Address

  • MyJava Training Institute ,
  • Plot No.243 , shop No 14 ,
  • Secnd Floor , Zone-II ,
  • M.P.Nagar , Bhopal,
  • Madhya Pradesh ( 462011 )
  • ☎  08871209400 , 7987028543
  • 🌐 www.myjava.in
FacebookGoogle +TwitterYouTube

MyJava - java Training Institute