aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes what is the output and why? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "what is the output and why?" Watch "what is the output and why?" New topic
Author

what is the output and why?

sonir shah
Ranch Hand

Joined: Nov 01, 2001
Posts: 435

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

Joined: Aug 07, 2001
Posts: 418
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

Joined: Nov 01, 2001
Posts: 435
Thanx Rashmi
R K Singh
Ranch Hand

Joined: Oct 15, 2001
Posts: 5371
<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


"Thanks to Indian media who has over the period of time swiped out intellectual taste from mass Indian population." - Chetan Parekh
anand raman
Ranch Hand

Joined: Jun 06, 2001
Posts: 66
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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: what is the output and why?