HTML CSS JAVASCRIPT PYTHON JAVA

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

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

Best Practices

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