Introduction to Variables and Primitive Data Types

A variable is a named memory location that can be assigned a value while the program is running. A data type describes the sort of data that a variable will hold. This tutorial will introduce you to one of the fundamental Java data types - the primitive data types.

The following is a list of all eight of the primitive data types. This tutorial will focus on just the int and double data types.

  • byte · 8-bit integer, -128 to 127
  • short · short integer, -32,768 to 32,767
  • int · integer, -2147483648 to 2147483647
  • long · long integer, -9223372036854775808 to 9223372036854775807
  • float · single-precision floating point
  • double · double-precision floating point
  • boolean · true or false
  • char · unsigned Unicode character


Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md Variables
C:\Java>cd Variables
C:\Java\Variables>Notepad Variables.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


/*
    Simple program to convert miles to kilometers
    We create a variable called miles and assign it an int data type and initialize it to 0.
    We create another variable called kilometers and assign it a double data type and initialize it to 0.
*/

class Variables {
    public static void main(String args[]) {
        int miles = 0; // (data type int) (variable miles) (assignment operator =) (value 0) (semicolon)
        double kilometers = 0.0d; // (data type double) (variable kilometers) (assignment operator =) (value 0.0) (semicolon)
        double distance; // (data type double) (variable distance) default value is 0.0d;

        miles = 11; // change the value of the miles variable 
        kilometers = 1.609344d; // change the value of the kilometers variable
        distance = miles * kilometers; // multiply variable values using the multiplication operator (*) and store the value to the distance variable

        System.out.println("There are " + distance + " kilometers in " + miles +" miles." );

    }
}

Now switch back to the command prompt (CMD) and type in javac Variables.java and press Enter.
Now type in java Variables and press Enter.


C:\Java\Variables>javac Variables.java
C:\Java\Variables>java Variables
There are 17.702784 kilometers in 11 miles.


Final thoughts

Data types define what type of data a variable can contain. The = assignment operator will store a value to the variable. Java supports arithmetic operators such as +,-,*,/ and more. The int data type has a default value of 0. The double data type has a default value of 0.0d;


Tutorials