|Navigate Language Fundamentals topic: )|
In the Java programming language, the words field and variable are both one and the same thing. Variables are devices that are used to store data, such as a number, or a string of character data.
Variables in Java programming
Java is considered as a strongly typed programming language. Thus all variables in the Java programming language ought to have a particular data type. This is either declared or inferred and the Java language only allows programs to run if they adhere to type constraints.
If you present a numeric type with data that is not numeric, say textual content, then such declarations would violate Java’s type system. This gives Java the ability of type safety. Java checks if an expression or data is encountered with an incorrect type or none at all. It then automatically flags this occurrence as an error at compile time. Most type-related errors are caught by the Java compiler, hence making a program more secure and safe once compiled completely and successfully. Some languages (such as C) define an interpretation of such a statement and use that interpretation without any warning; others (such as PL/I) define a conversion for almost all such statements and perform the conversion to complete the assignment. Some type errors can still occur at runtime because Java supports a cast operation which is a way of changing the type of one expression to another. However, Java performs run time type checking when doing such casts, so an incorrect type cast will cause a runtime exception rather than succeeding silently and allowing data corruption.
On the other hand, Java is also known as a hybrid language. While supporting object oriented programming (OOP), Java is not a pure OO language like Smalltalk or Ruby. Instead, Java offers both object types and primitive types. Primitive types are used for boolean, character, and numeric values and operations. This allows relatively good performance when manipulating numeric data, at the expense of flexibility. For example, you cannot subclass the primitive types and add new operations to them.
Kinds of variables
In the Java programming language, there are four kinds of variables.
|Code listing 3.9: ClassWithVariables.java
In the code listing 3.9, are examples of all four kinds of variables.
- Instance variables: These are variables that are used to store the state of an object (for example,
id). Every object created from a class definition would have its own copy of the variable. It is valid for and occupies storage for as long as the corresponding object is in memory.
- Class variables: These variables are explicitly defined within the class-level scope with a
staticmodifier (for example,
isClassUsed). No other variables can have a
staticmodifier attached to them. Because these variables are defined with the
staticmodifier, there would always be a single copy of these variables no matter how many times the class has been instantiated. They live as long as the class is loaded in memory.
- Parameters or Arguments: These are variables passed into a method signature (for example,
parameter). Recall the usage of the
argsvariable in the main method. They are not attached to modifiers (i.e.
static) and they can be used everywhere in the method. They are in memory during the execution of the method and can't be used after the method returns.
- Local variables: These variables are defined and used specifically within the method-level scope (for example,
currentValue) but not in the method signature. They do not have any modifiers attached to it. They no longer exist after the method has returned.
Variables and all the information they store are kept in the computer's memory for access. Think of a computer's memory as a table of data — where each cell corresponds to a variable.
Upon creating a variable, we basically create a new address space and give it a unique name. Java goes one step further and lets you define what you can place within the variable — in Java parlance you call this a data type. So, you essentially have to do two things in order to create a variable:
- Create a variable by giving it a unique name; and,
- Define a data type for the variable.
The following code demonstrates how a simple variable can be created. This process is known as variable declaration.
|Code section 3.40: A simple variable declaration.
Assigning values to variables
Because we have provided a data type for the variable, we have a hint as to what the variable can and cannot hold. We know that
int (integer) data type supports numbers that are either positive or negative integers. Therefore once a variable is created, we can provide it with any integer value using the following syntax. This process is called an assignment operation.
|Code section 3.41: Variable declaration and assignment operation (on different lines).
Java provides programmers with a simpler way of combining both variable declaration and assignment operation in one line. Consider the following code:
|Code section 3.42: Variable declaration and assignment operation (on the same line).
Grouping variable declarations and assignment operations
Consider the following code:
|Code section 3.43: Ungrouped declarations.
There are various ways by which you can streamline the writing of this code. You can group the declarations of similar data types in one statement, for instance:
|Code section 3.44: Grouped declarations.
Alternatively, you can further reduce the syntax by doing group declarations and assignments together, as such:
|Code section 3.45: Grouped declarations and assignments.
Although memory spaces have their own addresses — usually a hash number such as
0xCAD3, etc. — it is much easier to remember a variable's location in the memory if we can give it a recognizable name. Identifiers are the names we give to our variables. You can name your variable anything like
someonesImportantData, etcetera. But notice: none of the names we described here has a space within it. Hence, it is pretty obvious that spaces aren't allowed in variable names. In fact, there are a lot of other things that are not allowed in variable names. The things that are allowed are:
Zand their lower-case counterparts
9. However, numbers should not come at the beginning of a variable's name.
- And finally, special characters that include only
$(dollar sign) and
Any valid variable names might be correct but they are not always what you should be naming your variables for a few reasons as listed below:
- The name of the variable should reflect the value within them.
- The identifier should be named following the naming guidelines or conventions for doing so. We will explain that in a bit.
- The identifier shouldn't be a nonsense name like
lname, you should always name it properly:
lastNameis the best way of naming a variable.
Naming conventions for identifiers
When naming identifiers, you need to use the following guidelines which ensure that your variables are named accurately. As we discussed earlier, we should always name our variables in a way that tells us what they hold. Consider this example:
|Code section 3.46: Unknown process.
Do you know what this program does? Well, it multiplies two values. That much you guessed right. But, do you know what those values are? Exactly, you don't. Now consider this code:
|Code section 3.47: Time conversion.
Now you can tell what's happening, can't you? However, before we continue, notice the case of the variables. If a word contains CAPITAL LETTERS, it is in UPPER CASE. If a word has small letters, it is in lower case. Both cases in a word renders it as mIxEd CaSe.
The variables we studied so far had a mixed case. When there are two or more words making up the names of a variable, you need to use a special case called the camel-case. Just like the humps of a camel, your words need to stand out. Using this technique, the words
name could be written as either
The first instance,
firstName is what we use as the names of variables. Remember though,
firstName is not the same as
FirstName because Java is case-sensitive. Case-sensitive basically implies that the case in which you wrote one word is the case you have to call that word in when using them later on. Anything other than that is not the same as you intended. You'll know more as you progress. You can hopefully tell now why the variables you were asked to identify weren't proper.
Now that we know how variables should be named, let us look at the values of those variables. Simple values like numbers are called literals. This section shows you what literals are and how to use them. Consider the following code:
|Code section 3.48: Literals.
By now, we've only seen how numbers work in assignment statements. Let's look at data types other than numbers. Characters are basically letters of the English alphabet. When writing a single character, we use single quotes to encapsulate them. Take a look at the code below:
|Code section 3.49: Character.
Why, you ask? Well, the explanation is simple. If written without quotes, the system would think it's a variable identifier. That's the very distinction you have to make when differentiating between variables and their literal values. Character data types are a bit unusual. First, they can only hold a single character. What if you had to store a complete name within them, say John, would you write something like:
|Code section 3.50: Character list.
Now, that's pathetic. Thankfully, there's a data type that handles large number of characters, it's called a
String. A string can be initialized as follows:
|Code section 3.51: String.
Notice, the use of double quotation marks instead of single quotation marks. That's the only thing you need to worry about.