Variables In Java | Java Tutorial

In Java, variable is a name given to a memory location and this variable is associated with a value.

int x = 99;

int – data type
x – variable
99 – value

variable x holds integer values and its current value is 99.

Let’s see how to declare variables in Java

Syntax to declare a variable in Java:

data_type variable = value;

Example:

int x = 99;

Variable Naming Convention in Java:

Earlier we have learnt that Java is a Case Sensitive Language. Even variables have their own naming convention to follow.

1. Variable name can starts with special characters such as _ or $

Example:

int $myAge;

2. Variable name should begin with lower case leter

Example:

Wrong way: int Age;
Correct way: int age;

3. If the variable name consists of more than one word, it’s a best practice to capitalize the first letter of each subsequent word.

Example:

Wrong way: int myage;
Correct way: int myAge;

4. Variable name should not contain white spaces

Example:

Wrong way: int my Age;
Correct way: int myAge;

Types of Variables in Java:

There are three types of variables in Java.

1. Local variable
2. Instance variable
3. Class/Static variable

Let’s see each variable in detail.

Local Variable:

Local variable is a variable which we declare inside a Method. A method will often store its temporary state in local variables.

Instance Variable (Non-static):

Instance variable is a variable which is declared inside a Class but outside a Method. We don’t declare this variable as Static because these variables are non-static variables.

Class Variable (Static):

Class variable is a variable which is declared as Static. Additionally, the keyword final could be added to include that the value will never change.

Sample Program 1:

Sample Program 2:

Must Read: Java Tutorial

Get our latest blog posts delivered to your inbox

Subscribe and get popular blog posts about software testing industry.

Rajkumar

Leave a Comment

Share via
Copy link
Powered by Social Snap