Variables
In the chapter "Getting started", we learnt that an object has different properties or fields which they use to store their state. In the Java programming language, the words field and variable are both one and the same thing.
[edit] What are variables?
Variables are devices that are used to store data, such as a number, or a string of character data. However for a variable to hold data, a Java programmer has to explicitly define what it can and cannot hold. Thus all variables in the Java programming language ought to have a particular data type.
[edit] Kinds of variables
There are four kinds of variables in the Java programming language; these are:
- Instance variables: These are variables that are used to store the state of an object. These variables usually have the
private
access modifiers but they might seldom have apublic
access modifier. However, they can never have astatic
modifier attached to them. Every object created from a class definition would have its own copy of the variable. - Class variables: These variables are explicitly defined within the class-level scope with a
static
modifier. Because these variables are defined with thestatic
modifier, there would always be a single copy of these variables no matter how many times the class has been instantiated. - Local variables: These variables are defined and used specifically within the method-level scope. These variables are initiated much like the instance variables, however they do not have any modifiers attached to it (i.e.
public
,private
,protected
orstatic
). - Parameters or Arguments: These are variables passed into a method signature. Recall the usage of the
args
variable in the main method.
Question: Consider the following code:
public class SomeClass { public int a; private int b; public static int c; public void someMethod(int d) { int e; } }
In the example above, we created five variables: a
, b
, c
, d
and e
. All these variables have the same data type int
(integer). However, can you tell what kind of variable each one is?
a
andb
are instance variables;c
is a class variable;d
is a parameter or argument; and,e
is a local variable.
[edit] Creating variables
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. 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.
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.
Listing 1.1: A simple variable declaration.
int a;
[edit] 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.
Listing 1.2: Variable declaration and assignment operation (on different lines).
int a; a = 10;
Java provides programmers with a simpler way of combining both variable declaration and assignment operation in one line. Consider the following code:
Listing 1.3: Variable declaration and assignment operation (on the same line).
int a = 10;
Consider the following code:
int a; int b; String c; a = 10; b = 20; c = "some text";
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:
int a, b; String c; a = 10; b = 20; c = "some text";
Alternatively, you can further reduce the syntax by doing group declarations and assignments together, as such:
int a = 10, b = 20; String c = "some text";
This makes a programmer's life just that bit easier, and the code is easier to maintain as well.
[edit] Understanding data types
Take a look at the code in Listing 1.4. We understand that the variable age
that we created must hold an integer value (as understood from the usage of the int
data type). However, instead of putting an integer as a value, we present it with a floating point number (a number with a decimal point). Thus, the following code is not correct:
Listing 1.4: Setting a floating point number as a value to an int
(integer) type.
int age = 10.5;
As we already know, the code above is wrong. This is because integers are whole numbers and their opposites: 0
, 10
, 21
, -21
, etc. Anything with a decimal point is not an integer, hence the assignment operation in this instance is wrong. In common programming practice, variables that can hold numbers with decimal points are called floating point numbers and should have an appropriate data type.
[edit] Integer numbers and floating point numbers
The data types that one can use for integer numbers are byte
, short
, int
and long
but when it comes to floating point numbers, we use float
or double
. Now that we know that, we can modify the code in Listing 1.4 as:
Listing 1.5: Correct floating point declaration and assignment.
double age = 10.5;
Why not float
, you say? Well, there are several reasons why not. The number 10.5
could be anything – a float
or a double
but by a certain rule, it is given a certain type. This can be explained further by looking at the table below.
Data type | Values accepted | Declaration |
---|---|---|
byte |
Any number between -128 and 127 . |
byte b = 123; |
short |
Any number between -32,768 and 32,767 . |
short s = 12345; |
int |
Any number between -2,147,483,648 and 2,147,483,647 . |
int i = 1234567; |
long |
Any number between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 . |
long l = 1234567890L; |
float |
Extremely large numbers beyond the scope of discussion here. |
float f = 123.4567f; |
double |
Extremely large numbers beyond the scope of discussion here. The only difference between double and float is the addition of an f as a suffix after the float value. |
double d = 1234.56789; |
The above table only list the number data types. We will look at the others as we go on. So, did you notice why we used a double
in listing 1.3, and not a float
? The answer is pretty simple. If we'd used a float
, we would have to append the number with a f
as a suffix, so 10.5
should be 10.5f
as in:
Listing 1.6: The correct way to define floating point numbers of type float
.
float age = 10.5f;
[edit] Identifiers
Identifiers are the names we give to our variables. You can name your variable anything like aVariable
, someVariable
, age
, 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:
- Characters
A
toZ
and their lower-case counterpartsa
toz
. - Numbers
0
to9
. However, numbers should not come at the beginning of a variable's name. - And finally, special characters that include only
$
(dollar sign) and_
(underscore).
Question: Which of the ones below are proper variable identifiers?
f_name
lastname
someones name
$SomeoneElsesName
7days
TheAnswerIs42
I can tell you that 3 and 5 are not the right way to do things around here, the rest are proper identifiers. Well, not quite. They might be correct but they are not 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
fname
, you should always name it properly:firstName
is the best way of naming a variable.
[edit] 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:
int a = 24; int b = 365; int c = a * b;
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:
int age = 24; int daysInYear = 365; int ageInDays = age * daysInYear;
Now you can tell what's happening, can't you? However, before we continue, notice the case of the variables.
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 first
and name
could be written as either firstName
or FirstName
.
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.
[edit] Literals (values)
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:
int age = 24; long bankBalance = 20000005L;
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:
char c = 'a';
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:
char firstChar = 'J'; char secondChar = 'o'; char thirdChar = 'h'; char fourthChar = 'n';
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:
String name = "John";
Notice, the use of double quotation marks instead of single quotation marks. That's the only thing you need to worry about. Pretty simple, ain't it?
[edit] Primitive and object reference declaration
Variables are either primitive types or object references. Primitive types are data stored directly in memory; these include boolean, byte, char, short, int, long, float, and double. Everything else is an object reference, including a reference to an array instead of representing the actual data, object references could be described as a bookmark, which points to where the data is stored.
Primitives are defined like the following:
int myInteger; float amount; boolean isFinished;
The above lines both declare the variables and set aside space for the type. Bytes are 8 bits (signed), char 16 bits (unsigned), short 16 bits (signed), int 32 bits (signed), long 64 bits (signed), float 32 bits, and double 64 bits.
Object references are similar:
Object myObject; String name; Map contestants; int[] widths; JButton[] buttons;
The above lines declare the variables and set aside space for the references, but not for the object themselves. The objects must be created and assigned to the variables:
myObject = new Object(); name = "Jeff"; contestants = new HashMap(); widths = new int[26]; buttons = new JButton[numButtons];
The array referenced by widths will contain 26 integers, but the array referenced by buttons will only contain numButtons JButton references. The array must then be filled in with references to actual objects:
for (int i = 0; i < numButtons; i++) { buttons[i] = new JButton(); }
Variables can also be initialized right in the declaration statement:
int numButtons = 90;