How to Declare Integer Variables in Java

The Easy Way to Learn How to Declare Variables in Java

Cloudage
In Java you can name a piece of memory to store information. This information can be a character, a word, an integer, a decimal number and so on. Knowing how to declare and define variables, and what exactly those terms mean, is crucial when learning how to program in Java.

First you must decide what kind of data you want stored in the variable. This is called to declare the variable. If you want to store an integer, and you declare the variable as that data type, then you can only store integers. If you want a decimal number too, you must declare another variable to hold that number. The value of the variable can be altered later, as long as the data type is the same.

I am making a program to keep track of how many goldfish there are in my aquarium. I name a variable numberGFish, and since all my fish are in one piece, I use the integer data type. To declare this variable in Java, I would write the following piece of code:

int numberGFish;

Now I have an integer variable called numberGFish. That's how easy it is to declare a variable! Take notice of the semicolon at the end, in Java semicolons always mark the end of statements.

I want my Java program to know how many goldfish I have as well, and not just have an empty variable. To do this I write:

numberGFish = 400;

When I declared the variable numberGFish, I could have assigned a value in the same statement. This is called initializing, because I give a value to the variable at the same time as I declare it. If you know the starting value off the bat, it's often a good idea to do it like this.

int numberGFish = 400;

I also have customers that are interested in my goldfish. Every day goldfish are being sold to new homes, and at the end of the day I like to keep a record over how many fish are left. This means that I will need to declare another variable, one for the number of fish sold. Since I don't like to waste space, I would like to put this variable in the same statement as the number of fish that I have. I don't sell half of a fish, so this will also be a whole number, which means it matches the data type. Luckily for me, Java makes it very easy to do just this, just separate the two variables with a comma.

int numberGFish = 400, numberSold = 30;

This is just how easy it is to declare an integer variable in Java!

Published by Cloudage

I am a student studying and tutoring in math, chemistry and physics.  View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.