How to Declare Variables in Java: Syntax and Examples
In Java, you declare a variable by specifying its
type followed by a name. For example, int age; declares an integer variable named age. You can also assign a value during declaration like int age = 25;.Syntax
To declare a variable in Java, you write the type of the variable first, then the variable name, and optionally assign a value using the = sign. Every declaration ends with a semicolon ;.
- Type: The kind of data the variable will hold (e.g.,
int,double,String). - Name: The identifier you choose to refer to the variable.
- Value (optional): The initial data assigned to the variable.
java
type variableName; type variableName = value;
Example
This example shows how to declare variables of different types and assign values to them. It then prints their values.
java
public class Main { public static void main(String[] args) { int age = 30; // integer variable double price = 19.99; // decimal number String name = "Alice"; // text System.out.println("Age: " + age); System.out.println("Price: " + price); System.out.println("Name: " + name); } }
Output
Age: 30
Price: 19.99
Name: Alice
Common Pitfalls
Common mistakes when declaring variables include:
- Forgetting the semicolon
;at the end of the declaration. - Using a variable before declaring it.
- Choosing invalid names (like starting with a number or using spaces).
- Assigning a value of the wrong type (e.g., assigning text to an
intvariable).
java
public class Main { public static void main(String[] args) { // Wrong: missing semicolon // int number = 10; // Wrong: using variable before declaration // System.out.println(value); // int value = 5; // Wrong: invalid variable name // int 1stNumber = 10; // Wrong: type mismatch // int count = "five"; // Correct way: int number = 10; System.out.println(number); } }
Output
10
Quick Reference
Remember these tips when declaring variables in Java:
- Always specify the type before the variable name.
- End each declaration with a semicolon.
- Variable names should start with a letter or underscore, no spaces.
- Assign values compatible with the variable's type.
Key Takeaways
Declare variables by writing the type followed by the variable name and a semicolon.
You can assign a value during declaration using the equals sign.
Variable names must follow Java naming rules and cannot start with numbers.
Always end declarations with a semicolon to avoid syntax errors.
Assign values that match the declared variable type to prevent errors.