In this article, we are going to explain to all Java learners what Java variables are and how to work with them. You can learn the material either in video format with a CodeGym mentor or in a more detailed text version with me below.

What is Java variable

A variable in Java can be thought of as a box. This "box" has a certain size: the memory that is allocated for it. How much memory will be allocated depends on the type of the variable, but we are going to talk about this a little bit later. At the same time, the size of the box itself cannot be changed after its creation, but the contents can. The box may be empty. You can "insert" some value into it, and then extract and put some other value. Thus, a variable is a field that stores data values ​​during the execution of a Java program. This box has important features:
  • it can always contain only one value (or can be empty, in which case it will contain the default value),
  • It has a data type. Its size depends on the type of data, as well as on which particular area of ​​​memory the place is allocated for it (where it lies).
Variables in Java - 1

How to declare variables

To declare variables in Java, you need to specify its type and name. Here is an example of declaring three variables:

int myInt;
String s;
Object variableName;
Here int, String, and Object are the data type and myInt, s, variableName are variable names. The data type must be chosen based on the needs of the program, and it is better to choose a name so that it is clear what it is about. Of course, for beginners it’s not that strict, but in large projects, variable names like ‘s’ can impair the readability of the code. So it's better to get used to naming variables in a way that makes it clear what they are for from the very beginning. Within reason, of course.

How to initialize variables

When you declare a variable, you allocate memory for it. Initialization means that you "put" a certain value into the "box". This can be done immediately during the declaration of the variable or later. Also, the value of a variable can change during program execution. Example:

public class VariableTest {
    public static void main(String[] args) {
        int myInt = 5;
        String s;
        s = "init";
        System.out.println(s);
        s = s+5;
        System.out.println(s);
    }
}
Here we declared and initialized the myInt variable in one line, immediately allocating memory for it (32 bits for every int number), gave it a name, and then placed the value 5 in the allocated memory. Then we declared that we were allocating memory space for the string s, and already a separate command put the value “init” into it. After that, we printed out the string and changed the value of the variable s. In this program, we printed out the lines, and if you run it, you will see the following result:
init init5

Rules for Naming Variables

Choosing the right name for a variable isn’t just about making your code readable; it’s also about following Java’s rules to avoid compilation errors. A variable name must always start with a letter, a dollar sign ($), or an underscore (_). Numbers are not allowed at the beginning. Reserved keywords like class, public, or int cannot be used as variable names. Spaces are not allowed either, so names should be written in camelCase, meaning the first word is lowercase, and subsequent words start with an uppercase letter.

Here’s an example of valid and invalid variable names:


        // ✅Correct variable names
        int myAge = 25;
        double $price = 9.99;
        String _greeting = "Hello, Java!";

        // ❌ Invalid variable names
        int 2cool4java = 10;  // Numbers can't be at the start
        double final = 99.99; // "final" is a reserved keyword
        String my name = "Java"; // Spaces are not allowed

Following these rules will ensure your code runs smoothly without syntax errors.

Now that you know how to name variables correctly, let’s explore how to use them inside strings. One of the easiest ways to join strings together is with the + operator. Java automatically converts non-string values into strings when concatenating.

Take a look at this example:


        public class StringConcatenation {
            public static void main(String[] args) {
                String firstName = "John";
                String lastName = "Doe";
                
                // Using + operator to concatenate strings
                String fullName = firstName + " " + lastName;
                System.out.println("Full Name: " + fullName);

                // Concatenating strings with other data types
                int age = 30;
                System.out.println("Hello, " + firstName + "! You are " + age + " years old.");
            }
        }

The + operator makes it easy to combine text with variables. In the example above, firstName and lastName are joined with a space in between. The second output demonstrates how Java converts an integer to a string automatically when concatenating.

Data types of variables in Java: primitive and non-primitive

Data types of variables in Java are divided into two groups:
  • Primitive data types include byte, short, int, long, float, double, boolean, and char
  • Non-primitive data types such as String, Arrays, and Classes
Here is an example of working with variables:

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

       int myInt = - 5;               // integer (whole number)
       float myFloat = 2.718281828459045f;    // Floating point number
       char myLetter = 'a';         // character
       boolean myBool = true;       // boolean
       String myText = "Hero";     // String
       System.out.println(myInt + " " +
               myFloat +" " + myLetter + " " +  myBool + " " + myText);
       Student myStudent = new Student("Walker","Johnny", "Kyle", null);
      
   }
}
int, char, boolean, and float are primitives. String is non-primitive. What about myStudent variable? This is an object of the user-created class Student. It was created simply to illustrate the work with non-primitive variables. They are the majority in Java, since almost everything in this programming language is an object. For understanding, here is the code of the Student class:

import java.util.Date;

public class Student {
   String surname;
   String name;
   String secondName;
   Long birthday; // Long instead of long is used by Gson/Jackson json parsers and various orm databases

   public Student(String surname, String name, String secondName, Date birthday ){
       this.surname = surname;
       this.name = name;
       this.secondName = secondName;
       this.birthday = birthday == null ? 0 : birthday.getTime();
   }

