Variables in Java

In this post, I am going to talk about variables in Java. I will explain how to declare and initialize them, the types of primitive variables that we handle in Java, how to change the type of a variable and its scope.
But before we start, we must introduce a series of preliminary concepts:
• A variable is a container, a memory location, that stores a value while a program is running.
• We put a name to each variable, so that we can reference it in our code, and use the value it stores.
• Variables are of one type. The type of data that we intend to store in the said variable. For example, if a variable is of type int, it will be used to store integer values. However, if it is of type String, it is used to store a string of characters, that is, text.
• Variables have to be declared. In this declaration, we indicate the type of the variable and its name.
• A variable has to be initialized to be used in our program. Initializing a variable is putting a value in it.

Declaring and initializing variables

To declare a variable we have to indicate the type and the name. Some examples:

int month;
String message;

“int” is a primitive type while String is not. The String type is a character string. A character would be stored in a char that is a primitive type of java.

Let’s practice with an example:

Activity 1: declaring and initializing variables

  1. Open the online compiler.
  2. Enter the following code:
public class HelloWorld{

     public static void main(String []args){
        String message;
        message = "Hello World";
        System.out.println(message);
     }  
}

Line 3: the variable named message is declared of type String.
Line 4: the variable named message is initialized with the value: “Hello World”.
Line 5: Instruction to paint on screen the text stored in the variable named message.

Activity 2: declaring and initializing variables

  1. Open the online compiler.
  2. Enter the following code:
public class HelloWorld{
     public static void main(String []args){
        int number1, number2, sum;
        number1 = 11;
        number2 = 7;
        sum = number1 + number2;
        System.out.println(sum);
     }  
}

Line 3: variables number1, number2 and sum are declared as an integer type, with the identifier int.
Lines 4 and 5: We initialize variables number1 and number2
Line 6: we execute the sum operation with the values of the variables number1 and number2, saving the result obtained in the sum variable.
Line 7: We present on the screen the value of the variable sum.

Primitive types

Java defines some types of data known as primitive types. However, there are other types of data called referenced types, which are created by the programmer.
In this post, we will study primitive types.

TypeDescription
intIntegers (4 bytes)
shortIntegers (2 bytes)
longIntegers (8 bytes)
byteIntegers (1 byte)
floatFloating-point decimal numbers (4 bytes)
doubleDecimal floating-point numbers (8 bytes)
charCharacters using the Unicode encoding scheme (2 bytes)
booleanBinary value: true or false
The 8 primitive types of Java

Out of the 8 primitive types in Java, 6 are numeric. Let’s practice with the different types.

Activity 3: Practicing with primitive types

  1. Open the online compiler.
  2. Enter the following code:
public class HelloWorld{
     public static void main(String []args){
        int number1, number2, sum;
        number1 = 11;
        number2 = 7;
        sum = number1 + number2;
        System.out.println(sum);
     }  
}

In line 3: the variables number1, number2 and sum are declared as integers and everything works correctly.

  1. Now we change the addition operator to the division operator. In line 6: Change “+” to “/” .

The result of dividing 11 by 7 is 1, which is not completely accurate. We obtain this result because the variable sum is of type int, and does not admit a decimal value.

  1. Change the type of the variable “sum” from int to float.

The new code would be:

public class HelloWorld{
     public static void main(String []args){
        int number1, number2;
        float sum;

        number1 = 11;
        number2 = 7;
        sum = number1 / number2;
        System.out.println(sum);
     }
}
  1. Run the program
  2. The result is “1.0”. Which is not exact, but is expressed in a decimal number.

The result of an operation between two integers will always be an integer value. If we save it in a float variable, this value will be transformed to a decimal number, but remember that the result of the operation was an integer.

  1. Now we change the types of the variables “number1” and “number2” from int to float.

We can declare all the variables of the float type on the same line, obtaining the following code:

public class HelloWorld{
     public static void main(String []args){
        float number1, number2, sum;

        number1 = 11;
        number2 = 7;
        sum = number1 / number2;
        System.out.println(sum);
     }
}

Now the result is 1.5714285. So we finally get the exact result when we declare all variables with a type that supports decimal numbers.

  1. Now we change the type of the variable “sum” from float to int

We separate line 3 into two variable declaration lines:

        float number1, number2
        int sum;
  1. We run the program and we will get the error:
