SlideShare a Scribd company logo
1 of 16
Programming in Java
Topic: Assertion
Contents
 Introduction
 Assertion
 Using Assertion
 How assertion works
 Benefit of using Assertion
 Important Points
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).
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;
}
Assertion
 The assertion statement has two forms.
o 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.
o 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.
Example
public class AssertionExample{
public static void main(String[] args)
{
int num=Integer.parseInt(args[0]);
assert num>=10;// stop if number is less than 10
assert num<20: "number should be less than 20";
// if fail msg is displayed with error
System.out.println("Pass");
}
}
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
Difference between Assertion and If
statement
1. An if statement will not raise an exception when the
condition is false. Assertion will raise an assertion error
when the condition is false. An assertion exception will stop
the program unless the exception is handled by a try-
except block.
2. Look at assertions as a method for development. so you
can build various checkpoints across the code to ensure
that variables/arguments are meeting the expected
limitations (e.g. you know it must be number not letter, it
must be positive , etc...). Then once you're done with
development you can globally turnoff all the assertions. In
case you will use IF statements (instead of assertions) for
this, you will need to clean up the code and possibly
introduce some errors.
Continue…
3.
if-else is for controlling the flow of your program.
assert must not be used for this! Asserts are just
for having "checkpoints" in your code to check
conditions which "should always" match.
Asserts can be turned on or off when running a
program so that you could enable the asserts on
your development machine/integration
environment and disable them in the released
version.
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.
Need of Assertion
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"); }
}
}
What About it?
class AssertionNeedTest
{
public static void main(String [] rk)
{
new AssertionNeed().remainder(-7);
}
}
Need of Assertion
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"); }
}
}
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.
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.
21. Assertion.ppt

More Related Content

Similar to 21. Assertion.ppt

Similar to 21. Assertion.ppt (20)

Java unit 11
Java unit 11Java unit 11
Java unit 11
 
Control statements
Control statementsControl statements
Control statements
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
 
J unit a starter guide
J unit a starter guideJ unit a starter guide
J unit a starter guide
 
Junit
JunitJunit
Junit
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Chapter 4.1
Chapter 4.1Chapter 4.1
Chapter 4.1
 
SUBHASH.pptx
SUBHASH.pptxSUBHASH.pptx
SUBHASH.pptx
 
java notes.pdf
java notes.pdfjava notes.pdf
java notes.pdf
 
Md04 flow control
Md04 flow controlMd04 flow control
Md04 flow control
 
jhtp9_ch04.ppt
jhtp9_ch04.pptjhtp9_ch04.ppt
jhtp9_ch04.ppt
 
exception handling
exception handlingexception handling
exception handling
 
Java programming-Event Handling
Java programming-Event HandlingJava programming-Event Handling
Java programming-Event Handling
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style Guide
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 

Recently uploaded

HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 

Recently uploaded (20)

Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 

21. Assertion.ppt

  • 2. Contents  Introduction  Assertion  Using Assertion  How assertion works  Benefit of using Assertion  Important Points
  • 3. 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).
  • 4. 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; }
  • 5. Assertion  The assertion statement has two forms. o 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. o 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.
  • 6. Example public class AssertionExample{ public static void main(String[] args) { int num=Integer.parseInt(args[0]); assert num>=10;// stop if number is less than 10 assert num<20: "number should be less than 20"; // if fail msg is displayed with error System.out.println("Pass"); } }
  • 7. 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
  • 8. Difference between Assertion and If statement 1. An if statement will not raise an exception when the condition is false. Assertion will raise an assertion error when the condition is false. An assertion exception will stop the program unless the exception is handled by a try- except block. 2. Look at assertions as a method for development. so you can build various checkpoints across the code to ensure that variables/arguments are meeting the expected limitations (e.g. you know it must be number not letter, it must be positive , etc...). Then once you're done with development you can globally turnoff all the assertions. In case you will use IF statements (instead of assertions) for this, you will need to clean up the code and possibly introduce some errors.
  • 9. Continue… 3. if-else is for controlling the flow of your program. assert must not be used for this! Asserts are just for having "checkpoints" in your code to check conditions which "should always" match. Asserts can be turned on or off when running a program so that you could enable the asserts on your development machine/integration environment and disable them in the released version.
  • 10. 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.
  • 11. Need of Assertion 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"); } } }
  • 12. What About it? class AssertionNeedTest { public static void main(String [] rk) { new AssertionNeed().remainder(-7); } }
  • 13. Need of Assertion 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"); } } }
  • 14. 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.
  • 15. 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.