Java Variables

In this lesson, we will delve into the concept of variables in Java, which are containers for storing data values. Understanding variables is fundamental to programming, as they allow us to store and manipulate data.

Tutorials dojo strip



Types of Variables

In Java, there are several types of variables, each designed to hold different kinds of data:

  • String: Stores text values, such as “Hello”. String values are surrounded by double quotes.
  • int: Stores integers (whole numbers) without decimals, such as 123 or -123.
  • float: Stores floating point numbers with decimals, such as 19.99 or -19.99.
  • char: Stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotes.
  • boolean: Stores values with two states: true or false.




Declaring (Creating) Variables

To create a variable, you need to specify its type and assign it a value using the following syntax:

JAVA

Where type is one of Java’s variable types (e.g., int, String), and variableName is the name of the variable (e.g., x, name). The equal sign (=) is used to assign a value to the variable.




Example: Creating a String Variable

Create a variable called studentName of type String and assign it the value “Alice”. Then, use println() to print the studentName variable:

JAVA



Example: Creating an int Variable

Create a variable called age of type int and assign it the value 25:

JAVA



Declaring Variables without Assigning Values

You can declare a variable without assigning a value initially and then assign the value later:

JAVA



Modifying Variable Values

If you assign a new value to an existing variable, it will overwrite the previous value:

JAVA



Final Variables

If you do not want a variable’s value to be changed after its initial assignment, you can use the final keyword. This declares the variable as “final” or “constant”, making it unchangeable and read-only:

JAVA



Other Types of Variables

Here are examples of how to declare variables of different types:

JAVA

Tutorials dojo strip