Java Variables

What is a Variable?

As the name suggests variable is element whose value changes dynamically. For example consider a value 100 which is constant why? Its value never changes, it is always 100 only. But in real world there are so many parameters which dynamic in nature. For example consider temperature, which changes dynamically for ever second. We call these values as variables.

We store these variables in memory. But to access these memory locations we need to give a unique name to it. That is called variable name. This is same as how our houses will have unique house number, in the same way we will give unique name to our memory locations. By using this name we can easily access memory location to read and write data.

Declaring a Variable

As we already know every data we use in Java should have its type. In the same way every variable we declare in Java should have a type and it only stores of that type value only. Syntax for declaring a variable is,

data-type variable-name;

All variable must be declared before we use them. This is mandatory because compiler must know what type of data a variable holds and processes. This allows Java to perform strict type checking.

We can declare multiple variables of same type by comma separated.

data-type variable1, variable2,...;

For example in the below lines we are declaring an integer variable count and two character variables gender and nextline.

int count;
char gender, nextline;

You have to give variable to a meaningful name. Name should denote its usage in the program. In above example if I use gender variable for denote first letter of weekdays, it does not give information exact information about usage. This kinds of improper information leads to programming errors. So always give proper names to variable as per usage.

Initializing a Variable

It is most common practice to give default or initial value to a variable at the time of declaration. This is called initialization of a variable.

type name = value;
type name1 = value1, name = value2,...;

For example:

int count = 0;
char gender = 'f', nextline='\n';

In the above example we have initialized count to 0, gender to ‘f’ and nextline to ‘\n’ (new line escape sequence character).

Let us see full program with these variables and print them after initializing.

/*
This is a simple Java program about variables.
Call this file KH_Variables.java.
*/
public class KH_Variables {
	// A Java program begins with a call to main().
	public static void main(String args[]) {
		int count = 0;
		char gender = 'f', nextline = '\n';
		
		System.out.println("Count = " + count);
		System.out.println("Gender = " + gender + nextline + "This prints in new line.");
	}
}

Download the code Run the code

This program generates following output.

Count = 0
Gender = f
This prints in new line.

In the above program, to display a string and value of variable using println, we used + sign. This concatenates two values and displays as single string. In next statement, see how nextline value forces output to display in new line. This is to show how we can smartly use escape sequence characters.

Scope and Lifetime

The first question I will get is what is scope and lifetime of a varaible? A scope is till where a variable is visible to other parts of the program. Lifetime is till when variable exists in memory. Scope and lifetime is defined by block in which variable is declared.

The general rule of thumb is that a variable is available till the block in which it is declared ends. After the blocks ends variable is not available to access.

Scope and life time can be nested. It means variable is accessible to block which inside parent block but vice versa is not true. That is child block variable is not available to parent block.

Let’s understand this by a program.

/*
This is a simple Java program about variable scope.
Call this file KH_VariablesScope.java.
*/
public class KH_VariablesScope {
	// A Java program begins with a call to main().
	public static void main(String args[]) 
	{
		int x = 0;
		
		{
			int y = 10;
			
			x = 100;
			System.out.println("Inner block");
			System.out.println("x = " + x);
			System.out.println("y = " + y);
		}
		System.out.println("outer block");
		System.out.println("x = " + x);
		//System.out.println("y = " + y);
	}
}

Download the code Run the code

In the above example, we have declared two variables x and y. x is declared in outer block and y is in inner block. As we stated above x is available to inner block also, hence we can assign a new value to it and print x and y values. But after inner block ends I am printing only x and I have commented printing y, because y is not available to access and in memory once inner ends. If you it now below output is generated.

Inner block
x = 100
y = 10
outer block
x = 100

But if you uncomment printing y statement in outer block and try to compile it, you will get error that y is not defined. That is Java do not know about y anymore.

KH_VariablesScope.java:21: error: cannot find symbol
                System.out.println("y = " + y);
                                            ^
  symbol:   variable y
  location: class KH_VariablesScope
1 error

This is all about variable and its scope and lifetime. In future lessons we will discuss more about scope when we are discussing about classes.

<<< Java Keywords and Best PracticesData Types and Literals >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .