Declaration of Variables in Java
Let's remember that Java is a statically typed programming language, which means that it checks the typing of variables in compilation rather than in execution. This feature makes it so that Java has particular ways of declaring and initializing variables, and below we'll see each one of them along with some rules to keep in mind for naming variables.
Rules for Variable Naming
Case-Sensitivity: All variable names are case sensitive, which means that the variable num
is different from the variable Num
.
Label-Rule: Variables must start with a letter, an underscore ( _ ) or the dollar sign ( $ ), followed by a combination of letters, numbers, underscores or dollar signs.
Not-Keyword: Variable names cannot be the same as a reserved Java language keyword.
Explicit Declaration
The standard way to declare a variable is to place its type before the variable name as follows:
byte min;
int entero;
char letra;
This works for both primitive types and other data types.
String cadena;
Now, let's see how to assign values to these initialized variables.
min = 8;
entero = 3435;
letra = 'S';
We could have done this in a single sentence like this:
byte min = 8;
int entero = 3435;
char letra = 'S';
Implicit Declaration
Starting from Java 10, local variables can use type inference. This way, it is not necessary to specify the type since Java will infer it automatically. Keep in mind that this only works for local variables inside a method.
// this variable will be of type int
var valor = 345;
Alpha Notation
When using alpha notation, you can force the variable to be of a determined type. This is a feature of Java exclusively available for numeric types.
// this variable will be of type float
var valorFloat = 345f;
// this variable will be of type double
var valorDouble = 345d;
// this variable will be of type Long
var valorLong = 345L;