KnowledgeBoat Logo

Data Types & Variables

Declaring & Initializing Variables

ICSE Computer Applications


In a programming language like Java, a variable represents a memory location through a symbolic name which holds a known or unknown value of a particular data type. This name of the variable is used in the program to refer to the stored value.

In Java, you must first declare a variable before using it. The simplest way to declare a variable is this:

type variablename;

type can be any of Java’s primitive data types or the name of a class or interface. We learned about primitive data types earlier in this section. Class and Interface types will be covered later in this course. variablename is an identifier hence all the identifier naming rules apply to it.

Here are some examples of declaring variables:

int mathScore;

boolean promoted;

The first example declares a variable of data type int and names it mathScore. The second example declares a variable of data type boolean and names it promoted.

These two variables mathScore and promoted which we have declared just now are still uninitialized. Don’t get overwhelmed by this concept of uninitialized variables, it is very simple. It just means that we have not assigned any value to these variables yet. As we have not assigned any value to these variables so naturally their values are unknown. Now an important thing to remember here is that inside a method Java doesn’t allow you to use a variable without initializing it. Let me show you what I mean.

mathScore is a variable declared inside the method demoVariable. When I try to print the value of mathScore, I am getting an error. The error says, variable mathScore might not have been initialized. I need to first initialize a variable before I can use it. Initializing a variable is very simple and straight forward. Just assign a value of the same data type as the variable. Once I initialize mathScore with the value 10, the error goes away and compiler is happy again.

I am repeating it once again, the value of a variable declared inside a method is unknown. You must initialize your variable before using it. Trying to use an uninitialized variable will result in an error.

You can combine declaration and initialization of a variable in a single line like this:

int mathScore = 0;
boolean promoted = false;

You can declare and/or initialize multiple variables of the same type in a single line like this:

int num1 = 10, num2 = 20, num3, num4 = 40, num5;
byte first, second = 2;
double pi = 3.14159, e, sqrtOf2 = 1.41421356237309;
PrevNext