Assertion:
Assertion is a statement in
java. It can be used to test your assumptions about the program.
While executing assertion, it
is believed to be true. If it fails, JVM will throw an error named
AssertionError. It is mainly used for testing purpose.
Advantage of Assertion:
It provides an effective way to
detect and correct programming errors.
Syntax of using Assertion:
There are two ways to use
assertion. First way is:
1. assert expression;
and second way is:
1. assert expression1 : expression2;
Simple
Example of Assertion in java:
1. import java.util.Scanner;
2.
3. class AssertionExample{
4. public static void main( String args[] ){
5.
6. Scanner scanner = new Scanner( System.in );
7. System.out.print("Enter ur age ");
8.
9. int value = scanner.nextInt();
10. assert value>=18:" Not valid";
11.
12. System.out.println("value is "+value);
13. }
14. }
If
you use assertion, It will not run simply because assertion is disabled by
default. To enable the assertion, -ea or -enableassertions switch of java must be used.
|
Compile
it by: javac AssertionExample.java
|
Run
it by: java -ea AssertionExample
|
Output: Enter ur age 11
Exception in thread "main" java.lang.AssertionError: Not valid
Where
not to use Assertion:
There are some situations where
assertion should be avoid to use. They are:
- According
to Sun Specification, assertion should not be used to check arguments in
the public methods because it should result in appropriate runtime
exception e.g. IllegalArgumentException, NullPointerException etc.
- Do
not use assertion, if you don't want any error in any situation.
For-each loop (Advanced or Enhanced For loop):
The for-each loop introduced in
Java5. It is mainly used to traverse array or collection elements. The
advantage of for-each loop is that it eliminates the possibility of bugs and
makes the code more readable.
Advantage of for-each loop:
- It
makes the code more readable.
- It
elimnates the possibility of programming errors.
Syntax of for-each loop:
1. for(data_type variable : array | collection){}
Simple
Example of for-each loop for traversing the array elements:
1.
2. class ForEachExample1{
3. public static void main(String args[]){
4. int arr[]={12,13,14,44};
5.
6. for(int i:arr){
7. System.out.println(i);
8. }
9.
10. }
11. }
Test it Now
Output:12
13
14
44
Simple
Example of for-each loop for traversing the collection elements:
1. import java.util.*;
2. class ForEachExample2{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("vimal");
6. list.add("sonoo");
7. list.add("ratan");
8.
9. for(String s:list){
10. System.out.println(s);
11. }
12.
13. }
14. }
Test it Now
Output:vimal
sonoo
ratan
No comments:
Post a Comment