Just like in math a variable is something that holds and stores a value. In programming our variables can hold different types of values that are not just numbers. We denote these different types as data types. There are a few different ways that we can create and use variables which we will talk about later.
Unlike other programming languages Java is very strict about when and how you use different data types. This means it is very important to understand what a data type is and which are used for what. Below is a list of some of the main data types in Java along with a brief description. You will see these explained more in depth later in the tutorial.
- int is any non decimal number, positive or negative. Ex(-1, 5, -89, 0)
- double is any floating point decimal number, positive or negatibve. Ex(-1.0, 96.7, -0.2, 0.4648)
- boolean is the value true or false. Ex(true, false)
- char is any character (always enclosed with ''). Ex('h', '-', 'e','L', '7')
- String is a collection of characters (always enclosed with ""). Ex("hello", "987627", "9tim", "techwithtim.net")
These are the main data types that we will use but many more will appear in future videos.
Creating a Variable
In Java to create a variable we need three pieces of information.
1. The type of the variable (data type).
2. The name of the variable (we create this).
3. The value it will be assigned (must match the data type we specify)
We start by declaring the type, then the name and we assign it equal to the value using an = sign.
Once we've created a variable we can reference it throughout our program by using it's variable name. For example to print our variable to the console we can do the following:
We can change the value of our variable like so:
And we can assign the value of one variable to another.