JayasreeV
JayasreeV

Reputation: 3

Groovy - The assignment of a string , to a variable of type int results in a number

Assigning empty string or string with letters results in GroovyCastException.Assigning a string with number values results in a number.What operation is happening here?

    int var_1 = 2;
    println var_1 // 2
    var_1 = ""
    println var_1 // GroovyCastException

    int var_1 = 2;
    println var_1 // 2
    var_1 = "2"
    println var_1 // 50

What operation/s results in 50?

Upvotes: 0

Views: 760

Answers (2)

Jainendra
Jainendra

Reputation: 25143

When you do something like this

var_1 = "2"
println var_1 

Then the Unicode value corresponding to the character "2" got printed, which is 50. Similarly if you will try to print the unicode value of "B" or "C" then you will get 66 or 67 as the results.

You can print a result 50 by doing this:

int var_1 = "2"
println var_1 

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500515

It's considering "2" as a single character string, and assigning that character's Unicode value (U+0032 = '2') to the variable. So for example, I suspect if you do this:

var_1 = "A"
println var_1

you'll see 65 on the console

Upvotes: 1

Related Questions