Variables in Java with example

In Java, variables are used to store values in the program. A variable has a name, a type, and a value. The type determines what kind of data a variable can store, and the value is the data that is stored in the variable.


Here's a basic example of declaring a variable in Java:


int number; 


In this example, number is the name of the variable, int is the type, and the value is not yet assigned. You can assign a value to the variable using the equal sign (=), like this:


number = 10;

In Java, you can declare multiple variables of the same type on the same line, like this:


int a, b, c;

And you can also declare and initialize variables on the same line, like this:


int a = 10, b = 20, c = 30;

Java supports several built-in data types, including:


  • int: for whole numbers
  • double: for floating-point numbers
  • char: for single characters
  • boolean: for true/false values
  • String: for sequences of characters


It's important to choose the correct data type for your variables based on the type of data they will store. For example, you should use an int data type to store whole numbers, and a double data type to store floating-point numbers. This helps to ensure that your program is efficient and avoids errors due to type mismatches.