Previous | Home | Next |
A constant is a variable whose value cannot change once it has been assigned. The final keyword can be used with primitive data types and immutable. The final keyword means is that once the value has been assigned, it cannot be re-assigned. A block begins with an open braceand close is close brace.A block is a sequence of statements, local class declarations and local variable declaration statements within braces. A block is executed by executing each of the local variable declaration statements and other statements in order from first to last (left to right). After a block is executed all local variables defined inside the block is discarded, go out of scope.
You can declare local variables anywhere in a method body. if you declare a variable within a block, then it only has scope within the block.
PI = 3.14
Example :
public class Constants { public static void main(String[] args) { double r = 10; double area; final double PI=3.14; area = PI * r * r; System.out.print("radius = "); System.out.println(r); System.out.print("area = "); System.out.println(area); } }
output :
radius = 10.0 area = 314.00
A block is a compound statement and consists of all the statements between an opening and closing brace. The scope of a variable defines the section of the code in which the variable is visible. variables that are defined within a block are not accessible outside that block.
- Empty body (Zero statements):
- One statement:
- More than one statement:
{ // Open brace starts block } // Close brace ends block
{ // Open brace starts block System.out.println( "One" ) ; } // Close brace ends block
{ // Open brace starts block System.out.println( "One" ) ; System.out.println( "Two" ) ; System.out.println( "Three" ) ; } // Close brace ends block
Example :
public void set() { int x = 3 ; { // Open brace starts block int y = 4 ; // Prints 7. y is accessible here System.out.println( "Sum is " + (x + y) ); } // End of block. y is out of scope System.out.println( "x is " + x ); // Won't compile. y is not in scope System.out.println( "Sum is " + (x + y) ) ; }
Previous | Home | Next |