Programming in Java Assertion.

Slides:



Advertisements
Similar presentations
11-Jun-14 The assert statement. 2 About the assert statement The purpose of the assert statement is to give you a way to catch program errors early The.
Advertisements

1. Define the concept of assertions. 1 Explain the use of assertions. 2 Create Java program using assertions. 3 Run Java program using assertions. 4 2.
Detecting Bugs Using Assertions Ben Scribner. Defining the Problem  Bugs exist  Unexpected errors happen Hardware failures Loss of data Data may exist.
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 8 Exceptions and Assertions.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 13 Exception.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
8-May-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
The Java Assert Statement. 2 Assert A Java statement in JDK 1.4 & newer Intent: enables code to test assumptions. E.g., a method that calculates a particle’s.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
16-Jun-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Lecture 11. Today’s topic Conditional statement –Relational operators –if statement –if-else statement –If-elseif statement.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
1 Chapter 18 Exception Handling. 2 Motivations F Program runs into a runtime error –program terminates abnormally F How can you handle the runtime error.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Assertions Program correctness. Assertions Java statement – enables you to assert an assumption about your program. – An assertion contains a Boolean.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Exception Handling.
DAT602 Database Application Development Lecture 5 JAVA Review.
The Java Programming Language
1 Assertions. 2 assertions communicate assumptions about the state of the program, and stop processing if they turn out to be false very often comments.
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 15 Exceptions and.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Methods F Hello World! F Java program compilation F Introducing Methods F Declaring Methods F Calling Methods F Passing Parameters by value F Overloading.
A Survey on Java Modeling Languages Gergely Kovásznai,Eszterházy Károly College Wolfgang Schreiner,Johannes Kepler University Gábor Kusper,Eszterházy Károly.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Programming with Assertions © Allan C. Milne v
Pre- and postconditions, Using assertions and exceptions 1 Pre- and postconditions Using assertions and exceptions.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
David Streader Computer Science Victoria University of Wellington Copyright: David Streader, Victoria University of Wellington Debugging COMP T1.
Exceptions and Assertions Chapter 15 – CSCI 1302.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
The Java Assertion. 2 Assertion A Java statement in JDK 1.4 & newer Intent: enables code to test assumptions. E.g., a method that calculates the a particle’s.
1 Chapter 15 Exceptions and Assertions. 2 Objectives F To know what is exception and what is exception handling (§15.2). F To distinguish exception types:
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 15 Exceptions and Assertions Nothing is impossible.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
Chapter 5 : Methods Part 2. Returning a Value from a Method  Data can be passed into a method by way of the parameter variables. Data may also be returned.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Defensive Programming. Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
Winter 2006CISC121 - Prof. McLeod1 Stuff Midterm exam in JEF234 on March 9th from 7- 9pm.
Chapter 13 Exception Handling
Logger, Assert and Invariants
Exception Handling in Java Reference: COS240 Syllabus
SELECTION STATEMENTS (1)
Chapter 7 Exceptions and Assertions
Testing Recap Testing can find problems, but cannot prove your program works Since exhaustive testing is impossible, select test cases with maximum likelihood.
null, true, and false are also reserved.
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
Chapter 11 Exception Handling and Text I/O
Unit 3 Test: Friday.
PROGRAM FLOWCHART Selection Statements.
Additional control structures
CS-1020 and Exception Handling
Computer Science 340 Software Design & Testing
Corresponds with Chapter 5
Defensive Programming
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

Programming in Java Assertion

Contents Introduction Assertion Using Assertion How assertion works Benefit of using Assertion Important Points www.lpuians.com

Introduction An assertion is a statement in Java that enables you to test your assumptions about the program. Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw a runtime error (java.lang.AssertionError). www.lpuians.com

