Static fields with default string values cause uncaught TypeError, since string pool is not yet initialized
See original GitHub issueIt will fail to execute with “app.js:445Uncaught TypeError: Cannot read property ‘0’ of undefined”
How to reproduce
public final static String CONST1 = "FIRST";
public final static String CONST2 = "SECOND";
boolean isTrue = (new Random().nextBoolean());
StringBuffer buf = new StringBuffer(10);
buf.append((isTrue ? CONST1 : CONST2)).append(" ");
System.out.println(buf.toString());
Expanding it works
public final static String CONST1 = "FIRST";
public final static String CONST2 = "SECOND";
boolean isTrue = (new Random().nextBoolean());
StringBuffer buf = new StringBuffer(10);
if (isTrue)
{
buf.append(CONST1).append(" ");
}
else
{
buf.append(CONST2).append(" ");
}
System.out.println(buf.toString());
Issue Analytics
- State:
- Created 7 years ago
- Comments:6 (6 by maintainers)
Top Results From Across the Web
String initialization in Java - Stack Overflow
I know that for 3rd initialization above, the the string object is initialized in the string pool and the 4th has nothing to...
Read more >Guide to Java String Pool - Baeldung
In this quick article, we'll explore the Java String Pool — the special memory region where Strings are stored by the JVM.
Read more >What is Java String Pool? - DigitalOcean
We know that String is a special class in java and we can create String objects using a new operator as well as...
Read more >node-mssql | Microsoft SQL Server client for Node.js
useUTC - A boolean determining whether or not to use UTC time for values without time zone offset (default: true ). Default connection...
Read more >What is the concept of String Pool in java? - Edureka
If the string already exists in the string pool, a reference to the pooled instance returns.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
I found the reason. Usually, javac does not put
getstatic
instructions in such cases, instead it can inline constants withldc
. However, for some reason (probably, a bug) javac does not inline constants in conditional expressions.CONST1
andCONST2
do not get their value via<clinit>
method, instead they have default values specified. TeaVM initializes them via$rt_s
, which requires string pool to be prepared. String pools are initialized after all declarations, so string pool hasundefined
value when static fields compute their default values. A probable solution would be to initialize string static fields after initialization of string pool.