Variables in Java: Declaring and Using Them


Introduction to Variables

Variables are fundamental in Java for storing and manipulating data. They serve as containers that hold values
and can be of various data types. In Java, you need to declare a variable before using it.


Declaring Variables

To declare a variable in Java, you specify the data type, followed by the variable name. Here are some common
data types:


int age;        // Integer
double price; // Double
String name; // String
boolean flag; // Boolean

You can also initialize variables when declaring them:


int quantity = 5;
double discount = 0.1;
String greeting = "Hello, World!";
boolean isJavaFun = true;

Using Variables

Once declared, you can assign values to variables and use them in your Java code. Here's an example of using
variables in a simple program:


public class VariableExample {
public static void main(String[] args) {
int age = 30;
String name = "Alice";

System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

In this code, we declare and assign values to two variables, age and name print them to the console.


Conclusion

Understanding how to declare and use variables is a fundamental concept in Java programming. Variables allow
you to work with data, perform calculations, and build dynamic applications.