Results 1 to 2 of 2
  1. #1
    vknehra10 is offline Member
    Join Date
    Dec 2016
    Posts
    37
    Rep Power
    0

    Default Why my answer is wrong

    Java Code:
    public class MyStatic {
     
       static int x = 6;
     
       MyStatic() {
          x ++ ;
       }
       void method(){
          System.out.print("-x" + x);
       }
       public static void main(String[] args){
          MyStatic mc1,mc2,mc3,mc4;
          MyStatic mc5 = new MyStatic();
          MyStatic mc6 = new MyStatic();
          MyStatic mc7 = new MyStatic();
          mc7.method();
       }
    }
    Answer Provided: e. This program writes -x7 to the standard output.
    Correct Answer: d. This program writes -x9 to the standard output.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    5,847
    Rep Power
    10

    Default Re: Why my answer is wrong

    x is a static variable (aka class variable, not part of any instance). It is initialized to 6.
    At line 13 the new instance of MyStatic increments the value in the constructor - now x = 7;;
    At line 14 - same thing - now x = 8;
    At line 15 - same thing - now x = 9;
    At line 16 using mc7 instance to invoke method, the value is displayed as -x9

    Note: at line 16, mc5, mc6 could also have been used.

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

Similar Threads

  1. Answer me !
    By johnmecanse34 in forum New To Java
    Replies: 2
    Last Post: 11-20-2013, 01:49 PM
  2. What is the Right Answer :
    By sachin218 in forum New To Java
    Replies: 2
    Last Post: 11-04-2012, 03:41 AM
  3. Replies: 17
    Last Post: 09-15-2012, 03:50 AM
  4. Replies: 1
    Last Post: 08-30-2012, 12:07 AM
  5. Compare true Answer /Player answer
    By Eilime in forum New To Java
    Replies: 1
    Last Post: 04-24-2011, 08:51 PM

Tags for this Thread

Posting Permissions

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