Categories
java

Java Variables: Simplified Guide For Beginners

‘Java variables’ is one of the most basic and important topics every Java beginner must learn.

This tutorial has everything you must know about the Java variables that will help you master the Java programming language faster and better.

Previous Topic: Write Your First Java Program

Next Topic: Java Data Types

Page Contents

Java Variables

A variable as the name suggests is something that varies/changes.

Let’s take the case of you as an example.

You are an object in this world. Your age is one of your properties. It changes every year. That means your age is a variable.

That might not be the case for your name. Right?

Once your parents give you a name, most probably you will never change it.

i.e., your name is a constant, which is just the opposite of variables.

So, an object’s properties comprise variables and constants.

This is the same case for Java objects.

Java variables are the properties of the Java objects to hold values that you can change/update at any point.

Declare Java Variables

Before learning to declare Java variables, Let’s see what the term declaration means in Java (in case you don’t know).

Declaration Statements

Declaration statements are used to mention the existence of a class, method, variable, etc in Java. You don’t define its value or purpose. You just say that it exists. That’s what declaration means in Java.

When declaring Java variables, you must mention two things.

The first one is the variable’s type (data-type). This means what type of value the variable can hold. The type can be a digit, a string, a single character, etc.

The second one is the name of the variable. Whenever you want to access a variable, class, or method you access it by its name in Java. Just like we identify other people or things using their names in the actual world.

Since the names are for identifying a particular item, we call them Identifiers in Java.

The Java naming convention suggests you enter the Java Variable names in the camel case format as standard.

You can use single letters like x, y, z, or lengthy names like myFirstGeekyPointVariable, etc.

It’s always better to choose meaningful words as variable names. Not too small, not too big. Use medium length names to improve code readability.

Now, Let’s see how an actual Java variable declaration statement looks like.

data-type variable-name;

There are many pre-defined data-types in Java. I have listed some of them below.

  • int – store numbers without the decimal part.
  • float – store numbers with the decimal part.
  • char – store a single character.
  • String – store a sequence of characters.

Don’t worry.! You can learn more about the Java Data Types in the next tutorial.

For now, let’s use the above-given data types to declare our Java variables.

You can see some examples below.

int age;

float height;

char gender;

String name;

It is possible to declare multiple Java variables on the same line as you can see below.

int x, y, z;

float a, b;

String firstName, secondName;

Use a comma to separate each variable.

Even though it is possible, I do not recommend this approach. The best practice is to follow the “one line – one declaration” approach as below.

int x;

int y;

int z;

Initialize Java variables

Initialize Java variables means assigning values to them.

You can initialize Java variables at the time of variable declaration or after the variable declaration.

Initialize Java Variables At Declaration

Below given are some examples of initializing at declaration.

int age = 27;

float height = 5.10;

char gender = ‘M’;

String name = “Geeky”;

int q = 113, r = 114, s = 115;

Initialize Java Variables After Declaration

String fruit; // Declaration

fruit= “Apple”; // Initialization

You can initialize a Java variable any time you want after the declaration.

There is no restriction on the number of times in initializing Java variables. You are free to initialize Java variable n number of times.

When you assign a new value to your variable, the old value is gone forever unless you have stored it in any other variable or a database.

The new value becomes your variable’s value;

For example:

fruit = “Orange”; // Initializing again

If you wish to get the old value, then you will have to re-initialize it.

Now let’s create a small Java program to understand the Java variables better.

public class Human {
int  age;

public static void main (String[] args) {

int localVar = 0;

}
}

In the above program, there are three Java variables: age, args, localVar.

These variables are not declared in the same place as you can see. Java variables have unique characteristics according to where you declare them.

let’s discuss in detail.

First, let’s take the case of the first variable age.

The variable age is a class-level-variable.

Class Level Java Variables

Class-Level is the area outside the sub-blocks of a class. Methods are examples of sub-blocks.

 

At the class-level, you can do only two things.

  1. declare variables/ constants
  2. Initialize variables/ constants at the time of declaration

You can’t write any other program-statements at the class-level. If you do, the Java compiler will identify and show it as an error.

The variables you declare at the class-level are known as the class-level variables.

You can define the visibility of the class-level variables as you want. For example, you can make it public, private, etc.

The minimum visibility you can give to a class-level variable as the name suggests is ‘class-level’, i.e., inside its class.

You can initialize class-level variables at the time of declaration. At the class-level, Java does not allow initializing variables on the next lines after the declaration.

 

If you leave it un-initialized, a default value will be assigned to them.

There are two categories of class-level variables in Java.

  1. Instance variables
  2. Static variables

All the class level variables you will create belong to either of the above categories. This is the same case for everything inside a class. The properties, methods, etc in a class can either be static or non-static.

Since this guide is for the Java variables, let’s focus on that now.

Instance Variables

Instance‘ is just a term used to mention a specific object.

Instance variables are the variables of the instances/objects of a class. All the class-level variables you have seen above are instance variables.

Why they are called instance variables?

This is because each instance/object of a class will have unique memory areas for its instance variables. i.e., each instance has a copy of the instance variables declared in the class.

You can create n number of objects of a class in Java. So if you create 100 objects, then you get 100 unique memory areas for the instance variables. You can add, update, remove the values of the instance variables of each object independently.

For example, Imagine, you have a class called ‘Dog‘. You create an instance variable ‘String dogName‘. Now you create two objects ‘dog1, dog2‘ of the ‘Dog‘ class.

These objects denote two different dogs. Right?

So you must be able to give two different names to the dogs. This is what instance variables use for.!

you can give as below:

dog1.dogName = ‘Togo’;

dog2.dogName = ‘Max’;

 

The ‘dogName‘ of ‘dog1′ holds the reference/address of the memory location where the value ‘Togo‘ is stored. This is the same case for the ‘dogName‘ of ‘dog2′.

Note: The above image is just for you to understand the concept. The values of the variables will be in the memory, and the variables will have the address of the memory location to access the values.

Now let’s move on to the static variables.

Static Variables

static is a Java keyword. You can check out this previous guide link to get the basic idea of the static keyword. You can create static variables in Java by adding the static keyword at the time of variable declaration.

I have given some examples below:

static int x;

static char c;

static String str;

If you have read the previous topic, you might know that we can access static variables, methods without an object.

This is because the static items belong to the class, not to the objects of the class. Therefore, static variables are also known as class variables.

Static variables have their own static memory. So even if you create 100 objects of your class, a static variable in your class will have only a single memory allocated to it.

If you assign a value to your static variable, that value is the only value of your static variable throughout the entire program. If you change that value, you are literally updating it for the entire program.

Let’s understand it better with a small example.

Imagine that you have a static variable in your class.

You assign a value to the static variable and you use that variable in 100 places in your program. In all those places, the static variable holds the same value no matter what.

Then you update the value.

Now your static variable holds the new value. Not just in one place, but in all the 100 places you use it before. That’s the difference between a static variable and an instance variable in Java.

 

In the above image, there are two dogs with two different names. But the owner is the same for both the dogs. Even if you create 100 dogs, the owner will always be ‘Sara’ until you change it.

Since the class-level variable ‘owner‘ is static, you can’t assign different owners to different dogs. To do that, you have to make the variable ‘owner‘ non-static.

Another most important point is that if you want to use a class-level variable inside a static context of your class, you have to either make the variable ‘static’ or create an instance of the class.

Static Context

Any block of code that is declared as static is a static context. Static methods are examples of static contexts.

The Java main method is a static context because we declare the main method as ‘public static void main (String[] args)’ in Java.

Why non-static variables cannot be referenced from a static context?

The static elements belong to the class. The memory allocation of static variables/methods happens at the time of class loading. There are class loaders in Java that loads a class when you run the class or refer to the class in your Java program.

The memory allocation of non-static variables happens only when you create an object of the class. To create an object of a class, first, the class must be loaded into the Java Virtual Machine (JVM).

What you need to understand from this is that static variables/methods are available right after the JVM loads the class and non-static variables/methods are not.

Therefore, when a static context becomes alive, there won’t be any non-static variables available in the memory.

You cannot access something that doesn’t exist. Right?

This is the reason you cannot reference non-static variables in a static context.

 

It is possible to access non-static variables in a static context by creating the object of the class. Don’t worry. I will explain everything about object creation in Java later. 

Use of final keyword in Class-Level Variables

The keyword final is used to declare constants in Java. ‘final’ is a java non-access modifier. If you use the final keyword while declaring a class-level variable, it becomes a constant.

You must assign a value to constants at the time of declaration.

Once you assign a value, you can’t change it. Hence it is called a constant.

 

There are other uses of the final keyword in Java. You can expect a detailed explanation in the upcoming tutorials.

The class-level variables & constants are commonly known as class fields.

The next variables, ‘args‘ and ‘locVar‘ are both local variables. ‘args’ is also the parameter of the ‘main method’.

All Method parameters are local variables.

Local Java Variables

Local Java variables are the variables you declare inside methods, sub-blocks inside the methods, or any other sub-blocks in a class.

The visibility of local variables is limited to the block where it is declared.

For example, if the local variable is inside a method, you can’t access it outside the method. That’s why we call it a local variable.

The purpose of local variables is to be available locally only.

Unlike class-level variables, Java will not assign a default value to local variables if you leave it un-assigned.

It is your duty to initialize local variables before you use them.

You can leave it un-assigned but when you try to use the unassigned local variable, you will end up getting a compile-time error.

Java allows us to use the final keyword to the local variables. ‘final’ is the only non-access modifier you can use with local Java variables.

 

These are the key points you must know about Java variables. Now let’s create a simple Java program with everything you learn from this guide.

class JavaVariables {

static int variableOne;

static char variableTwo = ‘G’;

static final String usefulTutorials = “GeekyPoint”;

public static void main(String[] args) {

int localVar = 10;

final String finalLocalVar = “I am a local variable”;

System.out.println(variableOne);

System.out.println(variableTwo);

System.out.println(usefulTutorials);

System.out.println(localVar);

System.out.println(finalLocalVar);

}

}

Conclusion

In this guide, I have covered the very basic but the most important points about the Java variables. I hope you find this helpful.

Do I miss any important points?

Do you have any other major points you wish I must add to this guide?

Let me know your thoughts about this guide in the comment section below.

Leave a Reply

Your email address will not be published. Required fields are marked *