Assertion, Enum, Break, Continue, Label statements, Strictfp

Assertion

In Java, assertions can be used to document and validate assumptions made about the state of the program at designated locations in the code. Assertion is introduced in JDK 1.4 and implemented using assert keyword in java. Each assertion contains a boolean expression that is expected to be true when the assertion is executed. If this assumption is false, the JVM throws a special error represented by the AssertionError class. Since the assertion error signals failure in program behavior, it should not be caught programmatically, but allowed to propagate to the top level.

The following two forms of the assert statement can be used to specify assertions:
assert <boolean expression> ; // the simple form
assert <boolean expression> : <message expression> ; // the augmented form

The two forms are essentially equivalent to the following code, respectively:
if (<assertions enabled> && !<boolean expression>) throw new AssertionError(); // the simple form
if (<assertions enabled> && !<boolean expression>) throw new AssertionError(<message expression>); // the augmented form

If assertions are enabled, then the <boolean expression> is evaluated. 

By default assertion are disables in JVM. To enable it, you have to pass VM aruments. Two options are provided by the java command to enable and disable assertions with various granularities. The option -enableassertions, or its short form -ea, enables assertions, and the option -disableassertions, or its short form -da, disables assertions at various granularities.

Lets see an example.


package mynotes.shortConcepts;

public class AssertionExample {
 
 public double calculateSpeed(double distance, double time){
 
 assert distance>=0.0;
 assert time>=0.0 : "Time is not positive="+time;
 double speed =distance/time;
 return speed;
 
 }
 
 public static void main(String[] args) {
 AssertionExample aAssertionExample=new AssertionExample();
 //double speed= aAssertionExample.calculateSpeed(13, 2);
 //double speed= aAssertionExample.calculateSpeed(-13, 2);
 double speed= aAssertionExample.calculateSpeed(13, -2);
 System.out.println("Speed in km/h = "+ speed);
 }

}


Here both distance and speed needs to be positive. If they didnt satify the condition an AssertionError will be thrown. In the second assert statement of time, a custom message will also be thrown. To enable assertion in eclipse, go to Run > Run configuration and under the arguments tab , in VM arguments add -ea

AssertionEnabling

Now you can run, Previous program will result in following output:


Exception in thread "main" java.lang.AssertionError: Time is not positive=-2.0
 at mynotes.shortConcepts.AssertionExample.calculateSpeed(AssertionExample.java:8)
 at mynotes.shortConcepts.AssertionExample.main(AssertionExample.java:18)


JUnit extensively uses Java assertion to compare test result. It is recommended not to use assertion to validate arguments/parameters of a public method.

ENUM

An enumerated type defines a finite set of symbolic names and their values. These symbolic names are usually called enum constants or named constants. One way to define such constants is to declare them as final, static variables in a class (or interface)
declaration:


package mynotes.shortConcepts;

public class MachineState {

public static final int BUSY = 1;
 public static final int IDLE = 0;
 public static final int BLOCKED = -1;

}


Such constants are not typesafe, as any int value can be used where we need to use a constant declared in the MachineState class. Such a constant must be qualified by the class (or interface) name, unless the class is extended (or the interface is implemented).
When such a constant is printed, only its value (for example, 0), and not its name (for example, IDLE) is printed.

The canonical form of declaring an enum type is shown below.
enum MachineState { BUSY, IDLE, BLOCKED }; // Canonical form

Enums in Java are type-safe and has there own name-space. It means your enum will have a type for example “MachineState ” in below example and you can not assign any value other than specified in Enum Constants.

enum MachineState { BUSY, IDLE, BLOCKED };
MachineState state= MachineState .IDLE;
state= 1; //compilation error

Constructor of enum in java must be private any other access modifier will result in compilation error.


package mynotes.shortConcepts;

public enum MachineState {

BUSY(1), IDLE(0), BLOCKED(-1);
 private int state;

private MachineState(int state) {
 this.state = state;
 }

public int getState() {
 return state;
 }

}


Enum constants are implicitly static and final and can not be changed once created. Since constants defined inside Enum in Java are final you can safely compare them using “==” equality operator.

Enum in java can be used as an argument on switch statment and with “case:” like int or char primitive type. This feature of java enum makes them very useful for switch operations. 

You can not create instance of enums by using new operator in Java because constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.

Enum in Java can implement the interface and override any method like normal class. You can define abstract methods inside Enum in Java and can also provide different implementation for different instances of enum in java.

 

BREAK AND CONTINUE

A break statement results in the termination of the statement to which it applies (switch, for, do, or while).

A continue statement is used to end the current loop iteration and return control to the loop statement.


package mynotes.shortConcepts;

public class BreakContinue {

public static void main(String[] args) {

for (int i = 0; i < 10; i++) {

if (i % 2 == 0) { // if pair, will jump
 continue; // don't go to "System.out.print" below.
 }

System.out.println("The number is " + i);

if (i == 7) {
 break; // will end the execution, 8,9 wont be processed
 }

}
 }

}


Output:


The number is 1
The number is 3
The number is 5
The number is 7

A label is any valid Java identifier followed by a colon. e.g. outer:, inner:, inner123:, inner_: etc. Whenever during a program execution, a labeled break statement is encountered that control immediately goes out of enclosing labeled block. Similarily, labeled continue will bring control back to start. Just like in normal break and continue statements, with additional names given to blocks.


int[] numbers= new int[]{100,18,21,30};
 
 //Outer loop checks if number is multiple of 2
 OUTER: //outer label
 for(int i = 0; i<numbers.length; i++){
 if(i % 2 == 0){
 System.out.println("Odd number: " + i + ", continue from OUTER label");
 continue OUTER;
 }
 
 INNER://inner label
 for(int j = 0; j<numbers.length; j++){
 System.out.println("Even number: " + i + ", break from INNER label");
 break INNER;
 }
 }

Output:


Odd number: 0, continue from OUTER label
Even number: 1, break from INNER label
Odd number: 2, continue from OUTER label
Even number: 3, break from INNER label

Break can also be used inside CASE statement of switch construct.

A continue statement does not apply to a switch statement or a block statement, only to compound statements that loop: for, while, and do.

strictfp 

The strictfp keyword is used to force the precision of floating point calculations (float or double) in Java conform to IEEE’s 754 standard, explicitly. Without using strictfp keyword, the floating point precision depends on target platform’s hardware, i.e. CPU’s floating point processing capability. In other words, using strictfp ensures result of floating point computations is always same on all platforms.

The strictfp keyword can be applied for classes, interfaces and methods.

Rules

  • strictfp cannot be applied for constructors.
  • If an interface or class is declared with strictfp, then all methods and nested types within that interface or class are implicitly strictfp.
  • strictfp cannot be applied for interface methods.

Examples

The following class is declared with strictfp, hence all the floating point computations within that class conform to IEEE’s 754 standard:


package mynotes.shortConcepts;

public strictfp class StrictFPClass {
double num1 = 10e+102;
double num2 = 6e+08;
double calculate() {
return num1 + num2;
}
}

The following interface is declared with strictfp, but its methods cannot:


package mynotes.shortConcepts;

public strictfp interface StrictFPInterface {
double calculate();
//strictfp double compute(); // compile error
}

The following method is declared with strictfp:


package mynotes.shortConcepts;

public class StrictFPMethod {
strictfp double computeTotal(double x, double y) {
return x + y;
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: