aspose file tools*
The moose likes Beginning Java and the fly likes Understanding how this code works.. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Understanding how this code works.." Watch "Understanding how this code works.." New topic

Understanding how this code works..

Viv Richard

Joined: Jul 08, 2007
Posts: 5
From my book(HeadFirst Java), I was doing an exercise. This exercise was about putting together few pieces of codes which were already provided and also coming up with the provided output. I did the putting together part(which I think is the easiest part, it compiles and gives the required output as well). But I'm having hard time understanding the logic. Here below is the code and expected output:
class CodeMagnets

public static void main (String[] args){

int z = 3;

if (z >2)

while (z >0)
z = z - 1;

if (z == 1)
z = z - 1;

if (z == 2)
System.out.print("b c");

}//end of while
}//end of main
}//end of class


Expected Output:

C:\>java CodeMagnets
a-b c-d


Now my questions are mainly regarding those if statements. HOW or WHY making if statement with z, >, = and numeric value could put those letters in such orderly position?

I can READ the code as which line is doing what such as decrementing, initializing variables, if statement and so on. But I'm having hard time with logic. Help please.
Kail Limas

Joined: Jul 09, 2007
Posts: 24
The Question you have to ask yourself is: When will the code be used? Under which condition is for example the first if clause used? It should be easy to see then.
Jon Anslow

Joined: May 05, 2006
Posts: 16

Hi Viv,

your first if statment is using the > (greater than operator) and is checking "is current value of z variable greater than 2" z is currently 3 so it is true. Code in if statment will be executed.

The while loop will be executed until the test condition is false. Again, the condition here is using the > operator.

The other operator used in your code is == which is testing is z int value equal to another int value.

I hope these explanations help you look over your code, to understand the logic and what is happening.

Viv Richard

Joined: Jul 08, 2007
Posts: 5
Thanks a lot guys. The way I was not right way of thinking. That's why I was having hard time understanding.
I was thinking a-b c-d and 3,2,1,0 as their position in a string. So if my map had to be implemented, the position would have been 0 1 2 3. But the situation here is different abd I realized it. Thanks a lot. I will be back here and talk to you guys again.

I agree. Here's the link:
subject: Understanding how this code works..
Similar Threads
Be the compiler excercise in chap 3
Some Runtime vs. Compile Time SCJP 6.0 Mock Exam Questions
Where to find ans for mock test by Valentinn Cretazz
Sun Cirtification