I needed a .txt
file containing a lot of random integers and doubles - one each per line. I came up with the following code:
StringBuilder info = new StringBuilder();
for(int i = 0; i < 10000; i++) {
int id = (int)(Math.random() * 1000);
double weight = Math.random() * 100;
info.append(id)
.append(" ")
.append(weight)
.append("\n");
}
Files.write(Paths.get("something.txt"), info.toString().getBytes());
And it worked as expected. However, when I tried to 'trim down' the code to this:
StringBuilder info = new StringBuilder();
for(int i = 0; i < 10000; i++) {
info.append((int)(Math.random() * 1000))
.append(" ")
.append(Math.random() * 100)
.append("\n");
}
Files.write(Paths.get("something.txt"), info.toString().getBytes());
I received an exception:
java.lang.ClassFormatError: Truncated class file at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:763) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) at java.net.URLClassLoader.access$100(URLClassLoader.java:73) at java.net.URLClassLoader$1.run(URLClassLoader.java:368) at java.net.URLClassLoader$1.run(URLClassLoader.java:362) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:361) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:495)
Error: A JNI error has occurred, please check your installation and try again Exception in thread "main"
This is the first time I encounter such a problem. I tried to play a little with the code and realised that the problem is reproduced if the are more than one call to Math.random()
per append
nesting.
I also tried it with other methods, such as plain old:
int foo() {
return 42;
}
in place of Math.random()
calls. It compiled and executed successfully.
What it is to Math.random()
that it fails here? Are there any other methods that are unsafe to use like that? What is the official term to describe this behaviour? Is this a common differentiation between methods - whether they can be called in such way? What exactly happens here and how does the exception description relate to it?
EDIT: It might be the case that it's just a IDE/JDK/Configuration bug, but I am unsure about it. I am working with this code in IDE IntelliJ IDEA Ultimate Edition version 2018.1.4.0 paired with jdk1.8.0_161.