• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why doesn't this code not get an exception or not Compile?  RSS feed

 
Constance Cummings
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am studying for the Java Associate Certification Exam. So I am trying everything I can to understand Strings and arrays. Here is a code snippet that works - I thought it would fail and the results were are surprise. Can someone tell me what is going on?

it prints out:

null
huh?!1.23
[huh?!1.23, abc, def]

First of all I thought it would get an arraystore exception at line 2. But it didn't.
At line 11 it let me perform string operations on it and replace characters.

I get that it is appending 1.23d to a null string, but am surprised that the actual string "null" is stored in strings[0]. Why is it doing that?

 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The thing with "null" has to do with how the + operator works with Strings, which is as a concatenation operation.

The expression strings[0] += 1.23d is equivalent to strings[0] = strings[0] + 1.23d

The JLS specifies the behavior here: https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18.1 and here: https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.11

Basically, the rules say that the null reference strings[0] will be converted to the string "null" and then the value 1.23d will be converted to a Double which is then converted to a String and then concatenated to "null".
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...and welcome to the Ranch
 
Constance Cummings
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so much!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!