Variables in Java

Variables are pieces of memory that contain data type value. A variable is never written alone in Java, it always requires a Data Type. In a high-level language, a variable is a container of data. When said in plain language, different kind data is stored within a variable so it can be accessed from one place to another. Following are the types of Variables in Java:

  • Local variables
  • Instance variables
  • Static variables
  • Global variables

Local Variables

First we will talk about initializing a variable. To initialize an local variable a data type is first written and next to it is the variable, whereas variables can have any name, not the data types. Data types are specific keywords within Java. Learn more about Data Types here. Local variables are variables within a method, the local variable is limited within the method. A local variable cannot be defined as static. Here is how a instance variable declared & initialized within the main method.

public class Main {
    public static void main(String[] args) {

        // integer variable has value 1 with data type int
        int integer = 1;

        // floatValue variable has value 1.0f with data type float
        float floatValue = 1.0f;

        // doubleValue variable has value 1 with data type double
        double doubleValue = 1;

        // longValue variable has value 1 with data type long
        long longValue = 1;

        // string variable has value "string" with data type String
        String string = "string";

        // character variable has value 'a' with data type char
        char character = 'a';

        // Following are arrays initialized according to data type
        int[] integerArray = { 1, 2, 3, 4, 5 };
        float[] floatArray = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f };
        double[] doubleArray = { 1, 2, 3, 4, 5 };
        long[] longArray = { 1, 2, 3, 4, 5 };
        String[] stringArray = { "Jack", "Robert", "Mary" };
        char[] characterArray = { 'h', 'e', 'l', 'l', 'o' };

    }
}

These are the most popular and mostly used data types with easy to understand variables. The scope of these variables is within the method. Here is an another example of how variable scope works within Java

public class Main {
    public static void main(String[] args) {
        String name = "Jack";
        System.out.println(name);
        testFunc();
    }

    private static void testFunc() {
        String name = "Mary";
        System.out.println(name);
    }
}

Consider the example above as both the functions have same variable name and different value but both are local variables which are restricted to their own methods. Within the main method I called the testFunc() which printed out the name Mary with the same variable and is it not affected. This is called variable scoping in Java. It doesn’t matter if there are same variable names within different functions. Before moving further here are some rules for writing variables in Java.

Rules for writing variables in Java

  1. Variable name should be written according to its use. For example, if I am finding a result of 2 variables then the variable name should be “result” rather than “findingAdditionResult“.
  2. Variable names cannot be keywords, for example we cannot use String as a variable name, it will cause an error.
  3. Variable name cannot start with a number, for example we cannot use 2fruits as a variable name. The other option will be “twoFruits” which is valid.
  4. Always use a case type while writing variable names, the most commonly used is the Camel case. Learn about Case types here.

INSTANCE variables

Instance variables are written within a class, not in a method and the condition for them to act as an instance variable is that they should not be declared static. The reason they are called instance variables is that their values are instance specific and are not shared among instances.

Java program example

public class Main {

    // Instance variable
    private int integer;

    public static void main(String[] args) {

        // Accessing the instance variable
        Main main = new Main();
        main.integer = 10;
        System.out.println(main.integer);

    }
}

Output

10

In the above example, the private int integer is an instance variable. To access an instance variable within a static method, an object of the class containing the instance variable should be called. Here is how an object class is called

[Class Name] [variable] = new [Constructor](arguments);
Main main = new Main();

When a class is written without a constructor, it has a default empty constructor without any arguments. Using the variable main we initialized a value to the instance variable (integer) and printed it out. An instance variable can have the following access modifiers & a local variable cannot:

  1. Public (public) – available to every outer class.
  2. Private (private) – restricted to every outer class.
  3. Protected (protected) – accessible by the classes of the same package only.

Static variables

Static variables are declared with the keyword static before the variables. They cannot be local variables. Static variables produce a single copy of the variable and share it among all the instances. Memory is allocated to static variables once when the class loads. static variables can be accessed within a non-static functions. Static variables are available to the whole class for use.

JAVA PROGRAM EXAMPLE

public class Main {

    // static variable
    static int integer;

    public static void main(String[] args) {

        // Accessing the static variable
        integer = 10;
        System.out.println(integer);
        changeValue();
    }

    // Function changes the static variable value
    private static void changeValue() {
        integer = 20;
        System.out.println(integer);
    }
}

Output

10
20

In the above example, first we initialize the value of static variable integer as 10 and print it out and next we call the changeValue() function which changes the static variable integer to 20 and prints it out. This is how static variables can change values and be accessed. If no access modifier is specified with a static/instance variable, then it is said to be public which can be accessed everywhere. It is recommended to keep static/instance variables private.


Let me know in the comments if something I have written is incorrect. I love to hear from you.

Related: