Navigate Language Fundamentals topic: v  d  e )

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 edit

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 edit

In the Java programming language, there are four kinds of variables.

  Code listing 3.9:
public class ClassWithVariables {
    public int id = 0;
    public static boolean isClassUsed;

    public void processData(String parameter) {
      Object currentValue = null;

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 static modifier (for example, isClassUsed). No other variables can have a static modifier attached to them. Because these variables are defined with the static modifier, 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 args variable in the main method. They are not attached to modifiers (i.e. public, private, protected or 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.
Test your knowledge

Question 3.5: Consider the following code:

  Question 3.5:
public class SomeClass {
  public static int c = 1;
  public int a = c;
  private int b;

  public void someMethod(int d) {
    d = c;
    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 and b are instance variables;
  • c is a class variable;
  • d is a parameter or argument; and,
  • e is a local variable.

Creating variables edit

A graphical representation of computer memory

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.
int a;

Assigning values to variables edit

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).
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:

  Code section 3.42: Variable declaration and assignment operation (on the same line).
int a = 10;

Grouping variable declarations and assignment operations edit

Consider the following code:

  Code section 3.43: Ungrouped declarations.
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:

  Code section 3.44: Grouped declarations.
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:

  Code section 3.45: Grouped declarations and assignments.
int a = 10, b = 20;
String c = "some text";

Identifiers edit

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 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 to Z and their lower-case counterparts a to z.
  • Numbers 0 to 9. However, numbers should not come at the beginning of a variable's name.
  • And finally, special characters that include only $ (dollar sign) and _ (underscore).
Test your knowledge

Question 3.6: Which of the ones below are proper variable identifiers?

  1. f_name
  2. lastname
  3. someones name
  4. $SomeoneElsesName
  5. 7days
  6. TheAnswerIs42

I can tell you that 3 and 5 are not the right way to do things around here, the rest are proper identifiers.

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: lastName is the best way of naming a variable.

Naming conventions for identifiers edit

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.
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:

  Code section 3.47: Time conversion.
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. 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 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.

Literals (values) edit

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.
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:

  Code section 3.49: Character.
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:

  Code section 3.50: Character list.
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:

  Code section 3.51: String.
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.