Curriculum
In Java, a variable is a container that holds a value. The value of a variable can be changed during the execution of a program. Here are some examples of variables in Java:
int age = 20;
In this example, age
is an integer variable that holds the value 20
.
double height = 1.75;
In this example, height
is a double variable that holds the value 1.75
.
boolean isStudent = true;
In this example, isStudent
is a boolean variable that holds the value true
.
String name = "John";
In this example, name
is a string variable that holds the value "John"
.
int[] numbers = {1, 2, 3, 4, 5};
In this example, numbers
is an array variable that holds the values {1, 2, 3, 4, 5}
.
Scanner scanner = new Scanner(System.in);
In this example, scanner
is an object variable that holds an instance of the Scanner
class.
Note that in Java, you must declare the type of the variable before you can use it. You can also assign an initial value to the variable when you declare it, as shown in the examples above.
In Java, there are rules that you must follow when naming a variable. These rules ensure that your code is readable and easy to understand. Here are the rules for naming a variable in Java:
name
and Name
are two different variables.int
is a keyword and cannot be used as a variable name.x
, use a name like age
or height
that reflects the meaning of the variable.Here are some examples of valid and invalid variable names in Java:
Valid variable names:
int age; double height; String firstName;
Invalid variable names:
int 2years; // variable name cannot start with a number double my-height; // variable name cannot contain a hyphen (-) boolean public; // variable name cannot be a keyword String _address; // variable name can start with an underscore, but it's not a recommended practice
By following these rules, you can create variable names that are easy to understand and help make your code more readable and maintainable.