Java Variables


In this tutorial, you will learn all about Java variables and data types. Suppose you are writing a program that adds two numbers. First of all, you need to define where these numbers should be stored. Then, you need to define what type are these numbers. They could be simple integers or decimal numbers. Therefore, a type should be given to these variables. Well now, let's get started.

Primitive Data Types

These are used to define a variable and its type. They are keywords in Java and they are listed in the table below so skip down and read the table.

border="1" style="text-align:center">
Keyword Description Range
byte Byte for storing a small number -128 to 127
short Short integer for storing a short number -32,768 to 32,767
int Integer for storing a number -2,147,483,648 to 2,147,483,647
long Long integer for storing a large number -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float Floating point for storing a decimal number 1.4E-45 to 3.4028235E38
double Floating point for storing a large decimal number 4.9E-324 to 1.7976931348623157E308
boolean Boolean value for storing true or false true or false
char Character value for storing a character Letters and Symbols
String String value for storing a word or sentence Not applicable

Now check this code to know how to create variables.

public class Variables
{
   public static void main(String args[])
   {
      byte byty = 120;

      short shorty = -4000;

      int inty = 1000000;

      long longy = 10000000;

      float floaty = 2.5;

      double doubly = 3.33333;

      boolean booly = true;

      char chary = 'M';

      String stringy = "Java Judge";
   }
}

Note: a String is not a primitive data type but we consider it here because it is used a lot.

Congratulations

You now know how to create a Java variable. Move on to the next tutorial but first read the important notes below.

Important Notes

Naming a variable

A variable could have any name, int x, double y, short iceteaandbanana. However, a variable name cannot start with a number, cannot be a Java keyword, and cannot contain symbols. For example, int 123a, double System, float !@# will result in errors.

Multiple Variable Definition

Many variables can be defined on the same type can be defined on the same line using the comma ",". For example, int x=0, y=10; is perfectly correct.

Give Meaning to Variable Names

You may have noticed that we named our variables in this tutorials with a bunch of random names. However, when naming a variable, please choose an understandable and meaningful name so that you can know what the variable is used for.