[[painless-variables]] === Variables <> variables to <> values for <> in expressions. Specify variables as a <>, <>, or <>. Variable operations follow the structure of a standard JVM in relation to instruction execution and memory usage. [[declaration]] ==== Declaration Declare variables before use with the format of <> <>. Specify a comma-separated list of <> following the <> to declare multiple variables in a single statement. Use an <> statement combined with a declaration statement to immediately assign a value to a variable. Variables not immediately assigned a value will have a default value assigned implicitly based on the <>. *Grammar* [source,ANTLR4] ---- declaration : type ID assignment? (',' ID assignment?)*; type: ID ('[' ']')*; assignment: '=' expression; ---- *Examples* * Different variations of variable declaration. + [source,Painless] ---- <1> int x; <2> List y; <3> int x, y, z; <4> def[] d; <5> int i = 10; ---- + <1> declare a variable of type `int` and identifier `x` <2> declare a variable of type `List` and identifier `y` <3> declare three variables of type `int` and identifiers `x`, `y`, `z` <4> declare a variable of type `def[]` and identifier `d` <5> declare a variable of type `int` and identifier `i`; assign the integer literal `10` to `i` [[assignment]] ==== Assignment Use the `equals` operator (`=`) to assign a value to a variable. Any expression that produces a value can be assigned to any variable as long as the <> are the same or the resultant <> can be implicitly <> to the variable <>. Otherwise, an error will occur. <> values are shallow-copied when assigned. *Grammar* [source,ANTLR4] ---- assignment: ID '=' expression ---- *Examples* * Variable assignment with an <>. + [source,Painless] ---- <1> int i; <2> i = 10; ---- + <1> declare `int i` <2> assign `10` to `i` + * <> combined with immediate variable assignment. + [source,Painless] ---- <1> int i = 10; <2> double j = 2.0; ---- + <1> declare `int i`; assign `10` to `i` <2> declare `double j`; assign `2.0` to `j` + * Assignment of one variable to another using <>. + [source,Painless] ---- <1> int i = 10; <2> int j = i; ---- + <1> declare `int i`; assign `10` to `i` <2> declare `int j`; assign `j` to `i` + * Assignment with <> using the <>. + [source,Painless] ---- <1> ArrayList l = new ArrayList(); <2> Map m = new HashMap(); ---- + <1> declare `ArrayList l`; assign a newly-allocated `Arraylist` to `l` <2> declare `Map m`; assign a newly-allocated `HashMap` to `m` with an implicit cast to `Map` + * Assignment of one variable to another using <>. + [source,Painless] ---- <1> List l = new ArrayList(); <2> List k = l; <3> List m; <4> m = k; ---- + <1> declare `List l`; assign a newly-allocated `Arraylist` to `l` with an implicit cast to `List` <2> declare `List k`; assign a shallow-copy of `l` to `k` <3> declare `List m`; <4> assign a shallow-copy of `k` to `m`