Results 1 to 3 of 3
  1. #1
    dtacker is offline Member
    Join Date
    Oct 2015
    Location
    Tennessee
    Posts
    4
    Rep Power
    0

    Default Help me understand this While Loop please.

    This is a pretty basic question, but I just want to make sure I understand this fully.

    Below I've posted some code for a while loop. The question asked of me was what will the "j" value be in the printed statement at the end? The answer is 16 but I"m confused as to why this is? I don't see any incrementing for j in this code. I see that j=1 and that we are multiplying j * 2. So why wouldn't the answer simply be 2?


    Java Code:
    public class GeneralTest {
     
        public static void main (String[] args) {
     
     
        int i= 1;
     
        int j = 1;
     
        while (i<5){
     
            i++;
            j=j*2;
     
        }
     
            System.out.println(j);
     
     
        }
     
    }

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Help me understand this While Loop please.

    j = j * 2 says that j is replace by the previous value of j * 2. Now how many times does that happen before the loop exits? It will be easier to visualize this is you work it out with paper and pencil, keeping track of the values. You can also put a print statement inside the loop to watch the variables as they change.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    dtacker is offline Member
    Join Date
    Oct 2015
    Location
    Tennessee
    Posts
    4
    Rep Power
    0

    Default Re: Help me understand this While Loop please.

    Quote Originally Posted by jim829 View Post
    j = j * 2 says that j is replace by the previous value of j * 2. Now how many times does that happen before the loop exits? It will be easier to visualize this is you work it out with paper and pencil, keeping track of the values. You can also put a print statement inside the loop to watch the variables as they change.

    Regards,
    Jim
    Ahhhhh, makes sense now. Thank you

Similar Threads

  1. I Don't Understand The 'Enchanced For Loop'
    By OxigEN. in forum New To Java
    Replies: 2
    Last Post: 11-21-2014, 02:25 PM
  2. I want to understand this...
    By WHM2 in forum New To Java
    Replies: 6
    Last Post: 01-14-2014, 09:51 PM
  3. Replies: 2
    Last Post: 11-07-2011, 02:25 AM
  4. Replies: 1
    Last Post: 10-01-2011, 02:12 AM
  5. Replies: 5
    Last Post: 02-11-2011, 08:33 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •