Java data types

Variables

Possibly the most important thing a beginner programmer needs to understand is the concept of the variable:

A named memory location used to store data, the contents of which can be changed.

Definition of a variable

Introducing a variable to a program for the first time is called declaring the variable. The purpose is to give the variable a name, and to reserve a space for the variable in memory.

To use the variable we give it a value by stating the variable name, following it with an equals sign, and then finally the value we want to store. We call this assignment and say we are assigning a value to the variable.

x = 12 (puts 12 into a variable called x)
i = 0 (puts 0 into a variable called i)
name = "Zara" (puts Zara into the variable called name)

The variable name always goes on the left hand side of the equals, and the value to be stored into the variable goes on the right hand side of the equals.

Mathematicians don’t like this idea of using = to assign a value, because in maths you are using equals to say that two things are already equal. Whereas in a program, you are saying “make the thing on the left equal to the thing on the right”. To make mathematicians happier, in some languages assignment is “:=” instead.

Data types

A major difference between Java and some other languages is the way variables are handled.

Java requires you to state when declaring a variable what type of data will be stored inside it. It will then only ever be able to store that type of data, although the value could change. This is why Java is called a statically typed language – datatypes are static which means they can’t change. Python and Javascript have dynamic types, which means the type of data in a particular variable can be changed, as well as the value.

Activity 1

Activity 1 – Data types matching. Choose the correct data type for each value. Drag items from the right onto the matching value on the left.

Activity 2

Activity 2 – Java datatypes. Study this document which discusses some of the decisions you will need to make when storing data in variables in Java programs.

Activity 3

  1. Write a program that declares and intialises each of the 8 basic Java data types.
  2. Use hexadecimal assignments in at least one of the statements.
  3. Use a System.out.print statement after each declaration to print the contents of the variable to the screen.
  4. Change the value of one of the variables you have already declared and printed, and print out its contents again.

Knowledge check

  • What is a data type?
  • Why is it important to understand data types, particularly when programming in Java?
  • What would be a sensible data type to store a single key press on the keyboard?
  • What would be a sensible data type to store the value of PI?