Skip to content

Variables and types of data

What is a variable?

A variable is a programming construct which is composed of three basic attributes: symbolic name,storage location and value which, when you are browsing the source code, helps refer to it's actual source value or the physical storage location. The name is used to identify the variable which is why it is often called the variable identification. The variable is stored in the computer memory and it is identified by the address and data length. It's value corresponds to it's storage location.

Java identifies two phases of variable creation:

  • Declaration - we create the variable name and set up it's type.
  • Initialization - we assign a value to the variable.

Variable declaration

An example declaration of a variable can look like this:

private int number;

Here we have declared a whole number of a private type.

Similarly, the process of initializing a variable can be presented as follows:

number = 5;
The variable 'number' has been assigned the whole number of 5.

A more general declaration of a variable can be presented as such:

{access type} {type of variable} {variable identifier}

where:

  • access type - these are called the access modifiers (optional)

  • type of variable - describes the type,structure and value that the variable can take

  • variable identifier - the name which helps identify the given variable

Based on access privileges we can distinguish:

  • "Global" variables within a class - this class operates within the area of the class where it has been declared:
class ExampleClass {
    int myGlobal = 12;
    void someMethod() {
        // we can use the myGlobal variable
        System.out.print("My global variable: " + myGlobal);
    }
}
  • "Local" variables with a method - the variable is accessible within the method where it was declared:
class ExampleClass {
    void someMethod() {
        int myLocalVariable = 5;
        System.out.print("My local variable: " + myLocalVariable);
    }
    int myGlobal = myLocalVariable; // Error - myLocalVariable is not visible outside of the method where it was declared
}
  • "Local variables" declared within [conditional statements] (conditional_statements.md) or as a counter in [loops] (loops.md), such as:
class MyExampleClass {
    void someExampleMethod() {
        if (someCondition) {
            int a = 1;  
            // local variable declared within a conditional statement - it is visible only within such an instruction
        }
        for (int i = 0; i < 10; i++) {
            // the variable 'i' is only visible within the loop
        }
    }
}

Final variables

A final variable cannot change it's value once it has been set. When we declare the variable we add the key word 'final' . An example is provided below:

final int finalVariable = 25;
The next code snippet will result in a compilation error since we will be trying to change the final variable value:

private void finaVariableSample() {
    final int finalVariable = 123;   // final variable declaration and Initialization
    final long anotherFinalVariable;
    finalVariable = 12;             // the attempt to change the final variable will result in a compilation error
    anotherFinalVariable = 12345L;   // correct Initialization of a final variable

}
Final variables behave differently since they refer to an [object] (classes_objects.md) and not primitive types as seen above.

The key word 'final' means we are unable to change the value of it's reference but we can change the object state for instance by using such a definition of a class:

public class SimpleClass {
  private String name;

  public String getName() {
    return name;
  }

  public void setName(final String name) {
    this.name = name;
  }
}

We can execute this code:

public static void main(String[] args) {
  final SimpleClass simpleClass = new SimpleClass();
  simpleClass.setName("Michael");   //we are able to change the state of the object
  simpleClass = new SimpleClass();   // compilation error, we are unable to change the reference
}

Types of data

What are types of data?

Data types refer to the type, structure and the value range that a given literal,variable, final, argument, result of a function can take

Types of data in Java

We distinguish the given types of data in Java:

  • numeric types
    • integer values (aka whole numbers)
    • floating points
  • logic data types
    • true
    • false
  • char data types
  • string data types (aka text data types)

Java is a static based language as such:

  • variable types are assigned during the program compilation.

  • it is easy to detect errors during compilation.

  • it is imperative to declare the types of variables before initializing them.

Given the rules provided above the application seen below will result in a compilation error:

String myVariable;
myVariable = 2;

Whole numbers

The types representing whole numbers are listed below: * byte * short * int * long

byte

The 'byte' type assigns 1 byte (8 bits) into memory and we can use it to write numbers ranging from -128 to 127 (2^8=256).

An example of byte declaration is given below:

byte myByteNumber = 125;

short

The 'short' assigns 2 bytes (16 bits) into memory and we can use it to write numbers ranging from -32768 to 32767.

An example of short declaration is given below:

short myShortNumber = -22556;

int

The 'int' type assigns 4 bytes into memory and we can use it to write numbers ranging from -2147483648 to 2147483647.

An example of int declaration is given below:

int myIntNumber = 1230000;

long

The 'long' type assigns 8 bytes (64 bits) into memory and we can use it to write numbers ranging from -2^63 to (2^63)-1 which is really a lot. In reality they are mostly used for identity occurrence in databases. When we declare logs we add the prefix 'L'. We can also use the small letter 'l' but for readability we should use the big 'L'.

An example of a long declaration is given below:

long myLongNumber = 254555455672L;
There are also the non-primitive data types or reference data types which correspond to primitive types. They enable the use of methods which help automate repetitive functions. Java does not have or use the 'Unsigned' type (with only positive values) and when we exceed the maximum value of a given type we move to it's negative range.

Floating point numbers

Floating point numbers consist of:

  • float
  • double
float

The 'float' type assigns 4 bytes into memory and we can assign numbers with accuracy of maximum 6 or 7 decimal spaces. When we declare the numbers we use the prefix 'F' or 'f'.

An example use of float:

float myFloatNumber = 12.0005f;
double

The 'double' type assigns 8 bytes into memory and we can assign numbers with accuracy of maximum 15 decimal spaces. When we declare the numbers we use the prefix 'D' or 'd'.

An example use of double:

double myDoubleNumber = 12.000000005d;

Important: We distinguish the whole from the floating-point by using a dot not a comma separator. We also need to remember that floating-point number types which represent values using mantissa and exponent (e.g. float or double) should not be used for financial calculations where accuracy is valued, because we are unable to calculate exact values of all numbers. In such case approximate values are used. One class that solves this issue is BigDecimal. There is another class BigInteger which is seen as a reference for whole numbers and can show all ranges of numbers.

Logic data types

Java has only one logical data type 'boolean' which takes two possible values:

  • true, where something is true
  • false, where something is false

We often use boolean values in [conditional statements] (conditional_statements.md) and [loops] (loops.md). We can therefore check if a given instruction can be executed or not.

An example use of a logical type:

boolean myFalseValue = false;
boolean myTrueValue = true;
boolean myBooleanValue = myFalseValue && myTrueValue; // myBooleanValue will have the value 'false'

Char data type

The char data type is represented by 'char' in Java. We declare single characters by use of single quotes like this: 'a'. It is used to represent single characters using Unicode encoding.

A sample declaration of char can be seen below:

char signValue = 'y';

We can also represent special characters but they have to be preceeded by a '\' character such as:

  • \t - tab
  • \n - new line
  • \r - carriage return

An example use of the '\t' char:

char tab = '\t';

String type

The 'String' type is used to represent text using Unicode. It is of immutable type and it's state can not be changed. It is also a type of object (you can read more in further chapters). It's value is represented by double quotes as seen in the example below:

String someText = "This is a simple text.";