Variable Declaration
Variable Initialization
Can be done by:
int count = 10; // valor inicial char ch = 'X'; // inicializa com 'X' float f = 1.2F; // inicializa com 1.2
Dynamic Startup
double volume = 3.1416 * radius * radius * height;
Scope and Lifetime of Variables
A block defines a scope:
Scopes can be nested:
int x = 10; if(x == 10) { int y = 20; System.out.println("x and y: " + x + " " + y); x = y * 2; } System.out.println("x is " + x);
Scope Rules and Peculiarities
Variables created when entering the scope and destroyed when leaving it.
Variables are reset when re-entering the block.
for(int x = 0; x < 3; x++) { int y = -1; System.out.println("y is: " + y); y = 100; System.out.println("y is now: " + y); }
// Este programa não será compilado int count; for(count = 0; count < 10; count++) { int count; // inválido for(count = 0; count < 2; count++) System.out.println("This program is in error!"); }
Summary of Key Points
The above is the detailed content of Declaration and Initialization of Variables in Java. For more information, please follow other related articles on the PHP Chinese website!