File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes simple code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "simple code" Watch "simple code" New topic

simple code

sony kolla

Joined: Sep 25, 2008
Posts: 14
public class Exercise1b {

public static void main(String[] args) {

int x = 5;
while(x > 1)
x = x - 1;
if(x < 3)
System.out.println("small x");




small x
small x

my doubt is here x = 5 then why this condition

if(x < 3)
System.out.println("small x");

working and it is giving small x as output. i know this is a silly and simple doubt please dont mind please anyone answer me thank you.
Jason Kirk

Joined: Oct 07, 2008
Posts: 5
Hi Sony,

In this case, when you first enter the while loop, x = 4 since you have x = x - 1 in the beginning. When x becomes 2 in the loop, then the program hits the "if" statement which prints "small x". The program goes to the beginning of the while loop again, sees that x = 2 (so it passes), then it decrements x by 1 so now x = 1. The program would hit the "if" statement since x = 1 is less than 3 so it would print "small x" again. Since x = 1 now, the program would exit out of the while loop.

Hope that probably over-complicated explanation helps.

- Jason
Jules Bach
Ranch Hand

Joined: Apr 28, 2008
Posts: 71
If you indent your loops it becomes easier to follow the program execution..

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45301
Jules Bach is quite right; we have code tags which preserve the indentation and ought to be used whenever you post code.

And that is not a silly question at all; lots of people get confused about that sort of loop.
It is sorta covered in the JavaRanch Style Guide.
subject: simple code
It's not a secret anymore!