Java is a very versatile language, that can be used for object oriented programming (OOP), computation and many other applications. In order to make full use of Java, you need to know how to use variables.
Declaring A Data Type
Declaring your data type is one of the most important things when it comes to strong information. You are essentially warning the program what type of information it should be expecting. Declaring the correct type is important because once you declare a variable as a certain data type it can not be changed. Let’s look at some examples:
This means that the variable called “num” (short for number) is now of type “int”.
Note: Ensure that when declaring variables you remember to put a semicolon.
Now you have an empty variable called “num”.
You now have an empty string called s. A string is a group of characters that could be a word or a sentence or blank.
Note: Ensure that you make sure you correctly capitalize keywords.
This is a start, but you can not actually use these yet. The next step is to assign something to the variables.
Assigning Data to Variables
This step involves putting something in the variable which is done by simply using an equals sign (“=”). This looks like this:
You now have a number/integer (“int”) called “num” that stores the number “10”.
Note: Remember to use a semicolon and keep in mind that it is “=” and not “==”. “==” is used for comparison and not assigning.
To continue with our other example:
Keep in mind that when assigning something to a string you use quotes (“”). It is also an option to say:
This would mean that you are assigning it a blank string, which is different then assigning it nothing.
Combining And Simplifying
I have shown you the above way to show you how the declaration and assigning portions work. It is correct coding to declare variables the above way, but you can also combine the two steps into one line. So this:
Becomes:
and
Becomes:
This is much neater and faster to write, but both forms are useful.
Declaring Multiple Variables Simultaneously
This is a bit trickier and should be done cautiously. But if you have multiple things you want to declare, that are of the same type, you can do it in a single line, like so:
Note: they are separated by commas for the inner names and as normal ends with a semicolon
Like before, these are empty. You now have to assign information, in this case a number, to each variable. This looks like:
Again you can simplify this into one line:
Be sure that you are using commas between each variable with a semicolon at the end.
Using Different Primitive Data Types
Using the format described above you can use then use any other primitive data type as long as you know how to declare its type. For a list of other primitive data types and more in depth information on all of them check out my other post, Intro to Variables and Operators.