Variables in Java

Notes:

Variables in Java Programming Language :

What is a variable & a constant?

Variable:
Variable is a named memory location, whose value can change during the execution of a program.

Constant:
Constant is a named memory location, whose value never changes during the execution of a program.

i.e. constants stay constant whereas variables vary.

W.K.T. While developing any software application using Java; we will be dealing with different types of data and data values. In order to store and process different types of data & data values computer uses its memory (RAM). To allocate a chunk of memory and access it within a Java program, we need to declare a variable or a constant.

Declaring a variable or a constant:
- means allocating a memory location for some data

Initializing a variable or a constant:
- means assigning the initial value to that allocated memory location

Syntax for declaring a variable:
datatype nameOfVariable;
Ex:
int playerScore;
int playerHealth;

Note: In Java, default value of a variable depends upon the type of a variable
- byte (0) , short (0), int (0), long (0L),
- float (0.0f), double (0.0d)
- char (‘\0’)
- boolean (false)
- Any reference (null)

Note:
- Before using a local variable it has to be initialized or assigned with some meaningful value

Syntax for declaring and initializing a variable:
datatype nameOfVariable = ivalue;
Ex:
int playerScore = 0;
int playerHealth = 100;

Syntax for assigning new value to a variable:
nameOfVariable = newvalue;
Ex:
playerScore = 10;
playerHealth = 80;

Syntax for declaring multiple variables:
datatype nameOfVariable1, nameOfVariable2,...;
Ex:
int playerScore, playerHealth;

Syntax for declaring & initializing multiple variables:
datatype nameOfVariable1 = ivalue, nameOfVariable2 = ivalue,…;
Ex:
int playerScore=0, playerHealth=100;

Example Code:

package variablesdemo;

public class VariablesDemo {

public static void main(String[] args) {
/*
int playerScore;
int playerHealth;
System.out.println("player score = " + playerScore); // error
System.out.println("player health = " + playerHealth);// error

int playerScore=0;
int playerHealth=100;
System.out.println("player score = " + playerScore); // 0
System.out.println("player health = " + playerHealth);// 100

playerScore = 10;
playerHealth = 80;

System.out.println("player score = " + playerScore); // 10
System.out.println("player health = " + playerHealth);// 80
*/

int playerScore=0, playerHealth=100;
System.out.println("player score = " + playerScore); // 0
System.out.println("player health = " + playerHealth);// 100

playerScore = 30;
playerHealth = 70;

System.out.println("player score = " + playerScore); // 30
System.out.println("player health = " + playerHealth);// 70
}
}