Variables
A variable is an object that can hold a value:
int myVariable = 15;
You
initialize a variable by writing its type, its
identifier,
and then assigning a value to that variable. The previous section
explained types. In this example, the variable’s
type is int (which is, as you’ve seen, a type of
integer).
An identifier is just an arbitrary name you assign to a variable, method, class, or other element. In this case, the variable’s identifier is myVariable.
You can define variables without initializing them:
int myVariable;
You can then assign a value to myVariable later in your program:
int myVariable; // some other code here myVariable = 15; // assign 15 to myVariable
You can also change the value of a variable later in the program. That is why they’re called variables; their values vary.
int myVariable; // some other code here myVariable = 15; // assign 15 to myVariable // some other code here myVariable = 12; // now it is 12
Technically, a variable is a named storage location (i.e., stored in memory) with a type. After the final line of code in the previous example, the value 12 is stored in the named location myVariable.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access