Variables in Java

Java Variables

We have become familiar with what data is, and what are the different types of data that we can have. So, now, it’s important for us to know that there can be situations in which we might need to store whatever data we use inside the program.

For this purpose, we are going to make use of the variables. You can think of variables as some containers for storing our data(information). For different types of data, we have a different type of container. Let’s understand this thing with the help of an example – let’s say you are putting different things into different containers.

So we have salt, sugar, wheat, barley, etc. Just imagine that if we keep all the grains in one container, like salt and sugar in one container, it will not be good right? Just like we have different containers for different spices or something, similarly here we create different variables for storing different types of data.

I know this example does not relate directly, but what I mean to say is that the container created for an integer is supposed to store an integer. That’s it.

Variables are just some storage units for data, which may/may not change throughout the execution of the program.

So, in order to store some kind of data/information inside our program, we need to create some sort of variable. The variable has to be of the same type of data that you are going to store.

So, first, let’s see how can we create a Variables in Java. Also, we have to look at how we can access the variable once we have created that. Well, it’s simple, we just got to use the name that we are going to give to the Variables in Java.

You can create a variable just by doing something like this –

datatype variablename;

You can make use of the data types that we discussed earlier. So, you have to specify the data type of the variable. This specifies what type of data is that variable going to hold. So, if you want the variable to hold an integer value, just create a variable of type int.

The above is just a variable creation/declaration. If you want to initialize (store some value into) the variable that you have created, you just need to do the following –

int number = 1;

Here, we have created an integer type variable with a name as a number and we have also assigned the value 1 to it. So, the above variable is an integer variable so, it is meant to store some integer value. Notice here that the number is a Variables in Java that we have created and the 1 is the value that variable is given, that is, the variable number holds the value of 1.

You can also do something like declares the variable first, and then assign the value to it afterward. This can be just done by doing the following –

int number;
number = 19;

Here, we have first declared the variable number with type int, and then afterward in the program, we are assigning some value to it. By assigning it, we are just storing some value in it.

The variable is going to have some name, and it can be anything, but there are some rules we need to follow when we are creating variables. These names are something we are going to use to access the variable once it is created, and they usually resemble the value they are containing.

For example, if you want to create a variable to store salary, then you can name it as salary, or if you are creating a variable for storing the name of some person, then you can name that variable as something like name, or person_name instead of naming it as a or b or something meaningless. In short, the thing is that when you name the variable, you can name them in resemblance with what they do contain, along with certain rules that we need to follow.

Rules for giving a name to some Variables in Java –

  • The name of the variable should not be a keyword. We know a little bit about keywords from our previous concepts, right? So, it is clear that the keywords have some special meaning and they should not be used for anything else anywhere. For example, the int keyword is used usually when we declare some variable of type int. Now, if you use the int keyword as the name of the variable, the compiler will get confused. This is like – “Hey… this word is used for something else … you cannot just use it anywhere you feel. You have some restrictions here!!”.
  • The name of a variable can contain alphanumeric characters, and we can also use the special characters – dollar($) and underscore( _ ) in the variable name. By alphanumeric, I mean that the variable name can contain alphabets(capital or small) and digits (0 – 9) and the only special characters allowed are dollar sign and underscore. There is some twist again in this thing, which leads us to the next rule which says …
  • The first character of the variable name should not be a number.
    By this, we simply mean that we can use the digits in the variable name, but not at the start. So, if the variable is given a name as 1name, it is invalid. However, if the variable is named as name1, then it is fine. We will again deal with some valid and some invalid examples ahead.
  • Blank spaces are not allowed in the variable name.
    Well, this is pretty straightforward. We simply cannot use spaces in a variable name. But if you want to separate different words in the variable to define their meaning, you can use an underscore. For example, some variables can be named like this – student_name. This perfectly defines the meaning of what we are trying to do by creating this variable.
  • The variable names are case-sensitive. This means that if I create a variable as count, and another variable as Count, both the variables will be treated as different.

So, these are some of the rules that we need to follow while we declare variables. You don’t have to remember these rules forever. With practice, it will become your habit to always create a variable that is valid. Again, there is one more rule, which is not actually a strict rule, but still, it’s good if you follow this. Here is the rule –

  • If you are creating a variable, name it in such a way that it conveys what it is being created. For example, if there is some variable that you are creating to store salary, then create it with the name of salary, or employee_salary, or something which makes sense, which defines what the variable is going to hold, instead of creating the variable with some name like a or b or something meaningless. This makes our program slightly more readable, which is very important.

