Variables
In this lesson we’ll introduce you to variables.
What are Variables?
Variables are arguably the most important thing in programming any language. Variables consist of 3 main components:
- The type
This is what the variable stores, some examples are:String- Stores text, such as “Hello”. String values are surrounded by double quotes.int- stores integers (whole numbers), without decimals, such as 123 or -123.double- stores floating point numbers, with decimals, like 19.99 or -3.14159265. Double values end withd. (for people with experience, we will not be usingfloatin our code).char- stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotesboolean- stores values with two states:trueorfalse
- The name
This is what the value is stored to, you use this name to reference its value - The value
This is what the variable stores, it will be of the same type of the variable
The parts get arranged like so:
type name = value;
It’s important to note that the value is optional and the following is also a valid format:
type name;
If you use this, I would expect that you give it a value soon afterwards.
Some Examples
If I wanted to make a variable called message with a type of String and a value of Hello World I could do the following.
String message = "Hello World";
System.out.println(message);
The code above will print the value of the variable message which in this case is "Hello World".
double pi = 3.14159265d;
System.out.println(pi); // Prints 3.14159265
int number = 67;
System.out.println(number); // Prints 67
Assigning Later
The following is a example of how you can give a variable a value after declaring it.
int number;
number = 45;
System.out.println(number); // Prints 45
Notice how after declaring a variable, we don’t need to put the type next to it when assigning it a value.
Assigning Generally
We often find it useful to update a variable so here’s a example, it’s the exact same assigning syntax.
int number = 12;
number = 41; // Changes number to 41
System.out.println(number); // Prints 41
number = 67; // Changes number to 67
System.out.println(number); // Prints 67
Using Variables
Variables are useful in that they act as their value. Here are some examples of variables being used.
double x = 0.4d + 12.1d; // After the =, we can put any expression that gives us a value, for example, math operations
double y = 2.4d + 0.1d;
double result = x + y; // 12.5 + 2.5
System.out.println(result); // Prints 15
double x = 1;
x = x + 1;
System.out.println(x); // Prints 2
In our next lesson we’ll look at functions and how they are useful.