File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Plz explain me the code

 
Priya dharshini
Ranch Hand
Posts: 78
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test{
public static void main(String []args){
int [] [] [] x=new int[3][][];
int i, j;
x[0]=new int[4][];
x[1]=new int[2][];
x[2]=new int[5][];
for(i=0;i<x.length;i++)
for(j=0;j<x[i].length;j++){
x[i][j]=new int[i+j+1];
System.out.println("size="+x[i][j].length);
}
}
}

how many lines of output will be produced?(choose one)
A.7
B.9
C.11
D.13
E.Compilation fails
F.An exception is thrown at run tim

Ans: C

Plz explain me the code
 
Marcelo Ortega
Ranch Hand
Posts: 528
Eclipse IDE Hibernate Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi TR. Welcome to JavaRanch (the best site on the planet) .

What is it you don't understand about the code?
 
Priya dharshini
Ranch Hand
Posts: 78
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the way of the for loop..execution.
 
Marcelo Ortega
Ranch Hand
Posts: 528
Eclipse IDE Hibernate Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically we have a three dimensional array, which is nothing more than an array of an array of an array.

The first loop goes through the first array, which holds a 2D array.
The second loop goes through the second array and constructs a third array at the index of [i][j]. Then it simply prints out the length of the newly created 3D arrays.

hth.

Cheers, Marzo.
 
Priya dharshini
Ranch Hand
Posts: 78
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank u.. But How the output be 11? plz explain me..
 
Marcelo Ortega
Ranch Hand
Posts: 528
Eclipse IDE Hibernate Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The nested loop (the second one) goes through each element of the second array. So the first iteration of the outter loop (on x[0]) will cause the inner loop to 4 times (x[i].length), then 5 times, then 2. 11 LINES of out put all up.

Maybe i didn't explain myself properly, it's just that my boss is walking around and i pause, then unpause the explanation.
 
Marcelo Ortega
Ranch Hand
Posts: 528
Eclipse IDE Hibernate Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
x[0].length = 4
x[1].length = 2
x[2].length = 5
 
Priya dharshini
Ranch Hand
Posts: 78
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank U.. Marzo Kaahn .. I got it..
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic