Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.

Categories: Core Java Basics. No Comments on Java variables
4.6
(5)

In this article you are going to learn about Java variables which are the fundamental units of storage for data in a Java program. You will also learn about creating or declaring variables, initializing variables and using variables in Java programs and different types of variables.

 

Java variables

 

Variable Definition

 

A variable is a named location in memory (RAM) to store data.

 


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


It is common in programs to store data and process the data to get the required outcome. If the data is predetermined (Case 1), for example, you want to add 2 and 3. Here, you know what to add. But what if the data will be read at runtime (Case 2) or someone else will give the data for your program. You can’t predict that data.

 

For Case 2, you have to use variables for storing the data in memory and then process it to get the output.

 

Java program for Case 1 will be as shown below:

class Sample
{
    public static void main(String[] args)
	{
		System.out.println("Sum of 2 and 3 is: "+(2+3));
	}
}

 

In the above program you must enclose 2+3 in brackets. Otherwise instead of 5, which is the expected output, you will get 23 (2 and 3 will be treated as strings and gets concatenated with each other).

 

Before looking at the program for Case 2, let’s learn how to declare variables and use them.

 

Creating or declaring variables in Java

 

A variable can be created or declared in Java by using the below syntax:

 

datatype  variable_name;

variable_name can be any valid identifier in Java. Before using any variable in a Java program, you have to declare it first as per the syntax given above. The datatype specifies the type of value you are going to store in the variable. More on Java data types in another article. For now, just think of it as the type of variable.

 

Example for declaring a variable in Java is shown below:

 

int  x;

 

In the above example, int is a Java’s primitive data type and x is the name of the variable.

 

Initializing variables in Java

 

After declaring variables, we can initialize them as shown below:

 

variable_name = value;

 

So, we can initialize the variable x as shown below:

 

x = 10;

 

Remember that x has been declared as an integer. So, we can store integer values in x. For initializing a variable, we use the assignment (=) operator. We can combine variable declaration and initialization into a single line as shown below:

 

int  x = 10;

 

Initializing variables with literal values like 10, 2.5, etc… is known as static initialization. We can also assign an expression to a variable as shown below:

int a = 10;
int b = 20;
int c = a+b;

 

The expression a+b will be evaluated at runtime (execution of the program) and then it will be assigned to the variable c. This type of initialization is know as dynamic initialization.

 

We can declare multiple variables of the same type as shown below:

 

int  x, y, z;

 

Java program for Case 2 shown below will give you an example of how to use variables in Java:

import java.util.Scanner;
class Sample
{
    public static void main(String[] args)
	{
		int x, y;
		Scanner input = new Scanner(System.in);
		System.out.println("Enter value of x: ");
		x = input.nextInt();
		System.out.println("Enter value of y: ");
		y = input.nextInt();
		System.out.println("Sum of x and y is: "+(x+y));
	}
}

 

In the above program Scanner is a utility class available in java.util package to read data from various sources like standard input, files etc… To read input from console (standard input) we provide System.in as a parameter to the Scanner’s constructor.

 

nextInt() method available in the Scanner class returns the input entered by the user as an integer. The variables x and y are dynamically initialized. Output of the above program is:

Enter value of x:
10
Enter value of y:
20
Sum of x and y is: 30

 

Types of variables

 

Based on the location where the variable is declared and how it is declared, variables in Java are divided into three types. They are:

  • Instance variables
  • Class variables
  • Local variables

 

Instance Variables: A variable which is declared inside a class and outside all the methods, constructors and blocks is known as an instance variable.

 

Class Variables: A variable which is declared inside a class and outside all the methods, constructors, blocks and is marked as static is known as a class variable. More on static keyword in another article.

 

Local Variables: Any variable which is declared inside a class and inside a block, method or a constructor is known as a local variable.

 

Following Java example program demonstrates all the three kinds of variables:

class Sample
{
	int x, y;
	static int result;
	void add(int a, int b)
	{
		x = a;
		y = b;
		int sum = x+y;
		System.out.println("Sum = "+sum);
	}
    public static void main(String[] args)
	{
		Sample obj = new Sample();
		obj.add(10,20);
	}
}

 

In the above program and y are instance variables, result is a class variablea, b, sum and args are local variables.

 

One important point to remember is, every object maintains its own copy of each instance variable and a shared copy of each class variable.

 

Questions related to variables:

 

1. What is difference between instantiation and initialization?

A: Instantiation refers to creating an object for the class and initialization refers to assigning some value to a variable.

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Suryateja Pericherla

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.

He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.

He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

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