This content originally appeared on DEV Community and was authored by Eduardo Julião
A variable is a value that can change in your program.
Creating a variable
The structure to create a variable consists of:
<Data Type> <Name> = <Value>;
Data Type
Tells the program what type of variable it is, these can be int
, decimal
, string
, char
and others.
Name
A unique name to identify it.
Value
The value of the variable.
Some examples
int i = 10;
decimal d = 5.67;
float f = 7.90;
double d2 = 1.23;
string s = "string";
char c = 'c';
boolean b = true;
byte bt = 64;
Notice that a string is defined by using doble quotes "
, while a char is defined by using single quotes '
.
Array variables
We can also create a variable type that is the array
type, these variables are a list of values of a certain type.
Once an array is created, you can update its values, re-assign, but not extend its size.
Creating an array
<Data Type>[] name = new []{ };
or
<Data Type>[] name = new <Data Type>[<number of entries>];
Arrays are defined by adding []
after the data type, and can be assigned using one of the two forms.
Form 1
<Data Type>[] <Name> = new []{ <value1>, <valiue2> };
In this example, you create an array, that has a length of 3.
int[] arrayOfIntegers = new []{ 1, 2, 3 };
In this form, you don't need to specify the
Form 2
<Data Type>[] <Name> = new <Data Type>[<number of entries>];
In this example, you create an array, that has a length of 4.
int[] arrayOfIntegers = new int[4];
When creating an array in this form, the array will have 4 entries and all set to its default value, which in this case is 0.
Assigning values
You can assign values to an array by using its index, which starts at 0 and ends with its length - 1;
arrayOfIntegers[0] = 1;
arrayOfIntegers[1] = 2;
arrayOfIntegers[2] = 3;
arrayOfIntegers[3] = 4;
Constants
You can create variables that cannot change after being initialized. These types of variables are called constants.
Structure
const <Data Type> <Name> = <Value>;
Example
const int constantIntegerValue = 30;
This content originally appeared on DEV Community and was authored by Eduardo Julião
Eduardo Julião | Sciencx (2021-07-08T14:49:47+00:00) Variables. Retrieved from https://www.scien.cx/2021/07/08/variables/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.