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

How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxAmita Gupta
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 

Recently uploaded (20)

Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 

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.