/HelloWorld.java:3: error: ';' expected
        float number1, number2
                              ^
1 error

What has happened? The division between number1 and number2 is a float value, that is, a decimal number. When we try to store a decimal value in a variable that only supports integer numbers, we get the consequent error.

Now let’s practice with the type char

Activity 4: Practicing with the char type

  1. Open the online compiler.
  2. Enter the following code:
public class HelloWorld{

     public static void main(String []args){

        char character;
        character = 'C';
        System.out.println(character);
     }
}

In line 3: we declare the character variable of type char.
In line 4: We start the previous variable. Note that the value that we want to save in the variable, being of type char, has to be enclosed in single quotes. This is the nomenclature of java.
In line 5: We paint the value of the variable on the screen.

  1. Now we try to change the single quotes to double in the initialization of the variable. We make character = “C”;
  2. We run the program and get the following error:
/HelloWorld.java:6: error: incompatible types: String cannot be converted to char
        character = "C";
                    ^
1 error
  1. Remember, java is a language with a very strict syntax. When we initialize a char variable we will have to use single quotes. When we initialize a String we will use double quotes.
  2. Now type the following Code:
public class HelloWorld{

     public static void main(String []args){

        char character1, character2;
        character1 = 'H';
        character2='i';
        System.out.print(character1);
        System.out.print(character2);
     }
}
  1. Run the program and you will draw the word Hi on the screen.
    We have used a new method of writing: “print” instead of “println”. The difference is that the last method moves us to a new line after drawing its argument. The first one however does not, so using this method we draw the characters in a row.

Escape sequences

In java, we have a series of escape sequences:

Escape sequencesDescription
\bInserts a backspace
\tInserts a tab
\nInserts a new line
\fInserts a form feed
\rInserts a carriage return
\”Inserts a double quote character
\’Inserts a single quote character
\\Inserts a backslash character
List of escape sequences in Java

To understand how escape sequences work, it’s best to see it in practice.

Activity 5: Practicing with the escape sequences

  1. Open the online compiler.
  2. Enter the following code:
public class HelloWorld{

     public static void main(String []args){

        char character1, character2,character3;
        character1 = 'H';
        character2='\n';
        character3='i';
        System.out.print(character1);
        System.out.print(character2);
        System.out.print(character3);
     }
}
  1. Run the program and you will see the effect of the escape sequence, in this case, “\ n”, which generates a new line.
  2. Then lines 7,8 and 9 would be equivalent to:
System.out.println(character1);
System.out.print(character3);

Finally, we have one last primitive type to analyze: the boolean. A boolean variable has two possible values: true or false. And it can only contain one of those values.
To practice with this type, we need to introduce a control statement, which we will see in more detail in later notebooks. This is the “if” statement.

Activity 6: Practicing with booleans

  1. Open the online compiler.
  2. Enter the following code:
public class HelloWorld{

     public static void main(String []args){

        boolean paid;
        paid = false;
        System.out.println(paid);
     }
}

In line 3: We declare the Boolean variable.
In line 4: We initialize the Boolean variable.
So far nothing new, but let’s go on to use the if command showing the use of this type of variables.

  1. Type the following code:
public class HelloWorld{

     public static void main(String []args){

        boolean paid;
        paid = false;
        if (paid){
            System.out.println("Your product is on the way");
        }else{
            System.out.println("You have to pay the bill to receive your product");
        }
     }
}
  1. Run the Code and observe the text that is drawn on the screen.
  2. Now, change the paid value on line 4. Write: paid = true;
  3. Run the Code and observe the text that is drawn on the screen.
    Can you explain how the “if” command works based on the results we have obtained? If you do not understand how it works, do not worry, we will study it in later posts.

Constants

Sometimes we use variables in which we store a value that we do not want to change during the execution of the program. It is a constant.
To indicate that a variable is a constant, in its declaration, we have to write the keyword “final” before the keyword that indicates the type. For example:
final int year;
Once the constant has been initialized, we cannot change its value.

Activity 7: Practicing with contants

  1. Open the online compiler.
  2. Enter the following code:
public class HelloWorld{

     public static void main(String []args){

        final int thisYear;
        thisYear = 2020;
        System.out.println("Hello world in the year "+ thisYear);
     }
}

