JavaFX is a type-safe and type-strict scripting language. Therefore, variables (and anything which can be assigned to a variable including functions and expressions) in JavaFX must be associated with a type which indicates the expected behaviour and representation of the variable. Let us see how to create and assign values to variables in JavaFX.
The def keyword is used to declare and assign constant values. Once a variable is declared with the def keyword and assigned a value, it is not allowed be reassigned a new value. On the other hand, the var keyword declares variables which can be updated at any point after their declaration and initialization.
Variables may be bound to an expression. Whenever a value or other variable in the expression changes, the bound variable is updated automatically.
In the previous code sample, variable y will be updated with with value x + 10 whenever x changes.
When declaring your variables you have the options of specifying the type as shown below:
Or, you can leave out the type of the variable during declaration and the compiler will automatically convert the variable to its proper type based on the expression assigned to the variable as shown below:
Variable location will automatically be coerced into being a type of String during compilation since the first assignment is a string literal.
Variables can have three distinct scopes which implicitly indicates the access level of the variable when it is being used.
Script Level - Script variables are defined at any point within the JavaFX script file outside of any code block (including class definition). When a script-level variable is declared, by default it is globally visible within the script and is not accessible from outside the script (without additional access modifiers).
Instance Level - Variables that are defined at the top-level of a class is referred to as an instance variable. An instance level is visible within the class by the class members and can be accessed by creating an instance of the class.
Local Level - The least visible scope are local variables. They are declared within code blocks such as functions. They are visible only to members within the block.