Assert in Java
Assert is a reserved keyword not a method. It checks if the condition after it is true the application continues successfully otherwise vice versa.This program shows how to use Assert in Java.
Assert.java
import javax.swing.JOptionPane; public class Assert { public static void main(String args[]){ //Get input String numeric = JOptionPane.showInputDialog("Enter a numeric value: "); //Check if the input is correct? assert checkInput(numeric); //assert true allows application to continue successfully and assert false throws an exception. System.out.println("You did pass a numeric value"); } private static boolean checkInput(String numeric) { try { Integer.parseInt(numeric); return true; } catch (Exception e) { return false; } } }
Note: You must add '-ea' argument in the command before running it to enable assert, otherwise assert won't work.
No comments:
Post a Comment