It appears you have not yet registered with DEVPPL. To register please click here... (it's fast, easy and free!)

Forum

Log In Sponsors
Board index Programming Java Forum

how does this code compile?

how does this code compile?

Postby jihnd on Fri Oct 13, 2006 12:54 am

Hi,

I’ve been twisting over this for 3nights now and I’m officially in groundhog day. I’m working though Headfirst java, and I’ve come across a piece of code that I just cant understand – it’s from an excersise where you’re meant to figure out the output, so here it is inc output, and I’ll explain what I do & don’t get, any help would be so so so much appreciated, I might cry if I actually understand. I’ve even had a dream about this. seriously… need… help…

~~~~~~~~~~~~~~~~~~~~~~~~~~~

public class Mix4 {
int counter = 0;
public static void main(String [] args) {
int count + 0
Mix4 [] m4a = new Mix4[20];
Int x = 0;
while (x<9) {
m4a[x] = new Mix4();
m4a.counter = m4a[x].counter + 1
count = count + 1
count = count + m4a[x].maybeNew(x)
x = x + 1
}
System.out.println(count + “ “
+ m4a[1].counter);
}

public int maybeNew(int index) {
if (index<5) {
Mix4 m4 = new Mix4();
m4.counter = m4.counter + 1;
return 1;
}
return 0;
}
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~

output is:
14 1


so I understand the maybenew method takes the int index arguement which is passed as x which is declared as 1, which is less than 5, therefore the return value is 1. 1 array and 1 object created from class….
I guess I’d like to know how the compiler reads this code, how those output values (count + m4a[1].counter)
are arrived at, the addition of what iterations in which loop, what numbers when? Basically, can anyone could help walk me through how that output was computed?

Thanks for reading
jihnd
 
Posts: 0
Joined: Fri Oct 13, 2006 12:52 am

Who is online

Users browsing this forum: No registered users and 2 guests