Variables in Java

Variable Declaration in Java



In Java, all the variables must be declared to the compiler before they can be used in the program. We can declare a variable in Java by using two types of syntax:

Syntax:

1. data_type variable_name;

2. data_type variable_name = value;

You must end the declaration statement with a semicolon.



For example:

int a; where int is a data type and a is variable.

int b = 20; where int is a data type and b is a variable. Here, we can say that b is a type of int having value as twenty.

When we define a variable with some initial value, it is called initialization. A variable must be given a value after declaration but before it has been used in the expression.



To declare more than one variable of the same type, we can use a comma-separated list.

Following are the valid examples of the variables declaration and initialization in Java:



int x, y, z; // Here, we declare three variables x, y, and z having data type int.

int x = 10, y = 20; // Example of Initialization.

byte a = 30; // Initializes a byte type variable a.

double pi = 3.14; // declares and assigns a value of pi.

Variables Initialization in Java

The value of variables can be assigned in two ways:

1. Static: When the class is loaded into the memory, the memory is determined for the variables. Such variables are known as static variables or class variables in java.

For example:

static String name = “Kiran”; // Here, name is variable having string value and variable name is declared with the static keyword.



2. Dynamic: In dynamic initialization, you can declare variables anywhere in the program because when the statement is executed, the memory is assigned to them.

For example:

char ch = ‘B’; // Declaring and Initializing character variables.

int number = 100; // Declaring and Initializing integer variables.

int time = 40, distance = 50;

Naming Convention for the declaring variables in Java

➲ As per Java coding standard, the variable name should start with a lower case letter.

For example:

int age;

If you have lengthy variables such as more than one words then you can declare first word small and second word with the capital letter like this:

int smallNumber;

String collegeName;



➲ The variable name should not contain blank space.

int num ber = 100; is invalid because there is a blank space between num and ber.

➲ The variable name can begin with a special character such as $ and _.

For examples:

String $name; // valid.

String _nSchool; // valid.

int @num; // invalid.



➲ The first character must be a letter.

int 2num; // invalid.

➲ Java keywords should not be used as variable name.

➲ The variable names are case sensitive in Java.



So, these are some important points which you have to keep in mind for the declaration of variables in Java.

Types of Variables in Java