Java Reference
In-Depth Information
Declaring Variables
Scripting languages are loosely typed. The type of a variable is not known at compile-
time. The type of a variable can change during the execution of the program. The type of a
variable is determined at runtime based on the value stored in the variable. For example,
the same variable can store a number at one point and a string at another. This rule in
Nashorn is significantly different from Java that is a strongly typed language and type of a
variable is known at its declaration.
In Nashorn, the keyword var is used to declare a variable. Variable declaration is
known as a variable statement in ECMAScript terminology:
// Declare a variable named msg
var msg;
Note that, unlike Java, you do not specify the data type of the declared variable in
Nashorn. You can declare multiple variables in one variable statement. The variable
names are separated by a comma:
// Declare three variables
var empId, deptId, emplList;
Tip
in strict mode, it is an error to name a variable either eval or arguments .
A variable is initialized to undefined when declared. I will discuss data types and the
undefined value in the next section. You can also initialize a variable with a value at the
time of declaration:
/* Declare and initialize variables deptId, and empList. deptId is
initialized to the number 400 and empList is initialized to an
array of strings.
*/
var deptId = 400, emplList = ["Ken", "Lydia", "Simon"];
Note that you can create an array in Nashorn using an array literal that contains a
comma-separated list of array elements enclosed in brackets. I will discuss arrays in detail
in Chapter 7.
In nonstrict mode, you can omit the keyword var in the variable declaration:
// Declare a variable named greeting without using the keyword var
greeting = "Hello";
 
 
Search WWH ::




Custom Search