Casting Blocks and Scope in Java


Casting

Casting is the conversion of one type or class to another type or class. A cast is done from a source to a destination type. The syntax of type casting is as shown below.

destinationVariable = ( destination-type ) sourceType-expression

The destination-type as shown above is a reserved word. In the example below the subtraction is converted to a float for multiplication with the fraction. Also since an integer is required to be returned from the method the entire result is type casted into an integer before being returned from the method.

public int FahrenheitToCelcius ( int fahrenheit )
{
	return (int) ( ( 5 / 9 ) * (float) ( fahrenheit - 32 ) );

It should now be obvious that casting can result in a loss of information. For instance, casting from a float to an integer will result in loss of decimals after the decimal point. Thus the left-most bits are eliminated when casting down from a 32-bit to a 16-bit integer, ie. the number can become smaller by losing its 16 most significant bits.

Boolean types can not be cast at all.

Note that casting between classes is limited. In general casting between classes is abstracted through an inheritance hierarchy rather than specialised. This means that casting of classes is usually done from subclass to superclass. Casting in the other direction is allowed in Java but is risky. It generally does not make sense to cast from a superclass into a subclass since in actuality the subclass is specialised and thus the subclass may contain methods and attributes which are not available in the superclass. Therefore an error could be the result.

Blocks

All Java statements belong in blocks which group related statements together. Blocks can also be nested. Blocks are enclosed in braces ( { ... }). Most Java constructs like classes, methods and flow control statements use blocks to group related statements together. By convention the contents of blocks are indented to allow for more readability. Consistency must be maintained throughout code.

while (  )
{
	if (  )
	{
		...
	}
	else
	{
		...
	}
}

Scope

Scope is a term used to define where a variable is defined. Scope can also be said to have visibility within the section of code in which it is defined. Outside of that section of code that particular variable is undefined. A section of code implies a block and all blocks nested within that block. Note that multiple variables in different scopes can be given the same variable name. However, this is risky. Java is a strictly typed language in that variables require explicit declaration. Implicit declaration of variables is when variables do not require explicit declaration and any identifier can be used anywhere. This can lead to confusion and great difficulty in the finding of bugs caused by implicit variable declaration. Scoping of variables ensures that local variables are hidden from outer blocks of code.