Published on

Java Variables and Basic Data Types

  • avatar
    Jaden Tang

Java is a powerful programming language known for being object-oriented. As a result, it is easy to create data types, or classes, that are instantiated as objects. The object-oriented nature of Java makes it easier to organize and structure code. However, we first need to understand basic Java variables and their types.

Declaring Variables in Java

In Java, a variable is a container for storing data values. Unlike some programming languages, you are required to declare the type of a variable, and this type cannot change. To declare a variable, first specify the data type followed by the variable name.

int test;

(Remember to put a semicolon at the end!)

Initializing Variables in Java

After creating a variable, it cannot be used yet. We must first give it a value.

test = 5; // set the variable test we declared above to 5.

Instead of declaring a variable, and then initializing the variable later, we can also directly declare and initialize variables.

int test2 = 10;

In the example above, we declared a variable called test2 with a type of int and value of 10.

Reassigning Variables in Java

To set a new value to a previously declared variable in Java, we use the same syntax as initializing a declared, yet not initialized variable. To do so, we can set the variable to the new value.

test2 = 5;

Data Types

There are many different types in Java, and for good reason. Not all data is the same. For example, you can do multiplication with numbers but not with text.


There are many numerical types, each with its limitations. Some can only store integer values, meaning they cannot have decimal points.

  • int (stores from 2-31 to 231 - 1)
  • short (stores from 2-16 to 216 - 1)
  • long (stores from 2-63 to 263 - 1). To declare this special type of number, we should add L to it as a postfix: long z = 100000000000L. Otherwise, we will get a compilation error, as 100000000000 is too big for an int.

Other types can store decimal points. These are:

  • float (stores from 2-31 to 231 - 1). This stores up to 10 -7 precisely.
  • long (stores from 2-61 to 261 - 1). This stores up to 10 -15 precisely.


  • String: stores any combination of Strings, characters, ints, longs, shorts, and most data types.
  • char: stores exactly one character, encoded/decoded using ASCII values. This means you can set a char to an int and vice versa.


  • boolean: this is also known as a bit, as there are exactly two values: true and false.


Understanding data types in Java is necessary to code and create your own data types, which will be explained in a future blog post. Happy Coding!