Hi guys do you know of any sites where i can go through some java questions in preparation for a java exam. In the sort of style for example where you are provided a for loop and which isn't in the normal format and then asks you what would x be? or when run what the output would be.

Also the " ++i " thing confuses me, it means that it is iterated beforehand , is that right ? So what kind of questions might involve that?

Just wanna get some exam practise. Thank you.

Also the " ++i " thing confuses me, it means that it is iterated beforehand , is that right ? So what kind of questions might involve that?

Can you answer the following common exam question:

What is the output of the following code snippet?

$i = 17;
$i = -7;

EDIT: Here is a link to Google's first site when I typed in "Java exam questions" into the search engine. There were many, many more.

Hi man, thanks so much for the reply, really helpful. So is what happened with that code that where "$i = -7;" it is assigned the value -7, making above that irrelevant, and then the final println doesnt matter because it prints i and then adds one to it?

Is that right?

Well for starters, the code will output three values of i. What are those values at the time that the code outputs?

Sorry about the "$i", that is PHP syntax. It should be:

int i = 17;
      i = -7;

EDIT: Also, what is the value of i after the code is run?

My answer was


and after the program is run i = -7.

Compiled program answer:


then -7.

So i definately dont understand the ++i concept lol. So what should i be doing ?

Ok the trick is to decide when the variable is incremented. The pre-increment (++i) occurs before the variable is used in the current statement, so in the final output the increment happens before the output. The opposite is true for the post-increment (i++), here the increment occurs after the variable is used in the current statement.

So, the first output only outputs the value of i. That one's easy. The second one outputs the value of i and then increments it (i++) and the final output statement occurs after i is incremented again (++i). The value of i after the code is complete is a trick question, it wouldn't matter the order of the increments, the value would be -7 either way.

I hope this illustrates to you a bit better how increment works. Try this one for more practice:

int a = 0;

Or this slightly harder one involving methods:

public static int squared(int a)
  return a * a;

int b = 7;
int c = squared(b++);
int d = squared(++b);
int e = squared(b);

Hey thanks a lot man, you couldn't have been a bigger help, i totally get it now, i think i was confusing myself between pre (++i) and post (i++) incrementing. And i managed those questions! Thanks again!