Java Variables
Variables in Java are used to store data values. Unlike some languages, Java requires you to declare the type of a variable before using it.
Declaring Variables
In Java, you must specify the data type when creating a variable.
Example
public class Main {
public static void main(String[] args) {
int x = 5;
String name = "Ali";
System.out.println(x);
System.out.println(name);
}
}
Try this code
Common Variable Types
int→ stores integers (e.g., 10)double→ stores decimal numbers (e.g., 3.14)char→ stores a single character (e.g., 'A')String→ stores text (e.g., "Hello")boolean→ stores true or false
Declaring Multiple Variables
You can declare multiple variables in one line.
Example
public class Main {
public static void main(String[] args) {
int x = 5, y = 10, z = 15;
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
}
Try this code
Final Variables (Constants)
If you do not want a variable value to change, use the final keyword.
Example
public class Main {
public static void main(String[] args) {
final int x = 10;
// x = 20; // This will cause an error
System.out.println(x);
}
}
Try this code
Variable Naming Rules
- Variable names must start with a letter, $, or _
- They cannot start with a number
- Java is case-sensitive (age and Age are different)
- Do not use reserved keywords
Best Practices
- Use meaningful variable names
- Follow camelCase naming (e.g., userName)
- Keep names short but descriptive
Using Variables in Output
Variables can be used to display dynamic information.
Example
public class Main {
public static void main(String[] args) {
String name = "Ali";
int age = 25;
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
Try this code