So, whenever we need to store some data in our program, we make use of Variables in Java.

Right now we are discussing variables, and we have come this far, so also let’s discuss some kinds of variables… and basically understand them.

  • Instance variables(Nonstatic variables): Remember when we discussed, in brief, the static keyword? Here, the title says that the instance variables are nonstatic variables. Let’s understand what this needs to say. First let’s understand what will static do to a variable(By the way, this is going to be seen in the concept of the static variable itself ahead, but here we need to discuss it, in brief, to smoothly move ahead). So, coming back to what will static do when used with a variable, let’s explore this thing.

So, basically, when a variable is static, only one copy is created for that variable, which will be shared by all the objects. Similarly, we are right now talking about nonstatic Variables in Java, so we are expecting exactly the opposite thing here. If you try to define what an object is, you will find most of the time that the object is an instance of the class. This clears it all. The name instance variable does means that this particular variable is being created for an instance, so the instance variable would be unique or different for different objects or let’s say instances. For example, let’s say we have a class Car. So do we have objects of class Car? If we consider that price is some Variable in Java which is probably an instance variable in this case, then each car can have a different price right? So, this variable is there for that particular instance. Let’s move on to the next type, the static variable.

  • Class variable(static variable)- We have had a discussion about what happens when a variable is declared static. It will not be there for every instance. There would be only one copy created and shared among all the objects of the class. This makes it a class variable. Let’s consider a very simple example for this type of variable. There is a class of students who belong to the same college. So, for every object of the class student, i.e for every student, the college name is going to be the same. So, instead of making an instance variable for every student object, we can just make one class variable, which can be shared among all the student objects. You can have many other related examples like for all the employees working for one company, the company name is going to be same, or something like that.

Now let’s discuss constants. As the name suggests, the constants are something whose value won’t change throughout the program. At times, we require to create constants in our programs. Like, if we are writing a program to calculate the area of a circle, we are going to have a constant value pi, which has a value of approx 3.14.

Now, if we store this value into a regular variable, it can be changed at any point in the program, which we would never want to happen since the constant does not change.

So, we need something, whose value cannot be changed once we create it in the program, and this is where the constants come into the picture,

To create a constant, you have to create Variables in Java and add a final keyword before it. Here is an example –

int count = 8;
final int age = 10;

So, if you try to change the value inside age now, you won’t be able to do it. But if you do the same thing with the count, you can comfortably do that.

Now, let’s consider an example case of why would you want to declare something as constant. Let’s say you are writing a program to calculate the area of a circle, and you have declared the value of PI inside a variable with the name pi (because now you too think that we should give meaningful names to Variables in Java, and of course, those names should not be keywords)But the thing is that if you do not declare the variable as constant, at any point, the value of the variable pi can be manipulated, like in the below code –

package com.company;
public class Main {
public static void main(String[] args) {
float pi = 22/7f, radius; // we created two variables – pi and radius of type float
// pi contains the value 22/7.

radius = 3.2f; //the radius holds the value 3.2.
pi = 3;
System.out.println(“area = ” +pi * radius*radius);
}
}

The output for the above code comes out to be –
area = 32.182858

But the thing is that this is not the correct or the expected output. This has happened because the value of pi was manipulated in between. So, to prevent such types of things, we can declare them constant.

because once it is constant, it cannot be changed. Here is the below code which fixes that –

package com.company;
public class Main {
public static void main(String[] args) {
final float pi = 22/7f, radius; // we created two variables – pi and radius of type float
// pi contains the value 22/7.
radius = 3.2f; //the radius holds the value 3.2.
pi = 3;
System.out.println(“area = ” +pi * radius*radius);
}
}

Running the above code will throw an error since we are trying to assign some value to the final Variables in Java. You receive some error messages like –

java: cannot assign a value to final variable pi

In the above discussion about data types, we discussed a range of data types. The thing is that if you try to store some number that is greater than the maximum value for an int type Variables in Java as an example, then the such condition is called overflow, in which we are trying to fit in a number that is actually out of bounds for that much number of bits. The same is with the negative number in the range, but this is called underflow this time. So, it is important to choose the data type wisely.

For example, if you want to store some very long integer value inside a variable, use the long data type instead of int, since you know that it may surpass the max value for integer causing overflow, and ending up with an unwanted value.