Data Types

Like all programming languages Java allows data to be stored in variables. The term variable has its origins in the idea that the contents may vary, i.e. At the start of a program variable may contain 10 and later it might contain 99.

Behind the scene a variable is a name or label given to a piece of memory. That name can be used to refer to whatever value is currently stored in the memory location. It is a little like the use of symbols such as X or Y in algebraic equations.

There are rules for what names can be given to variables, but you are generally safe if you stick to names containing all letters, and preferably a name that means something to you. Thus if you are storing the height of an image you are better off calling it Height rather than z or p. There is a convention amongst some programmers to add letters to variables to indicate the data type. Thus if the height of an image is being stored in an integer you might call a variable iHeight.

All variables must be given a data type when they are created. There are some languages sometimes called “weakly typed” languages that do not require this. For example in the PHP language used to create web pages there is no concept of assigning a type to a variable. Although this can seem very convenient it can cause problems where people misspell a variable name and the language assumes it is an attempt to create a new variable and so the programmer is not warned. The requirement to give a type to all variables is considered to be a feature that makes Java "safer", i.e. It is not so easy to create bugs.

You can create a variable ready for use elsewhere or you can assign a value to it at the same time you create it. Here is an example of creating an integer (int) variable without assigning a value.

int i;

This tells java to create a variable called i with the type int. An int is a type that can store the values between approximately plus or minus 2 billion and has no fractional part (decimal point values).

The other form of creating a variable is

int iHeight=10;

This does the same as the previous example, except that it assigns a value to the variable at the same time as it creates it. Note that in both examples the line ends with a semi colon. This indicates the end of the statement to the compiler. Sooner or later everyone misses off the semi colon or places a colon or similar character by mistake. Luckily the error messages from Java give a good indication what the error is.

Last modified: Thursday, 24 July 2014, 2:54 PM