What happens when an array with a specified size is assigned with values fewer than the specified size?

Java 8Object Oriented ProgrammingProgramming

An array is a data structure/container/object that stores a fixed-size sequential collection of elements of the same type. The size/length of the array is determined at the time of creation.

The position of the elements in the array is called as index or subscript. The first element of the array is stored at the index 0 and, the second element is at the index 1 and so on.

Each element in an array is accessed using an expression which contains the name of the array followed by the index of the required element in square brackets.

For example, if an array of 6 elements is created with name myArray, you can access the element of the array at index 3 as −

System.out.println(myArray[3]); //25

What happens when an array with a specified size is assigned with values fewer than the specified size?

Creating an array in Java

In Java, arrays are treated as referenced types you can create an array using the new keyword similar to objects and populate it using the indices as −

int myArray[] = new int[7]; myArray[0] = 1254; myArray[1] = 1458; myArray[2] = 5687; myArray[3] = 1457; myArray[4] = 4554; myArray[5] = 5445; myArray[6] = 7524;

Or, you can directly assign values with in flower braces separating them with commas (,) as −

int myArray = { 1254, 1458, 5687, 1457, 4554, 5445, 7524};

Accessing array elements greater than its size

Though, you can refer the elements of an array by using the name and index as −

myArray[5];

You cannot access the elements that are greater to the size of the array. i.e. If you create an array with 7 elements, as you observe in the diagram you can access up to myArray[6].

What happens when an array with a specified size is assigned with values fewer than the specified size?

If you try to access the array position (index) greater than its size, the program gets compiled successfully but, at the time of execution it generates an ArrayIndexOutOfBoundsException exception.

Example

