Lesson 7: Numerical Variables

After learning about variables and printing Strings, we are now going to learn about some numerical variables that we encounter in Java.  

As you will find out with practice, many Java programs require a fair bit of numerical data.  The best and most common way to store numerical values are by using the variable types: int (short for integer) and double.  

When we want to store whole numbers, we will want to use the “int’ data type.  Some examples of ints would be 1, -200, or 500.  However, we can not use any decimal numbers without causing a compiler error.  That is where the variable type double comes into play.

If we have a number that is a decimal, we will want to use the double data type to store our number. Some examples of doubles are 2.5, -5.7, or 100.9920.

It is important to note that you can store an integer as a double value, but it will return the integer with a decimal point and 0 placeholder.  For example, if we stored the integer 1 as a double value, it would become 1.0.

Let us make a class in Java and name it:  Numbers.  Then, implement the main method.

Now we are going to declare 2 numbers – an integer and a decimal number.

For our integer, we will name it integer and make the value 5

For our decimal, we will name it decimal and make the value 2.25.

After making our variables, we will now use print methods to see what the console returns.

After compiling the code above, we can run our code and get the following output:

Nice job!  As you can see, declaring numerical variables is straight forward process.  Just remember that we use int for whole numbers and double for any decimal numbers.

GitHub link.

Leave a Reply

%d bloggers like this: