• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mock Exam Q

 
Tanuja Vaid
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class SomeClass
{
public static void main(String args[])
{
int size = 10;
int[] arr = new int[size];
for (int i = 0 ; i < size ; ++i) System.out.println(arr[i]);
}
The above code prints 0 ten times.Shouldn't it print 0 only nine times.Any comments/suggestions
TIA
 
Jamal Hasanov
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Tanuja,
When you declare an array, all fields of array are initialized to default values( Classes to null,numeric values to 0, boolean values to false)
That's all
Jamal
 
Alf Fernandez
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tanuja,
The size of the array you has declares, is 10 (int size = 10; int[] arr = new int[size]
And the for loop, goes from the first element to the last (the first element of an array is 0, and de last, is array.length minus one)
for (int i = 0 ; i < 10 ; ++i)
So, it prints the contents of the array, that are 10 ceros.
[The above code prints 0 ten times.Shouldn't it print 0 only nine times.Any comments/suggestions]

Alf.
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
midirectorio,
Please read the Javaranch Naming Policy and change your publicly displayed name to comply with our unique rule. Thank you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic