• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is the output and why?

 
sonir shah
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

class ArrayTest
{
public static void main(String[] args)
{
int ia[][] = { {1, 2}, null };
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
System.out.println(ia[i][j]);
}
}
 
Rashmi Tambe
Ranch Hand
Posts: 418
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
U shuld have tried this code na du would have gor the answer... anyways...the o/p is:
1
2
Exception in thread "main" java.lang.NullPointerException
at ArrayTest.main(ArrayTest.java:8)
this is because ...
int ia[][] = { {1, 2}, null };
and when the loop tries to print ia[1][0], the exception is throws as the second reference in multidiamentional array ia is null.
Hope this helps.
Rashmi
 
sonir shah
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx Rashmi
 
R K Singh
Ranch Hand
Posts: 5384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<pre>
class ArrayTest
{
public static void main(String[] args)
{
int ia[][] = { {1, 2}, null };// 1: compiles
int ib[] = {1, null}; // 2: DOES NOT compile
}
}
</pre>
Hi
why stmt 2: does not compile while 1: compiles
thanks in adv.
------------------
Regards
Ravish
 
anand raman
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi ravish
int ib[] = {1, null}; // 2: DOES NOT compile
You are defining a single dimensional array of integer primitives. By doing this you are trying to assign a null value to a primitve int, which cant happen. Thus the compiler complains.
On the other hand.
int ia[][] = { {1, 2}, null };
is a multi dimensional array and expects multiple primitive int arrays. By doing this you are setting the second primitive int array to null..
Hope this helps
Anand
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic