Java Variables

What Is a Variable?

When writing a program, you need to store data required for the program’s behavior. Java stores this data in memory.
A variable is a representative name given to the memory location where a value is stored.
A variable names the space where data is stored and can store only one piece of data.
It can be compared to a container, as memory space for storing data used in a program, such as numbers, characters, strings, and logical values.
A variable is called a variable because the data stored in it changes depending on processing.

Variable Declaration and Initialization

To use a variable, you must first declare things such as “what kind of value, such as a number or string, will this variable store?”, “what name will it have?”, and “what value will it store initially?”

To use a variable in Java, you must perform “variable declaration” and “variable initialization.”

type name[=init], ...
  type: data type
  name: variable name
  init: initial value

Variable Declaration

Variable declaration tells the program about a variable you want to use. A program can control only declared variables. Before using a variable, you must declare it with a data type according to the type or size of data you want to store.

Method and structure of variable declaration

int variable;

To declare a variable, write the data type(int) and the variable name(variable).

  • Data type: determines the type of data to enter.
  • Variable name: the name of the variable. Duplicates are not allowed.

Variable Initialization

Variable initialization is the action of storing data in a variable declared earlier. There are two ways to initialize a variable, as shown below.

Declaring and initializing on separate lines

int num;

num = 10;

Declaring and initializing on the same line

int num = 5;

Either method can be used.

If the data type is the same, variables can also be listed as follows.

double num = 3.14, num2 = 1.414;

Once a variable type has been declared, it cannot be changed. Therefore, if you try to assign a string to a variable declared as double type(decimal type), as shown below, an error occurs.

double num;

num = "Hello World! Java.";  // error

Variable Naming Rules

  • Case-sensitive
  • No length limit
  • Reserved words cannot be used
  • Cannot start with a digit
  • Special characters _ and $ are allowed