HOME HTML EDITOR C JAVA PHP

Java Variables: Storing Data

Variables are the fundamental building blocks of any Java program. Think of a variable as a labeled container that holds a specific value in the computer's memory.

Memory Logic: When you create a variable, Java allocates a specific amount of space in the RAM. The label you give to the variable allows you to access or modify that memory location easily.

1. Types of Java Variables

In Java, there are different types of variables meant to store different kinds of data. Here are the most commonly used ones:

String

Stores text, such as "Hello". Text must be surrounded by double quotes.

int

Stores integers (whole numbers), without decimals, such as 123 or -123.

float / double

Stores floating-point numbers, with decimals, such as 19.99 or -19.99.

char

Stores single characters, such as 'a' or 'B'. Values are surrounded by single quotes.

boolean

Stores values with two states: true or false.

2. How to Declare and Initialize Variables

To create a variable, you must specify the type and assign it a value.

Syntax: type variableName = value;
// Declaring an integer variable int myNum = 15; // Declaring a String variable String name = "John"; // Printing the variables System.out.println(myNum); System.out.println(name);

3. Modifying Variable Values

As the name suggests, "variables" can change. You can assign a value to a variable and change it later in the program.

int myNum = 15; myNum = 20; // myNum is now 20 System.out.println(myNum);
The final Keyword:

If you don't want others (or yourself) to overwrite existing values, use the final keyword. This makes the variable a "constant".

final int myNum = 15; // myNum = 20; // This will generate an error

4. Declaring Multiple Variables

You can declare more than one variable of the same type in a single line using a comma-separated list.

int x = 5, y = 6, z = 50; System.out.println(x + y + z);

You can also assign the same value to multiple variables in one line:

int x, y, z; x = y = z = 50; System.out.println(x + y + z);

5. Java Identifiers (Naming Rules)

All Java variables must be identified with unique names. These unique names are called identifiers.

Rule Example
Names can contain letters, digits, underscores, and dollar signs. myVar_1, $price
Names must begin with a letter (or $ and _). score (Good), 1score (Bad)
Names are case-sensitive. myVar and myvar are different
Reserved words (like Java keywords) cannot be used as names. int, boolean (Cannot be names)

6. Variable Categories (Scope)

Depending on where they are declared, Java variables are categorized into three types:

Module Conclusion

Variables are the heart of your data processing. Once you understand how to name and store them, you need to understand the memory they consume. In the next chapter, we will explore Data Types in detail to see how Java optimizes memory for different values.

Next: Java Data Types →