Java Variables

In this Java tutorial, learn about the Java variables and types of variables. Also, look at the example of how to declare a variable in Java. We will also see some best practices for naming the variables in Java.

The Java programming language uses both “fields” and “variables” as part of its terminology. Fields refer to variables declared outside methods, and variables are referred to declarations inside methods, including method arguments.

1. What is a Variable?

As the term suggests, a variable is whose value can vary during the runtime. In Java, a variable is a named reference to a memory area where the value of the variable is stored.

Java Variable Example
How a variable works

1.1. Java Variable Syntax

The given syntax explains how to declare a variable in java:

[data_type] [variable_name] = [variable_value];

  • data_type – refer to type of information stored in memory area.
  • variable_name – refer to name of variable.
  • variable_value – refer to value to be stored in memory area.

For example, the below statements are valid variable declarations in Java.

int i = 10;         //Variable of int type

String str = "";   //Variable of string type

Object obj = new Object();      //Variable of object type

int[] scores = [1,2,3,4,5,6,7,8,9];         //Variable of int type

1.2. Java Variable Example

int i = 10;
int j = 10;

int sum = i + j;

System.out.println( sum );  // Prints 20

2. Widening and Narrowing

2.1. Widening

When a small primitive type value is automatically accommodated in a bigger/wider primitive data type, this is called the widening of the variable. In given example, int type variable is assigned to long type variable without any data loss or error.

int i = 10;
long j = i;

System.out.println( i );  
System.out.println( j );  

Program output.


2.2. Narrowing

When a larger primitive type value is assigned in a smaller size primitive data type, this is called the narrowing of the variable. It can cause some data loss due to less number of bits available to store the data. It requires explicit type-casting to required data type.

In given example, int type variable is assigned to byte type variable with data loss.

int i=198;  
byte j=(byte)i;  

System.out.println( i );  
System.out.println( j );  

Program output.


3. Types of Variables in Java

In Java, there are four types of variables. These variables can be either of primitive types, class types or array types.

All variables are divided based on scope of variables where they can be accessed.

  1. Instance variables

    Variables declared (in class) without static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class. They are also called state variables.

    public class VariableExample
        int counter = 20;         //1 - Instance variable
  2. Static variables

    Also know as class variables. It is any field declared with the static modifier. It means that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.

    public class VariableExample
        static float PI = 3.14f;    //2 - Class variable

    A variable declared as “public static” can be treated as global variable in java.

  3. Local variables

    These are used inside methods as temporary variables exist during the method execution. The syntax for declaring a local variable is similar to declaring a field. Local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.

    public class VariableExample
        public static void main( String[] args ) {
            int age = 30;     //3 - Local variable (inside method body)
  4. Method arguments

    An argument is a variable that is passed to a method when the method is called. Arguments are also only accessible inside the method that declares them, although a value is assigned to them when the method is called.

    public class VariableExample
        public static void main( String[] args ) {
            print( 40 );
        public static void print ( int param ) {      //4 - Method Argument
            System.out.println ( param );

4. Difference between Instance variables and Class Variables

  • Instance variables (non-static fields) are unique to each instance of a class.
  • Class variables (static fields) are fields declared with the static modifier; there is exactly one copy of a class variable, regardless of how many times the class has been instantiated.
  • To access instance variable, you MUST create a new instance of class. Class variables are accessible through class reference, and do not require to create object instance.

    Take an example. We have a class Data which has one instance variable as well as one class variable.

    public class Data 
        int counter = 20;
        static float PI = 3.14f;

    We can access both variables in a given way.

    public class Main 
        public static void main(String[] args) 
            Data dataInstance = new Data();
            //Need new instance
            System.out.println( dataInstance.counter );    //20
            //Can access using class reference
            System.out.println( Data.PI );                 //3.14 

5. Variable Naming Conventions in Java

There are a few rules and conventions related to how to define variable names.

  1. Java variable names are case sensitive. The variable name employee is not the same as Employee or EMPLOYEE.
  2. Java variable names must start with a letter, or the $ or _ character.
  3. After the first character in a Java variable name, the name can also contain numbers, $ or _ characters.
  4. Variable names cannot be reserved keywords in Java. For instance, the words break
    or continue are reserved words in Java. Therefore you cannot name your variables to them.
  5. Variable names should written in lowercase. For instance, variable or apple.
  6. If variable names consist of multiple words, then follow camelcase notation. For instance, deptName or firstName.
  7. Static final fields (constants) should be named in all UPPERCASE, typically using an _ to separate the words in the name. For example LOGGER or INTEREST_RATE.

Happy Learning !!

Leave a Reply

Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.