On line 3: We declare the integer variable thisYear as a constant, adding the keyword “final”.
On line 4: The constant thisYear is initialized.

  1. Let’s try to change the value stored in the constant thisYear. To do this, we simply type another line in which we try to give the constant another value, using an assignment operation.
public class HelloWorld{

     public static void main(String []args){

        final int thisYear;
        thisYear = 2020;
        thisYear = 2021;
        System.out.println("Hello world in the year "+ thisYear);
     }
}
  1. We execute the program and get the following error:
/HelloWorld.java:7: error: variable thisYear might already have been assigned
        thisYear = 2021;
        ^
1 error

Casting of variables

Commonly, we need to convert the type of variable to a different one. This operation is known as Casting.
When we perform operations with numeric values of different types, java will automatically perform one of these conversions, following the rules:

• If one of the values is of type double, then the other value is automatically converted to double.
• If neither is of type double but one is of type float, then the other value is converted to type float.
• If neither is double or float but one is type long, then the other value is converted to type long.
• If all of the above fails, both values are converted to int.

The figure below shows these automatic conversions. The dotted line indicates that we may lose precision when we do the conversion it indicates.

type conversion rules
Types conversion rules

But there are some types of conversions that java does not do automatically and they have to be forced by the programmer, using casting.
To cast a variable from one primitive type to another, we have to write the final type in parentheses just before the name of the variable whose type we want to change. The syntax would be:

<variable1> = (type) <variable2>

The data type stored in variable2 is cast to the type in parentheses, and that data with the new type is stored in variable1.
Let’s see it in an example.

Activity 8: Practicing with casting

  1. Open the online compiler.
  2. Enter the following code:
public class HelloWorld{

     public static void main(String []args){

        double pi = 3.141592;
        System.out.println(pi);
        int piEntero = (int) pi;
        System.out.println(piEntero);
     }
}

Line 3: We declare and initialize the variable pi as type double. Then we will be able to store decimal values in it.
Line 4: The value of pi is drawn on the screen.
Line 5: We convert the data in the variable pi, which is of type double, to type int. And we save the data in the variable piEntero which is of type int.
Line 6: The integer value is drawn on the screen.

  1. We execute the program and obtain the following result:
3.141592
3

Scope of a variable

The scope of a variable is the part of the program from where the variable is accessible and we can therefore use it. As a general rule, the scope of a variable is limited to the block in which it has been declared. Remember that the block will be marked by a start brace and a closing brace.
Java has some keywords that allow us to modify the scope of a variable, going beyond the limits of the block in which it is declared.
Let’s do an activity to test how the scope of variables works.

Activity 9: Practicing with the scope of a variable

  1. Open the online compiler.
  2. Enter the following code:
public class HelloWorld{

     public static void main(String []args){
        double pi;
        pi= 3.141592;
        otherMethod();
     }
     public static void otherMethod(){
         System.out.println(pi);
     }
}

Line 3: The variable pi is declared within the main method, then its scope goes from line 2 to line 6.
Line 5: We call the “otherMethod” method
Line 8: We try to use the variable pi inside the “otherMethod” method, that is, out of its scope. The variable is not available there, so if we run the program, we will get the consequent error.

/HelloWorld.java:9: error: cannot find symbol
         System.out.println(pi);
                            ^
  symbol:   variable pi
  location: class HelloWorld
1 error
  1. To solve this issue, we are going to change the scope of the variable pi. Now we declare the variable pi in the body of the class, which goes from line 1 to the closing brace on line 10. And this will be the scope of the variable.
public class HelloWorld{
    static double pi;   
    public static void main(String []args){
        pi= 3.141592;
        otherMethod();
    }
    public static void otherMethod(){
         System.out.println(pi);
    }
}

Line 2: We declare the variable pi. As this declaration is inside the Class block, the scope of this variable goes from line 2 to line 10.
Line 8: the variable pi is used by the println function to draw its value on the screen. And it works since this line is part of the scope of the variable pi.
Line 2: In the variable declaration, I have added the keyword “static” before indicating the type of the variable. This is necessary to be able to refer to the variable by its name, without having to use an object (an instance of the class) to access it. In any case, do not worry about this now, when we see the Class notebook, I will explain this topic in detail.

  1. Let’s do one last test with a variable declared inside an if block. We write the following Code:
