What is the role of array capacity in java? In the below code i set array capacity to 2 there are 4 array is defined & no error. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is the role of array capacity in java? In the below code i set array capacity to 2 there are 4 array is defined & no error.

public class Program { public static void main(String[] args) { {String [] myNames =new String [2]; } String[ ] myNames = { "A", "B", "C", "D"}; System.out.println(myNames[3]); } }

7th Feb 2017, 1:16 AM
Sahil
Sahil - avatar
2 Answers
+ 2
When you added the curly braces { } around the first myNames variable you created a new inline code block defining its scope within that block only. It is allocated to memory. Never initialized or assigned. Then immediately deallocated from memory and made available for garbage collection. Thus could never be used. You then defined a new variable outside that block with the same name. If you were to remove the curly braces you'd get an error and your code wouldn't compile. Likewise, if you moved the curly braces around the second declaration of the variable myNames, you'd end up getting an array out of bounds error as you'd be attempting to access an element beyond the end of the array.
7th Feb 2017, 4:57 AM
ChaoticDawg
ChaoticDawg - avatar
+ 6
cause the first is a local variable only available inside the main function the other one isnt and with that println u r calling the second one so will print D
7th Feb 2017, 1:27 AM
Kawaii
Kawaii - avatar