Create Software Components 

Using Java Level 2



Course Info




Java Demos




   Lecture 4

Data Types, Variables & Constants 

Read on for an overview of data types, variables and constants. 

Data Types

Literals & Constants

Variables and Variable Declaration

Scope of a Variable

Data Types 

Imagine you are filling in a form.  Perhaps you have to type in your name, your age and your massive bank balance.  The information or data you are entering is of different types.  Your age is a number, while your name is a sequence of characters.   Age is a different data type to name.

In Java and other programming languages, we have to be aware of different data types.  The table below lists the data types recognised by Java. 

Type bytes Minimum Value Maximum Value

Integer Types


1    -128    127


2    -32 768    32 767


4    -2 147 483 648    2 147 483 647


8    -9 223 372 036 854 775 808    9 223 372 036 854 775 807

Real Types


4    +/- 3.4 E+38    +/- 1.4 E-45


8    +/- 1.8 E+308    +/-4.9 E-324

Non Numeric Types

boolean 1  true, false

a single character

char 2

We can see that there are quite a few different data types.  


Integers are whole numbers such as 100, -20.  But Java likes us to be a bit more specific about our integers.  We can have a byte, a short , an int or a long .  They are all whole numbers but each type is restricted in how small or how large the number can be.  For example, a byte  can be a whole number between 128  and -127 but an int can have a wider range of values.

Why would Java want to partition whole numbers like this?  Think about memory allocation.  Numbers take up room in memory.  The larger the number the more memory space it would take up.  

You will see later that when we use variables, we specify the data type of the variable and we always choose the data type that will take up the least amount of room in memory.  For example, if I know that a variable will only have to hold a number between 1 and a 100, I would tell Java the variable was going to hold a byte data type.  Then Java would allocate 1 byte of memory for that variable.

    Real numbers

Real numbers are numbers with a decimal part like 10.50 , -0.0635 .  Again, Java likes us to be more specific about our real numbers.  We can have a float or a double.  A double can be a much larger or much smaller real number than a float.  A float takes up 4 bytes of memory while a double takes up 8 bytes of memory. 

    Non numeric Types

A character is a non-numeric data types.  'a ' and '5 ' are examples of characters.  You can combine characters into strings too.  "I am a string"  is an example of a string.

A boolean data type is something that evaluates to a true or a false. 

Literals & Constants 


Most programming makes use of literals:- a fixed numeric or non-numeric value.  When we use literals, the value is fixed in our code.  Look at the example code below.  How many literal values can you spot?

