Next page | Contents page |

Statements and local variables

Statements

All statements end with a semicolon (;).

Anywhere that a statement could be used it may be replaced by a compound statement, in curly braces:

{
	statement1;
	statement2;
	// ...
}

It is usual to align the braces and indent the lines inside. Nested compound statements are common.

Local variables - scope

If variables (or constants) are declared within a compound statement they are local. They cease to exist ("go out of scope") when execution leaves that compound statement. Eg,

	int x = 2;

	{
		int i = 3, j = 4;
		x += i * j;
	}
	
	// i and j no longer exist, but x still does

So in our Squarer program (Exercise 1) the body of the main method is inside curly braces and therefore the same rule applies. The variables we declared (n and nsq) exist inside the method but afterwards they are cleared away automatically by the JVM.

Next page | Contents page |