Variables are the basic entities in a program that are used to identify different values. A variable can be declared as :

type variable-name;

Initialize a variable

int a = 10; // 10 is assigned to a
char c = 'x'; // x is assigned to c

When declaring two or more variables of the same type using a comma-separated list, you can give one or more of those variables an initial value. For example:

int a, b = 8, c = 19, d; // b and c have initializations

Dynamic Initialization

int a=10;
int b=20;
int c = a+b; // dynamic initialization

Scope and Lifetime of Variables

there are mainly two types of lifetime of variable, one is global variables and other is local variables. They are explained as :

Global Variables : Global variables are valid throughout the program, they can be modified anywhere in the program.
Local Variables : Local variables are valid throughout the Block ( between { and }), they can be modified anywhere in the block only and not visible outside block. Example is as follows :

public class GlobalAndLocal {

	public static void main(String[] args) {
		int gVariable = 20; // gVariable will be global to the main function here
		{ // block starting here
			int lVariable = 10; // local to this block only
			System.out.println("Global Variable " + gVariable);
			gVariable = 100; // modifying global variable assign 100 to gVariable
			System.out.println("Global Variable again " + gVariable); 
			System.out.println("Local Variable lVariable" + lVariable); 

		}// block ending here
		System.out.println("Local Variable lVariable" + lVariable); /* will give
		error as lVariable is not known here, scope of lVariable is only to the
		upper block */

You may also like...