Example For example, if we write a method that calculates the interest of any account, we might assert that the roi or amount is positive. double calculateInterest(int amt, double roi, int years) { //Using assertion assert amt>0; double interest = (amt*roi*years)/100; return interest; } www.lpuians.com

Assertion assert Expression1; assert Expression1 : Expression2; The assertion statement has two forms. assert Expression1; Here, Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message. assert Expression1 : Expression2; Here, Expression1 is a boolean expression and Expression2 is an expression that has a value and it cannot be an invocation of a method that is declared void. www.lpuians.com

Example assert num >20 : “Number is greater than 20”; public class AssertionExample {     public static void main(String[] rk) {         // get a number in the first argument         int num = Integer.parseInt(rk[0]);           assert num <= 10; // stops if number > 10 assert num >20 : “Number is greater than 20”;          System.out.println("Pass");     } } www.lpuians.com

Using Assertion Assertion will not work directly because assertion is disabled by default. To enable the assertion, -ea or -enableassertions switch of java must be used. Compile: javac AssertionExample.java Run: java -ea AssertionExample www.lpuians.com

How Assertion Works? In assertion a BooleanExpression is used and if boolean expression is false then java throws AssertionError and the program terminates. Second form of assert keyword "assert booleanExpression : errorMessage" is more useful and provides a mechanism to pass additional data when Java assertion fails and java throws AssertionError. www.lpuians.com

Need of Assertion void remainder(int i) class AssertionNeed{ public static void main(String [] rk) { new AssertionNeed().remainder(8); } void remainder(int i) { if(i%3==0) System.out.println("Divisible by 3"); else if(i%3==1) System.out.println("Remainder 1"); else{ System.out.println("Remainder 2"); } } www.lpuians.com

What About it? class AssertionNeedTest { public static void main(String [] rk) new AssertionNeed().remainder(-7); } www.lpuians.com

Need of Assertion void remainder(int i) class AssertionNeed{ public static void main(String [] rk) { new AssertionNeed().remainder(-7); } void remainder(int i) { if(i%3==0) System.out.println("Divisible by 3"); else if(i%3==1) System.out.println("Remainder 1"); else{ // assert i%3 == 2 : i; System.out.println("Remainder 2"); } } www.lpuians.com

Why Assertion? Using assertion helps to detect bug early in development cycle which is very cost effective. Assertion in Java makes debugging easier as AssertionError is a best kind of error while debugging because its clearly tell source and reason of error. Assertion is great for data validation if by any chance your function is getting incorrect data your program will fail with AssertionError. www.lpuians.com

Important Assertion is introduced in JDK 1.4 and implemented using assert keyword in java. Assertion can be enabled at run time by using switch –ea or – enableassertion Assertion does not replace Exception but compliments it. Do not use assertion to validate arguments or parameters of public method. www.lpuians.com

Programming in Java Assertion

Contents Introduction Assertion Using Assertion How assertion works Benefit of using Assertion Important Points www.lpuians.com

Introduction An assertion is a statement in Java that enables you to test your assumptions about the program. Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw a runtime error (java.lang.AssertionError). www.lpuians.com

Example For example, if we write a method that calculates the interest of any account, we might assert that the roi or amount is positive. double calculateInterest(int amt, double roi, int years) { //Using assertion assert amt>0; double interest = (amt*roi*years)/100; return interest; } www.lpuians.com

Assertion assert Expression1; assert Expression1 : Expression2; The assertion statement has two forms. assert Expression1; Here, Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message. assert Expression1 : Expression2; Here, Expression1 is a boolean expression and Expression2 is an expression that has a value and it cannot be an invocation of a method that is declared void. www.lpuians.com

Example assert num >20 : “Number is greater than 20”; public class AssertionExample {     public static void main(String[] rk) {         // get a number in the first argument         int num = Integer.parseInt(rk[0]);           assert num <= 10; // stops if number > 10 assert num >20 : “Number is greater than 20”;          System.out.println("Pass");     } } www.lpuians.com

Using Assertion Assertion will not work directly because assertion is disabled by default. To enable the assertion, -ea or -enableassertions switch of java must be used. Compile: javac AssertionExample.java Run: java -ea AssertionExample www.lpuians.com

How Assertion Works? In assertion a BooleanExpression is used and if boolean expression is false then java throws AssertionError and the program terminates. Second form of assert keyword "assert booleanExpression : errorMessage" is more useful and provides a mechanism to pass additional data when Java assertion fails and java throws AssertionError. www.lpuians.com

Need of Assertion void remainder(int i) class AssertionNeed{ public static void main(String [] rk) { new AssertionNeed().remainder(8); } void remainder(int i) { if(i%3==0) System.out.println("Divisible by 3"); else if(i%3==1) System.out.println("Remainder 1"); else{ System.out.println("Remainder 2"); } } www.lpuians.com

What About it? class AssertionNeedTest { public static void main(String [] rk) new AssertionNeed().remainder(-7); } www.lpuians.com

Need of Assertion void remainder(int i) class AssertionNeed{ public static void main(String [] rk) { new AssertionNeed().remainder(-7); } void remainder(int i) { if(i%3==0) System.out.println("Divisible by 3"); else if(i%3==1) System.out.println("Remainder 1"); else{ // assert i%3 == 2 : i; System.out.println("Remainder 2"); } } www.lpuians.com

Why Assertion? Using assertion helps to detect bug early in development cycle which is very cost effective. Assertion in Java makes debugging easier as AssertionError is a best kind of error while debugging because its clearly tell source and reason of error. Assertion is great for data validation if by any chance your function is getting incorrect data your program will fail with AssertionError. www.lpuians.com

Important Assertion is introduced in JDK 1.4 and implemented using assert keyword in java. Assertion can be enabled at run time by using switch –ea or – enableassertion Assertion does not replace Exception but compliments it. Do not use assertion to validate arguments or parameters of public method. www.lpuians.com