Java Tutorial - Assignment Operators

It is very hard to write any program without using variables. And when we use variable, the first thing we want to do is to assign it some values. Variables are like storage of data, so it is natural for us to put some values to this storage. In this post, we will show how to use the assignment operator in Java, which assigns values to a variable.

Assignment Operator Syntax

We will typically see two syntax for assignment operator in Java. The first one is shown below.
type variable = some expression;
Which means we declare the variable to be of some type, and assign a value to it at the same time as the declaration. Below is an example:
int a = 1;
The example shows we declare an integer a, and assign it with the value of 1. Hence when we run the code above, we get the below output:
Another syntax is when the variable was already declared previously. We can assign new value to it to override previous value:
variable = some expression;
For example:
int a = 1;
a = 2;
So in the code above, a was initialized with the value of 1 upon declaration. But at the next line, we assign it a value of 2. So the previous value is now gone and 2 is the new value. So when we run the code above, we get:

Assignment With Literal

As shown above, we can assign a variable with a literal value. For example

int num = 10;

So 10 is a literal number assigned to variable num. Hence the output below is expected:


Assignment With Another Variable

We can also assign a variable with the value from another variable, for example:

int a = 3;
int b = a;

So we assign a with the value of 3. Then we assign the value of a to b. Hence, the value of a, which is 3, is copied to the variable b. Now b has the value of:


Assignment With Expresison

And we are not constrained with just a literal or variable, we can actually assign the result of an expression to a variable. For example:

int a = 5;
int b = a + 3;

So a has the value of 5. And a +3 is adding 5 and 3, which results to 8. So the result 8 is assigned to variable b. So when we print the value of b to the console we get:

Introduction to Java Topics