public class HelloWorld{
    static double pi;   
    public static void main(String []args){
        pi= 3.141592;
        otherMethod();
    }
    public static void otherMethod(){
         System.out.println(pi);
         if (pi>2){
             int x = 5;
             System.out.println("x is equal to "+x);
         }
    }
}

We have only added 4 lines to the above Code. From line 9 to 12.
Line 10: I declare the variable x as of type int and initialize it to the value 5. So its scope is limited to the “if” block, from lines 9 to 12.
Line 11: We use the variable x and everything is fine since we are within the scope of the variable.
However, if we were to move line 11 out of the “if” block, we would be trying to use the variable x out of scope, and we would get the error:

/HelloWorld.java:13: error: cannot find symbol
         System.out.println("x is equal to "+x);
                                            ^
  symbol:   variable x
  location: class HelloWorld
1 error

Strings

A String type is a sequence of characters, so it can be viewed as text.
It is not a primitive Java type, but a referenced type, defined in the String class. However, its use is so common that it can sometimes seem like a primitive type.

Activity 10: Practicing with Strings

  1. Open the online compiler.
  2. Enter the following code:
public class HelloWorld{
     public static void main(String []args){
        String text = "Hello world";
        System.out.println(text);
    }
}

Line 3: We declare and initialize the variable text, of type String. Note that, for initialization, that is, to store a value in the variable, we use double quotes.
Line 4: We draw the value of the text variable on the screen.

  1. Combining Strings. Type the following code:
public class HelloWorld{
     public static void main(String []args){
        String text1 = "Hello, ";
        String text2 = "my name is John";
        String textFinal;
        textFinal= text1+text2;
        System.out.println(textFinal);
     }
}

Line 6: We combine the Strings text1 and text2, saving the result in the variable textFinal

  1. If we execute the program, we will obtain the result:
Hello, my name is John
  1. Combining with literal texts, we type the code:
public class HelloWorld{
     public static void main(String []args){
        String text1 = "Hello";
        String text2 = "John";
        String textFinal;
        textFinal= text1+", my name is "+text2;
        System.out.println(textFinal);
     }
}

Line 6: We combine String type variables with literal texts.
If we execute the program, we will get the same result as before:

Hola, my name is John
  1. Combining with integers, we type the code:
public class HelloWorld{
     public static void main(String []args){
        String text1 = "Hello";
        String text2 = "John";
        String textFinal;
        textFinal= text1+", my name is "+text2;
        System.out.println(textFinal);
        int age = 23;
        textFinal = text1+", I am "+text2+" and I am "+age+" years old";
        System.out.println(textFinal);
     }
}

We have added 3 lines to our previous Code: From line 8 to 10.
Line 9: We store in “textFinal” the combination of String variables, literal texts and a numeric value of an int variable. The integer value is converted to String to be able to be combined with the others, and the result is stored in the variable “textFinal”, which logically is also of type String.
If we run the program, we will get the result:

Hello, my name is John
Hello, I am John and I am 23 years old
  1. Using a method of the String class

I have mentioned previously that String is a referenced type defined in a Class, which provides us with different methods to make it easier to work with Strings. Although we have not talked about classes before, in this practice, we will see how to use a method of the String Class. Do not worry if at this moment it sounds strange to you, we will study the methods in another notebook and all this will be clear to you.
Type the following Code:

public class HelloWorld{
     public static void main(String []args){
        String text1 = "Hello";
        String text2 = "John";
        String textFinal;
        textFinal= text1+", my name is "+text2;
        System.out.println(textFinal);
        int textLength;
        textLength = textFinal.length();
        System.out.println("The length of the text is: "+textLength);
     }
}

Line 8: I declare the variable textLength of type int, where I will store the length of the text stored in the variable textFinal, which is of type String.
Line 9: textLength is initialized with a value delivered by the length method of the String class. What this method does is count the number of characters.
Without going into much detail, we see that when we want to use a method of a class, we refer to it using a variable (an object), followed by a dot and the name of the method.

  1. Execute the program and you will get the result:
Hello, my name is John
The length of the text is: 22

NOTE:

This post is part of the “Java” collection that reproduces the notes of the class that I teach on the subject at ESIC University. You can see the index of this collection here.