Java Variables

“Situational variables can exert powerful influences over human behavior, more so that we recognize or acknowledge” Philip Zimbardo

We use variables in programs when we want to store data temporarily while the program is running.

If we think about it, programs for the majority of cases, need data to function correctly.

For example a calculator takes numbers and runs operations on them (like division, addition, and multiplication etc.). Or consider a browser that needs the address of a website to be able to load that website for us to see.

A video player is another example of a program that needs data (video) to display it to users.

These data are stored in the memory and we use variables to have the access to those data.

Basically a variable is the representation of the data that we store in that variable. When we need the data, we just call the variable instead of looking for it in the memory.

Variables syntax in java

This is the structure of how we create a variable:

Data-type variable-name;

Variables type:

Data-type: data in programs has different types and when we create a variable, it’s important to declare the type of that variable as well.

For example if we have a value that is an integer like 100, and we want to store this value in a variable, we need to declare the type of that variable as int which stands for integer.

Also after declaring the type of a variable, we can’t change that type anymore and from the declaration onwards, only values of the specified type are allowed to be stored in the target variable.

Now the question is why in programs we need to declare the type of a variable?

Well the first reason is the amount of memory space that will be allocated to a variable.

In Java there are multiple data types like int, double (for storing floating values), float (another data-type for storing floating values) and other types.

Each of these types takes a different amount of memory. For example a variable of type int has enough memory space to only store integer values range from -2,147,483,648 to 2,147,483,647.

If in a program we need to store a value larger or smaller than the range that a variable of type int can support, then we need to use another type like long and short just to name a few.

So the data type of a variable declares the amount of memory space that should be allocated to the variable.

The second reason that we use data-types is to help the compiler and developers to figure out what type of values are allowed to be stored in the variable.

Note: if we put a value of different data type to a variable, depending on the type of the value, your program will either crash and stop working properly or it will try to cast the value to the right type which might end up malfunctioning.

Check the Java data type section for more information.

variable-name: the variable-name is used to access the memory location assigned to that variable. It’s like a door that opens to the memory-space.

With the help of this name, we can store and get values in and out of that memory space.

Here's an example of creating variables:

int age;
String name;

Here the first variable is named age and its data type is integer so we can store values range from -2,147,483,648 to 2,147,483,647 into this variable.

The second variable is named name and its data type is String. A variable of type String is used to store character-strings like names, sentences etc.

Assigning values to variables

In Java assignment operators section we will explain in depth how to assign a value to a variable but for now this is how we can do so:

int age;
String name; age = 40; name = "John";

First of all we use assignment = operator to store a value to a variable.

For example here we’ve stored the value 40 into the age variable and the value John into the name variable.

Notes:

  • We use double quotation `” “` to store character string into a
    variable of string type.

  • We could directly assign values right where the variables are
    declared.

int age = 40;
String name = "John";

Also the process of assigning values to variables for the first time is called initialization.

Now if we call these two variables, we would get their values.

Example:

public class Simple {

public static void main(String[] args){
int age = 40;
String name = "John";
System.out.println(name + " " + age);
}
}

Output: John 40

As you can see, both the value of the name variable and the value of the age variable are sent to the output stream when we called the println method.

Note:

  • The `println` method, takes different types of values and one of
    them is character string or a value that can be casted to
    character-string. In this example we want to send the values of two
    variables to the output stream (The screen in this case).

In such cases, because this method only takes one argument, we need to somehow combine the values of these two variables to represent only one value and then send it as the argument of the method.

So what we did was to use the addition + operator.

This operator will attempt to add the first value to the second one.

Here the first value is John which is the value stored in the name variable and then the next value is a white space. So now the space is attached to the name John. After that we’ve added another + operator to attach the current value to the value 40 which is the value of the age variable.

So the final value that is sent to the println() method is this: John 40.

Note: if we didn’t use the white space, the message that could be sent to this function was John40 which as you can see there’s no space in between.

Variables naming convention

There are some rules that need to be followed when we want to set a name for a variable:

  • The name that we use for a variable can contain letters, numbers
    and underscore (_). For example: jack, ellen2020, _black, sunnySeason
    etc.

  • A name for a variable can begin with either underscore or letter.
    For example: _sum, check_point etc.

  • The name of a variable cannot start with number.

  • We can’t use white space and special characters like !@#
    %^&*()+ etc. in variable’s name.

