java面試題:寫代碼使得分別出現StackOverflowError和OutOfMemoryError


今天做了個筆試,這是其中的一道題目:寫代碼使得分別出現StackOverflowError和OutOfMemoryError

1.StackOverflowError

  堆棧溢出錯誤一般是遞歸調用嘛。下面的代碼就可以出現:

package T20131009;
public class StackOverflowTest {
    public static void main(String[] args) {
        method();
    }
    public static void method(){
        for(;;)
            method();
    }
}

運行結果:

  

 2.OutOfMemoryError

   內存溢出一般是出現在申請了較多的內存空間沒有釋放的情形。下面的代碼就可以出現:

package T20131009;
import java.util.ArrayList;
import java.util.List;
public class OutOfMemoryTest {
    public static void main(String[] args){
        List list=new ArrayList();
        for(;;){
            int[] tmp=new int[1000000];
            list.add(tmp);
        }
    }
}

運行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM