Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Feb 2014
    London, UK
    Thanked 0 Times in 0 Posts

    Just a bit of a challenge for a loop

    public class Q12aFrom2011
    int i=1;
    static int s=2;
    i=0; s++;
    System.out.println("test: "+ i +s);

    public static void main (String [] args)
    Q12aFrom2011 t1= new Q12aFrom2011();
    System.out.println("t1: " + t1.i + t1.s);
    Q12aFrom2011 t2=new Q12aFrom2011();
    System.out.println("t2: " + t2.i + t2.s);


    I have got above Java code, and it displays following values:

    test: 03
    t1: 03
    test: 07
    t2: 87
    But I still don't get the way how this loop works? As it's evident, it does somehow work and I even got the solution, but I simply don't understand the steps it's doing in order to get the solution.

    Does anyone got a clue? Can you explain it by step by step please? It's just a few lines and it must be easy for a pro, I am not a pro at all...It's like a rocket-science for me.

    Thanks in advance.

  2. #2
    New to the CF scene
    Join Date
    Jan 2014
    Thanked 0 Times in 0 Posts
    Well, it isn't a loop. But here are some things to help you understand what's happening. Since s is static, its value is shared by all instances of the Q12aFrom2011 class. Those instances are t1 and t2. When you make a new instance, the constructor (the method specified in the class definition) sets i to 0 and increments the (shared) value of s by one. Whenever you call the constructor (it gets called when you do new Q12From2011(); ), the "test: " thing gets printed, and there are two other instances of printing stuff, in the main function. Also, if you do something like this:
    "bananas"+1+2, you get the string "bananas12"
    That should help. If not, you probably need to reread your introductory material.


Posting Permissions

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