For example, these names are illegal: ell en, %%jack, Tony&&, pre-process.

  • The Java language is case sensitive which means a variable named
    `ellen` is different than a variable named `Ellen` or `ELLEN`.

  • We can’t create two variables with the same name in the same
    scope. But we can have two variables with the same name each live
    in different scope or one live in one method and the other live
    in global (outside all other functions).

  • We can’t use Java language reserved keywords as the name of a
    variable.

Here’s the list of reserved keywords:

abstract do if private this
assert double implements protected throw
boolean else import public throws
break enum instanceof return transient
byte extends int short true
case false interface static try
catch final long strictfp void
char finally native super volatile
class float new switch while
const for null synchronized continue
default goto package
  • Semicolon `;`: the process of creating a new variable is called
    `declaration statement` and any declaration statement ends with
    semicolon `;`.

Note: We only use data types once when we’re declaring a variable. From that moment afterward, assigning values to a variable does not need mentioning the type of the variable anymore.

For example:

int firstNumber;
firstNumber = 100;

Locations where we can declare a variable:

A variable can be either declared as the local variable of a method or it can be declared outside of all methods which in that case it is considered as the attribute of the class and any method in that class can access the variable.

Note: if the access specifier of an attribute variable is public it can also be accessible via objects that are created from that class.

Local variables:

Local variables are only accessible from the body of a method that they are declared in. This means if we have two methods named first and second and inside the first method we declare a variable named age the second method can’t access that variable.

If we attempt to do so, we will get a compile time error.

Note: compile time error means the compiler will not compile the source code and instead it will return an error giving its reason of why not compiling.

Example:

public class Simple {

public static void main(String[] args){
int age = 40;

}
public static void second(){
System.out.println(age);
}
}

Output:

Error: Cannot fine the symbol: variable age.

As you can see we have a variable named age in the main method so it is the local variable of this method. But we’ve also tried to access the value of this variable in another method named second.

Now because a local variable as its name suggests is not accessible in another method, the compiler returned error instead of compiling the program. Basically, your program crashed even before running.

Now let’s declare the variable outside of all methods:

public class Simple {
static int age;
public static void main(String[] args){
age = 40;
second();
}
public static void second(){
System.out.println(age);
}
}

Output: 40

Note: when creating a variable outside of any method, and that variable is about to be used in a static method, we need to declare the variable as `static` just like the way we did it in this example.

Also a static variable is not accessible in a non-static method. You’ll learn more about it in static variables section.

In this example the variable named age is declared as the attribute of the class (outside of all methods) and so methods of this class can access the variable (of course only static method). This means methods of this class (static methods) can change or just get its value.

Here we changed the value of the age variable in the body of the main method and then called the second method and in the body of that method we sent the value of the age variable to the output stream.

Check the method section to see how we can call methods in Java.

Notes:

  • A method can only see and work with variables that exist globally
    or within the body of that method. Check the method section for
    more information.

  • Also the name of a variable should be unique in the scope that is
    declared. For example if a variable is declared globally with the name
    `gVar`, no other `gVar` is allowed to be declared globally. Similarly,
    if within the body of a method like `main()` we declared a variable with
    the name say `age`, no other variable with this name is allowed to be
    declared inside this method.

Note: But we can have two variables with the same name one declared globally and the other declared locally within the body of a method. Also there can be two or more local variables with the same name if each one of them is declared inside a separate block.

Multiple variable declarations:

We can declare multiple variables of the same type in a single statement as well:

Data-type variable_one, variable_two, variable_n;

In this structure, each variable is separated via colon ,.

For example:

double v_one, v_two, v_n;

In the example above, we’ve created 3 variables of type double.

Note: we could also assign values directly to each variable if we wanted.

For example:

int variable_one = 10, variable_two = 30, variable_n = 50;
Access specifier:

A variable also has something called access specifier.

In access specifier section we will explain in details but for now remember that an access specifier comes before the data type of a variable and it declares the accessibility of that variable.

For example a variable that is declared private like:

private int variable_one = 10;

Means the variable is only accessible in the class where it’s being declared and no objects that are created from that class can access the variable.

Or if we set the access specifier of a variable as public that means the variable is accessible from objects created from that class.

public int variable = 10;

Note: access specifiers are only used for class level variables (AKA global variables) and we can’t use them for the local variables though.

Again in access specifier section we will explain this topic in greater details.