1

I have read this answer here, but what would happend if you keep adding strings to the same variable? after reching the max_value. Assuming the computer have enough resources to do this. For example:

 String s="";

 double n=Math.pow(2,32);

 for(int i=0;i<n;i++)
 {
   s=s+'x';
 }
  • 1
    Probably throws an OutOfMemoryException – Spectric Oct 09 '20 at 15:04
  • 2
    Is there something stopping you from running your code in order to see what happens? – Abra Oct 09 '20 at 15:26
  • @Abra: doing this stepping by 1 will take hours at least, maybe days. OP: if you step by say 10-100 chars at once you will get quicker but equally representative results. Note as covered in the older and more complete dupe https://stackoverflow.com/questions/1179983/ in Java 9 up Strings containing only Latin1 chars occupy less storage than others, so you might want to test both Latin1 and non-Latin1 cases. Also note `long` can represent pow(2,32) and compute it more easily as `1L<<32`, but `int` cannot count to this value, so use `long i`. – dave_thompson_085 Oct 09 '20 at 15:37

2 Answers2

0

Well, what I did was:

    public static void main(String args[])
    {
        String s = new String(new char[Integer.MAX_VALUE-1]);
        s = s + ".";
    }

What I obtained was:

java.lang.OutOfMemoryError: Requested array size exceeds VM limit
Kitswas
  • 1,134
  • 1
  • 13
  • 30
0

Technically the limit is Integer.MAX_VALUE characters, however, some JVMs can't actually create an array of length Integer.MAX_VALUE so you can find a practical limit is a few characters less.

public static void main(String[] args) {
    for (int i = 0; i < 1000; i++) {
        try {
            char[] chars = new char[Integer.MAX_VALUE - i];
            System.out.println("Created new char[MAX_VALUE-" + i + "]");
            break;
        } catch (OutOfMemoryError oome) {
            if (i == 0)
                oome.printStackTrace();
        }
    }
}

on my Windows 10 Java 8 update 251 machine prints

java.lang.OutOfMemoryError: Requested array size exceeds VM limit
    at A.main(A.java:12)

Created new char[MAX_VALUE-2]
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Thank you for the answer. I'm going to investigate more about the 'OutOfMemoryError'. Now, theoretically speaking, what would happend if the JVM can create such array? after the array reach the Integer.MAX_VALUE it will throw me an OutOfMemoryError? – NewProgrammer Oct 09 '20 at 17:51
  • It seems that OutOfMemoryError extends VirtualMachineError, so, correct me if I'm wrong the error will not appear in a theoretical enviorment, where there is no JVM involved, I know i'm being a little abstract with the question, but there is a question in one of my classes that is something like the one I asked, and can't find information anywhere – NewProgrammer Oct 09 '20 at 18:07