Variables

Variables are containers which are used to store some value. There are different types of variables which store data on the basis of type their type. For example, int type variable will store intergers.

Types

  • int - stores numbers without decimal point.
  • double - stores numbers with decimal point.
  • float - stores numbers with decimal point but precision is higher.
  • char - stores single character.
  • boolean - stores either true or false.

Rules for assigning variables names

  1. Variable names can only consist of letters, digits, underscores (_), and dollar signs ($).
  2. They must start with a letter, underscore, or dollar sign.
  3. They are case-sensitive, meaning that myVariable and myvariable are treated as different variables.
  4. You cannot use Java keywords (e.g., int, if, class) as variable names.
  5. Variable names cannot contain spaces.

Note: There is no strict limit on the length of a variable name, but it's a good practice to keep variable names reasonably short and meaningful.

Declaring Variables

Specify the data type of variable and then write its name and finally assign it some value.

Note: Names of variables must be unique. The variables are identified by these unique names. These names are called identifiers. For example, in the above program, age is an identifier.

Printing value of a Variable

Specify the data type of variable and then write its name and finally assign it some value.

We can also declare a variable first and then assign it some value later.

Changing the value of a Variable

We can also change the value of a variable.

Final Variables

Final variables are the variables whose values can not be changed once assigned.

Dealing with String type Variables

String type variables store text which is enclosed in double quotation marks.

String Concatenation

String type variables can be joined / concatenated using "+" operator.

Declaring many variables

We can declare many variables in one line, if their data type is same.

Assigning same value to many variables

We can assign same value to many variables.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

Which of the following is a valid variable name?

10 XP~3 min
Exercise 2 of 2Easy

To declare an integer variable named 'age', we write: ___ age;

10 XP~2 min