public class WordLiterals {
   public static void main(String[] args) {
      System.out.println("Hello " + "there.");
      System.out.println("I am a");
      System.out.println("string literal");



Hello there

I am a

string literal


 The code above has four literals of the string type:-  "Hello ", "there.", "I am a" and  "string literal". 

Note: --  a character is specified by surrounding it with the single quote symbol ' and a string is specified by surrounding it with double quote marks ".



We can use numeric literals too.  An integer literal would be a whole number such as 0, 100, -2000, etc.  A real number may be given in fixed or floating point notation such as 3.14 or 0.34E01.  

Can you spot the numeric literals in the code below?

public class NumLiterals {
   public static void main(String[] args) {







There is one problem with using literal values.  Programs like the ones above can only print to screen the exact values we typed into the code.  This is only useful if we know the exact value everything is going to be when we create our code.  What if we have a program that has to get some user input - say a number - and we need to do something with this number.  We don't know what the number is going in advance so we have to use a variable to represent this unknown number. 


What is a constant?  Imagine you are using a literal value in your code over and over again.  As an example consider the following:

public class aConstant {
   public static void main(String[] args) {
      System.out.println("My value of PI is 3.14");
      System.out.println("The area of a circle is 3.14 * radius^2");

I have used the literal value 3.14  more than once.  What if later on I decide to change that literal value to 3.141.  I would have to change my code twice in this case.  It would be even more tedious if my code had lots more references to the literal value  3.14.  Imagine 10 or 20 or more references - I would have to change each one.

A convenient way around this is to create a CONSTANT.  Examine the following code;

public class aConstant {
   public static void main(String[] args) {

      final double PI = 3.14; 
      System.out.println("My value of PI is " + PI);
      System.out.println("The area of a circle is " + PI + " * radius^2");

This produces the same output as the original code.  The difference is in the line

final double PI = 3.14 

 The final keyword tells Java that I want to create a constant value.  The name of my constant is PI and I have given it the value of 3.14

In the code above every time Java comes across the constant PI in the code,  it replaces it with the value 3.14 which I assigned to PI.

What if I decide to change the value of PI  from 3.14 to 3.141?   Now I  only have to change the value once.  In the code below I have changed the value of the constant PI from 3.14. to 3.141.   Every time Java comes across the constant PI in the code,  it will be now be replaced with 3.141.

public class aConstant {
   public static void main(String[] args) {

      final double PI = 3.141; 
      System.out.println("My value of PI is " + PI);
      System.out.println("The area of a circle is " + PI + " * radius^2");

By convention, constants names are UPPERCASE, so we can identify them in our code.  Java comes with a lot of pre-defined constants.  If you see a word in UPPERCASE, then it is probably a constant.

Variables & Variable Declaration

You can't do much with programs that just print on the screen literal values that we specify in our code.  What if we have a program that has to get some user input - say a number - and we need to do something with this number?  We don't know what the number is going to be in advance so we need something in our code that will represent this unknown number.
That's where variables come in...

    What is a Variable?

  • a variable can hold information for us
  • a variable can hold a value given by the user (from user input)
  • a variable can hold a value temporarily for us so we can use it later on in our program
  • a variable is a place in memory (#important concept#)

Every variable in a program is allocated it's own space in memory.  You can imagine variables as boxes (memory locations), where... 

  • The box has a name, (the name we give our variable)
  • The box holds a value, (the value of the variable -  which can change)

Here I have a variable called a which has a value of 1000 and a variable b with a value of 40 and c which does not have a value yet.  Perhaps the variable c will have an unknown value until the user runs the code and we get some user input.

    Declaring a Variable

We must declare a variable before we can use it.  The declaration specifies the name of the variable and what type it is.  Some examples would be

char ch;                  // declares the variable c of type char         

int index;             // declares the variable index of type int         

float balance;    // declares a floating point variable called balance

long distance;  // declares a variable distance of type long


The comma separator can be used to declare several variables of the same data type:

int index, count;    // declares two variables of type int

float average, balance;    // declares two floating point variables

Variables can be initialised (given a starting value) at the time they are declared by using the = sign.  We can only do this if we know the value of the variable when we declare it. E.g..

char ch = 'a';

int index = 10;

float balance = 100.56;

We don't have to give a variable a value at the time we declare it.  Once you have declared a variable, you can place a value in that variable after the declaration.  

int index;       // declares the variable

index = 0;   // assigns the variable a value

.......  //lots more code here that does something

index = 10;   // assigns the variable a value again

Once you place a value in a variable, you are not stuck with that value.  You can place a value in a variable more than once.  The code fragment above shows that although index was given a value of 0, later on it was given a different value of 10.

It is also possible to initialise variables using a previously defined variable.

int x1 = 10;       // declares and initialises the variable x1 

int x2 = x1;       // assigns the value of x1 to x2 

int x3 = x1 * x2;  // assigns the value of the of x1 times x2 to x3 


Note: --  Java does not initialise variables for us.  This means that when you declare a variable, memory space is allocated for that variable but until we give that variable a value it could have a strange value that happens to be in that memory space already.  

Make sure you initialise your variables before using them.  The compiler usually tells you if you have not initialised a variable.


    Naming a Variable

You can can call your variables almost anything provided they conform to the following rules:

  • the first character must be a letter, underscore _ or $
  • subsequent letters can be a letter, underscore, $ or number.
  • a variable name must not be a keyword; e.g. class, int, long, import, etc.

Also, by convention we name our variables so that:

  • the name describes what is represented by the variable.
  • the name starts with a lowercase letter.
  • if a variable is made up of more than one word the second and following words have their initial letters in UPPERCASE.

Here are some good variable names  (what information would you expect to find in each one?)

interestRate, xCoordinate, examMark, accountBalance, anAddress

The first four examples would hold numbers, the last would hold a string.
Here are some bad or invalid variable names:

20birds, letter, OXAE, m, #var, exammark.

Don't forget, Java is case sensitive and interestRate is seen as a completely different variable identifier from InterestRate.

    Why Declare a Variable?

Why do we have to declare variables.  There are two good reasons.  

The first is to tell Java the data type the variable is going to hold.  The variable will then be allocated enough memory to hold that data type.  If you declare a variable with a certain data type and subsequently assign the wrong data type to that variable, you will either get a compiler error or a run-time error which may crash your program.  E.g.

int index;       // declares the variable

index = 10.3; // assigns a floating point value to index - INCORRECT 

the above would cause the compiler to complain.

boolean result;  // declares the variable

result = 10.3; // assign a floating point value to result - INCORRECT 

the above would also cause the compiler to complain.  In this case, result is declared as a boolean and is allocated 1 byte of memory, but the next line tries to assign a floating point number to result, which requires 4 bytes of memory.  

The second reason to declare variables is to catch syntax errors, (errors in our written code). Here is an example:

int index, num;       // declares the variables

inex = 2;   

num = index;   

I have misspelled index.  If variable declaration was not required, then another variable called inex might be created.  My program would run incorrectly.  However, because variable declaration is required, the compiler would tell me that inex is not declared.  Then I would spot the misspelling and correct my code.

Scope of a Variable

It is important to be aware of the scope of a variable.  This means knowing where a variable exists or doesn't exist  within your code.

When a variable is first declared, it is allocated space in memory at the precise moment the declaration statement is encountered during program execution.  The variable exists in memory until the block of code within which it was declared is exited.  Then the variable is destroyed and the memory space allocated for that variable is deallocated.

As an example, consider the following code which calculates the area of a rectangle and displays a message in the applet window.

import java.awt.*; 

import java.applet.Applet;


public class Box extends Applet{

    int area;


    public void calcArea() {

      int length = 100;

      int height = 50;

      area = length * height;



    public void init() {




    public void paint (Graphics g) {

      g.drawString ("The area of my rectangle is " + area, 0, 40);


The class Box has three variables, area, length and height. However, the variables length and height are local to the method calcArea.  In other words, these two variables are created when the calcArea block of code is executed and then they are destroyed when the method is finished executing.  

If I tried to use one of these variables outside the calcArea method I would get an undeclared variable error message from the compiler, e.g.

public void paint (Graphics g) {

    g.drawString ("The area of my rectangle is " + area, 0, 40);

     g.drawString ("length is " + length, 0, 80); //INCORRECT


I cannot reference the length variable in the paint method because it is declared in the calcArea method and only exists in the calcArea method.  When the paint  block of code is executed, the calcArea has finished executed and length has already been destroyed.

However, the area variable is declared in the class block of code called Box.  So this variable is created as soon as an instance of the class Box is created and it is destroyed when the Box instance is destroyed.

This means that all the other methods can reference the variable area even though area is not a local variable of these methods. So...

  • length is a local variable belonging to the calcArea method
  • height is a local variable belonging to the calcArea method
  • area is an instance variable belonging to the class. 

Here is my HTML code for displaying the Box applet



<Title> Box Applet </Title>



<p ALIGN="center" ><font face="Times New Roman" size="4"> Box Demo </font></p>

<p ALIGN="center" <Applet code="Box.class" width=200 height=100 ></Applet> </p>



Have a quick look at the Box applet running.

That is folks!!

Now try the Variables & Constants exercise


  Site Home 

Java Home   


Course Info





Scheme of Work





Learning Center

Web Materials


Java Demos



Lecture Materials

Tutorials & Notes





Site Home


Unit Home

ADR 2002