Skip to main content

Building Blocks in Java

Variables in Java

Introduction to Variables

In the last lesson, we familiarise ourselves with literals. Nevertheless, In real-life problems, we may often require the storage of data for future use. For this we use something called Variables.

Think of a variable as a box where you can keep things like numbers or words. These boxes can hold different things at different times.

In this lesson, we will focus on the following aspects - 

  1. Creating variables: We will understand how to declare variables in Java. 
  2. Assigning data to variables: You will learn how to allocate values to variables. 
  3. Modifying values assigned to variables: We will explore techniques for changing the data stored in variables.

Let’s jump right in!

Creating Variables

The syntax to create a variable in Java is -

type variableName;

Here, type is one of Java's datatypes, and variableName is the name of the variable. The equal sign is used to assign values to the variable.

Example

string bookName;

Here,

  • "bookName" is the name of the variable.
  • "string" type tells what type of data a variable can hold; in this case, it’s going to be text (we'll learn more about this later).

Remember, in Java, we always need to put a ‘;’ at the end. It's like saying that we're done writing for now.

Assigning data to variables

Once variable creation is done, we can assign a value to it. Here’s how we do it -

  1. First, we declare a variable:
string bookName;
  1. Then we can assign a value to the variable depending on its type. For example, 'bookName' variable is of type “string”, we can assign a text to it. 
bookName = "How to Win Friends and Influence People"

 So now, our bookName variable contains the text "How to Win Friends and Influence People".

Modifying values assigned to variables

Imagine you have a variable with a number in it. You can change that number whenever you want. 

For example, if you have a variable with the number 22 in it and you want to change it to 24, you can do that. Here's how it works:

int age = 22; // we put 22 in the variable name age.
age = 24; // we change the number in the variable to 24.

QUIZ