Newby Coder header banner

Variables

Variables in Programming

A variable is an identifier or a name assigned to a value or object

The name of a variable is typically restricted to english alphabets, numbers and underscore (_), while its value may vary during the program is run

So the name remains same and any operation done with the variable is applied on its value

Changing the name for an object means assigned the object to another variable

Variables can be declared or initiated without any value or an empty value, and can have a value assigned to it when the program is run

Variables can also be declared as constants, to be associated with a single value during their lifetime

The lifetime of a variable depends on the scope(global or local) in which it is used

Scope of a Variable

A variable can be declared globally (i.e. outside of any class or structure) so that these can be accessed by all parts of the program

Or it can be declared locally inside a function or as an object variable, in which case they are accessible only when the function is run or when the object exists

The scope can be narrower, like a condition inside a function

Types of variables

Type of a variable depends on the value(s) that it is to be assigned to

In statically typed language, such as Java, the type of a variable is predefined by the programmer, and any value assigned to it must correspond to that value

In a dynamically typed language, such as Python, a variable only refers to a value and the type is associated with the value

So a variable can be assigned to value of any type in such cases

The type of a variable can be a default datatype of programming language like int(number), string(defined sequence of characters, but may be a single alphabet or multiple words), lists (of int,string) etc

Type of a variable may also be an user-defined datatype like a class