I have two questions.
I did the following code to find the ASCII value of $ :
def a = "\$"
def b = (int)a
println b //prints 36
Well I’m happy with the answer. But when I tried to do it in reverse like this, I found I’m missing something :
def a = 36
String b = a
println b // getting output only 36
Question 1:
So my first question is why it prints 36 and why not $? Am I wrong here?
Well if the same first code block is re-written as:
def a = "\$"
def b = a as int
println b
If I run this program I get an error like this :
Caught: java.lang.NumberFormatException: For input string: "$"
at T.run(T.groovy:2)
Even though I’m trying to do the same as before. I’m getting an error.
Question 2:
So why does the as keyword doesn’t work here and does def a = (int)b is not equal to to def a = b as int? Explain me.
Thanks in advance.
when you cast a string to int it’s ok while you have one char in it, so we can say you cast a char to int, when you try to cast int to a string i think it uses toString method or something like that. Try to cast 36 to char and you’ll see your ‘$’