public class AccessingElements {    public static void main(String[] args) {       //Creating an integer array with size 5       int inpuArray[] = new int[5];       //Populating the array       inpuArray[0] = 41;       inpuArray[1] = 98;       inpuArray[2] = 43;       inpuArray[3] = 26;       inpuArray[4] = 79;       //Accessing index greater than the size of the array       System.out.println( inpuArray[6]);    } }

Run time exception

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6    at myPackage.AccessingElements.main(AccessingElements.java:17)

What happens when an array with a specified size is assigned with values fewer than the specified size?

Updated on 02-Jul-2020 12:20:04

Discussion :: Arrays - General Questions (Q.No.1)

1. 

What will happen if in a C program you assign a value to an array element whose subscript exceeds the size of array?

[A]. The element will be set to 0.
[B]. The compiler would report an error.
[C]. The program may crash if some important data gets overwritten.
[D]. The array size would appropriately grow.

Answer: Option C

Explanation:

If the index of the array size is exceeded, the program will crash. Hence "option c" is the correct answer. But the modern compilers will take care of this kind of errors.

Example: Run the below program, it will crash in Windows (TurboC Compiler)

#include<stdio.h> int main() { int arr[2]; arr[3]=10; printf("%d",arr[3]); return 0; }

Since C is a compiler dependent language, it may give different outputs at different platforms. We have given the Turbo-C Compiler (Windows) output.

Please try the above programs in Windows (Turbo-C Compiler) and Linux (GCC Compiler), you will understand the difference better.

Vaishnavi said: (Aug 2, 2010)  
When I tried the program in the compiler an error namely "invalid initialization"appeared. So the compiler has thrown an error.

Then why could not B option be the correct answer. Could anyone please explain me.

Sundar said: (Aug 3, 2010)  
Hi All, I have tested the above program in Turbo C, it crashes at run time as explained (as given in Option C). In GCC it shows the output as '10'. Here the compiler takes care of this kind of situation (as given in Option D). And I have tested the same concept in Java as given below: public class Test { public static void main(String [] args) { int arr[] = new int[2]; arr[3] = 10; System.out.print("The output is : " + arr[3]); } } It gives the following Run time error (as given in Option C): Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Test.main(Test.java:8)

Therefore, I conclude that there are more possibilities of program crash or termination. So option C is correct.

Gajendra Gayakwad said: (Sep 3, 2011)  
Because in c language bound checking is performed by compiler array size always be given by programmer side.

Raj said: (Sep 7, 2011)  
The code which I tried in turbo C is #include<stdio.h> int main() { int arr[3]={1,2,3}; arr[5]=6; printf("%d",arr[5]); return 0; } This program prints the output as 6.

Can anyone explain please ?

Vishwas said: (Jan 6, 2012)  
For character array there is an indication of end of the string by null char, but in integer array there is no such end, if there is an free space at address arr[5] in RAM it will get allocated by value 6.

Cybog said: (Jul 23, 2012)  
Even if some value is already present at that location, it will be overwritten. So if some important value like count or status is stored there, it may lead to unexpected o/p or program crash.

Arunesh said: (Dec 29, 2012)  
I have tried the program but the program gives me the out put 10 . I have tried on indiabix online compiler #include<stdio.h> int main() { int arr[2]; arr[3]=10; printf("%d",arr[3]); return 0; }

please explain how?

Swathi Gs said: (Aug 15, 2013)  
In GCC it shows the output as '10'. Here the compiler takes care of this kind of situation (as given in Option D).

please explain this.

Naresh said: (Nov 12, 2013)  
What is a magic matrix?

Sujeet Kumar said: (Jun 16, 2014)  
When I tried the program in the compiler an error namely "invalid initialization"appeared. So the compiler has thrown an error.

Priyanka Kumari said: (Sep 6, 2014)  
I write the same program but it shows me answer 10. I executed in the compile given below and execute it it also shows result 10. Then how can we decide appropriate option? it creates ambiguity.

Vasuvandan said: (Sep 23, 2014)  
Sometimes it throws error and other times it assigns value even array bound exceeds.

Pritam said: (Dec 20, 2014)  
I write the same program in Turbo C and Linux. It shows me answer 10. Compiler not given any type of error. Can you explain me?

Difu said: (Jan 30, 2015)  
#include<stdio.h> #define SQR(x) (x*x) int main(){ int a,b=3; a= SQR(b+2); printf("%d",a); return 0; }

What is the output of this program? why not 25?

Saloni said: (Feb 3, 2015)  
I tried it on Turbo C and get result 10.

Shiva said: (Mar 21, 2015)  
I have tried in my compiler but came out of editor? Anyone explain?

Nar Singh Yadav said: (Mar 22, 2015)  
What does the following declaration means int (*ptr) [10];?

Arockiasamy.k said: (Mar 23, 2015)  
Answer is 11. Because the x value passed as 3+2. So, SQR(x)(x*x) change into as SQR (3+2(3+2*3+2). So, the operator priority multiplication get the first priority. = (3+2*3+2).

= (3+6+2) = 11.

Manojkumar said: (Aug 10, 2015)  
Very good.

Haritha said: (Apr 13, 2016)  
I tried it in linux compiler it gave the output as 10.

Amertarasu said: (Jul 21, 2016)  
Isn't in the case why ArrayIndexOutOfBounds Exception exists?

Anand Kumar said: (Oct 4, 2016)  
I also tried and found no error, it still gave the expected output, no compilation or runtime error.

Priya said: (Oct 25, 2016)  
If the number of elements exceeds the array size, where the exceeded elements will be stored exactly.

For ex: If the array size is [5], if i enter six elements where the sixth element is stored. Whether it overwrites the array size or it stores some other location.

Divya said: (Jun 7, 2017)  
On linux compiler will give some only warnings like array size is exceeded.and it will give o/p like this, int a[2]={1,2,3,4,5};

o/p:1,2 only will give.

Rama said: (Sep 8, 2017)  
Why we don't do this program in java?

Subhakar said: (Apr 18, 2020)  
@ALL.

C compiler doesn't do bounds checking.

SB said: (Sep 12, 2020)  
When I tried it with GDB compiler, it gave the output 10. #include<stdio.h> int main() { int arr[2]; arr[3]=10; printf("%d",arr[3]); return 0; } 10

Program finished with exit code 0.