Variables in Java

In this tutorial, we will learn about variables and their types in Java and how to declare them by using a proper syntax.


Variables in Java

Variable in Java programming language is a storage location that contains data of any sort. We give storage area or variable unique name to the variables so that we can easily identify them later on.

Types of Variables in Java

  • int: stores integers only, non decimal values.
  • string: stores text inside double quotations.
  • float: stores float values that contains decimal
  • char: stores just one character like ‘a’ or ‘c’.
  • boolean: stores only true or false values.

Recommended Books



Syntax of Declaring a Variable

type of variable = value;

Declaring a Variable in Java

It is pretty simple to declare a variable in Java:

int num = 10;

In the above code, num is a variable that has a data type of int. That means num can only hold integer values. We will be diving deeper into the data types in java throughout this tutorial.

Let’s look at another example:

int num;
num = 10;

In the previous example, we have designated a value to the variable while identifying its data type, but you can also define the data type and declare a variable without designating the value. Later on, you can designate any value while just picking up the variable name.

int num = 10;
num = 20;

You can change the value that it is designated to a variable in your program.

Scope of a Variable in Java

It is important to to use the same data type in a predefined variable and not outside the scope. Now what do we mean by variable scope?

Let’s see if a variable has a data type int designated to it, then we cannot change it to float.

int num = 10;
float num; //This is wrong

Rules of Declaring Variables in Java

Like any other programming language java also has its rules for declaring variables, here are a few to keep in mind:

  • Whenever you are declaring a variable, make sure that you are not disturbing the case sensitivity of it.
  • You can declare the variable name in Java starting with the $ sign and underscore ( _ ). But make sure that you are not padding whitespaces between the variable name.
  • An ideal way to declare a variable name is to always start it with a lowercase letter.
  • Try to use one word variable name rather than single letters or else you may forget the declared variable names.
  • If a variable has two joined words, make sure that to capitalise the first letter of the second word. For example, numScore.

We will learning more about the data types in Java in the upcoming tutorials.