   @Override
   public int hashCode(){
       //TODO: check for nulls
       //return surname.hashCode() ^ name.hashCode() ^ secondName.hashCode() ^ (birthday.hashCode());
       return (surname + name + secondName + birthday).hashCode();
   }
   @Override
   public boolean equals(Object other_) {
       Student other = (Student)other_;
       return (surname == null || surname.equals(other.surname) )
               && (name == null || name.equals(other.name))
               && (secondName == null || secondName.equals(other.secondName))
               && (birthday == null || birthday.equals(other.birthday));
   }
}

Types of variables in Java: local, instance, and static

There are three different types of variables in Java, we have listed them as follows:
  1. Local Variables
  2. Instance Variables
  3. Static Variables

Local Variables

A variable declared inside the body of the method is called a local variable. Also, local variables are declared inside constructors and blocks. You can use local variables only within that method, constructor, or block where they were created and the other methods in the class aren't even aware that the variable exists. So local variables are created when the method, constructor, or block is entered and the variable is destroyed once the method, constructor, or block doesn’t work. A local variable cannot be defined with the static keyword. Even more: you can’t use access modifiers for local variables. Here is an example:

public class VariableTest {
   public static void main(String[] args) {
       System.out.println(myMethod("C plus "));
   }
           private static String myMethod(String myString) {
       String myOtherString = "plus";
       return myString + myOtherString;
   }
}
Here myOtherString is a local variable. You can’t use it from the other method, but myMethod. Local variables can’t have default values. If at least one local variable is not initialized in the program, the program will not work correctly. Let's make a small change in one of the previous examples and "forget" to initialize the myBool variable:

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

       int myInt = - 5;               // integer (whole number)
       float myFloat = 2.718281828459045f;    // Floating point 
       char myLetter = 'a';         // character
       boolean myBool;       // boolean
       String myText = "Hero";     // String
       System.out.println(myInt + " " +
               myFloat +" " + myLetter + " " +  myBool + " " + myText);
       Student myStudent = new Student("Walker","Johnny", "Kyle", null);

   }
}
If we try to run the program, it will throw an error:
Error:(10, 50) java: variable myBool might not have been initialized

Instance Variables

A variable declared inside the class but outside the body of any method, constructor or block is called an instance variable. Instance variables are created when an object is created using the new keyword. It is destroyed when the object is destroyed. It can’t be declared as static, but you can use access modifiers for instance variables. Instance variables are visible for all methods, constructors and blocks in the class. Usually instance variables are private, but you can change the visibility for subclasses. Instance variables as opposed to local variables have default values. For all number primitive types the default value is 0, for booleans it’s false, and for object references it’s null. Values can be assigned during the declaration or within the constructor. Here is an example:

//instance variable example
public class Employee {

   // here we have a public instance variable. It is visible for this class and child classes
   public String name;

   //this instance variable is private so it’s visible for the Employee class only. You can use setters and getters to get it
   private double salary;

   public Employee (String empName) {
       name = empName;
   }

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }

   public double getSalary() {
       return salary;
   }

   public void setSalary(double employeeSalary) {
       salary = employeeSalary;
   }

   public static void main(String args[]) {
       Employee employee = new Employee("Johnny");
       employee.setSalary(1500);
       System.out.println("name = " + employee.getName());
       System.out.println("salary = " + employee.getSalary());
   }
}

Static variables

A variable that is declared as static is called a static variable. Java offers you to declare such variables outside a method, constructor or block. It cannot be local, they belong to class, not to instances. That means that a single copy of a static variable once created and shared among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory. They can have any visibility, but usually they are declared as public. They also have default values such as instance variables.

public class Box
{
   public void add(int data)
   {
       Storage.sum = Storage.sum + data;
       Storage.count++;
   }

   public void remove(int data)
   {
       Storage.sum = Storage.sum - data;
       Storage.count--;
   }
}

public class Storage
{
   public static int count = 0;
   public static int sum = 0;
}
In the example above, we created a separate Storage class, moved the count and sum variables into it, and declared them static. Public static variables can be accessed from any program method (and not only from a method).

You've got a solid grasp of Java variables, but let’s take things up a notch by introducing final variables. If you've ever wondered how to create constants or prevent accidental modifications in your code, this section is for you! Let's dive in.

What is a Final Variable?

A final variable in Java is a variable that, once initialized, cannot be modified. Think of it as a locked vault—you can put something in, but you can’t change it afterward.

Here’s a simple example:


        public class FinalVariableExample {
            public static void main(String[] args) {
                final int SPEED_OF_LIGHT = 299792458; // meters per second
                System.out.println("Speed of Light: " + SPEED_OF_LIGHT);

                // Uncommenting the next line will cause a compilation error
                // SPEED_OF_LIGHT = 300000000;
            }
        }

Notice how we used uppercase letters for the variable name? This is a common convention when declaring constants.

Why Use Final Variables?

Final variables are useful for defining constants, ensuring data integrity, and improving code readability. Once assigned a value, they cannot be changed, making them ideal for values that should remain consistent throughout the program.