java.lang.NegativeArraySizeException while cloning in java


In this Example we are going to understanding the clone in Java and its exceptons..

Error Message :
Exception in thread "main" java.lang.NegativeArraySizeException: -5
       at com.si.cloneSample.<init>(cloneSample.java:9)
       at com.si.cloneSample.main(cloneSample.java:17)

Error Description :

package com.si;

public class cloneSample implements Cloneable {
      
       int number;
       Integer[] intArray;
       cloneSample(int num){
              number  = num;
              intArray= new Integer[number];
             
       }
       public Object clone() throws CloneNotSupportedException {
              return super.clone();
       }

       public static void main(String[] args) {
              cloneSample samp1 = new cloneSample(-5);
              System.out.println(samp1.intArray[0]);
       }

}

In the above example ,the red background color line is giving the exception.
Due to negative number we are getting this error

Solution:

To avoid this exception we can do the positive number check if we don't know the exact value or we should make sure we are giving positive numbers.

package com.si;

public class cloneSample implements Cloneable {
      
       int number;
       Integer[] intArray;
       cloneSample(int num){
              number  = num;
              intArray= new Integer[number];
             
       }
       public Object clone() throws CloneNotSupportedException {
              return super.clone();
       }

       public static void main(String[] args) {
              cloneSample samp1 = new cloneSample(5);
              samp1.intArray[0]= 1;
              System.out.println(samp1.intArray[0]);
       }

}
                         
Output:

1
Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar