Can someone tell what is happening in the code

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jinnejeevansai
    New Member
    • Nov 2014
    • 48

    Can someone tell what is happening in the code

    Can someone tell why is variable a not getting printed.
    Code:
    import java.lang.*;
    import java.io.*;
    class t
    {
            int a=5;
            void fun()
            {
                    System.out.println(a);
            }
            public static void main(String args[])
            {
            }
            t()
            {
                    t var = new t();
                    var.fun();
            }
    }
  • q88qaz
    New Member
    • Sep 2015
    • 1

    #2
    Nothing ouput.
    The main methoed is null,did nothing.

    Comment

    • jinnejeevansai
      New Member
      • Nov 2014
      • 48

      #3
      But i was printing a in fun

      Comment

      • chaarmann
        Recognized Expert Contributor
        • Nov 2007
        • 785

        #4
        You "were printing a in fun" only if you would have called it in main. But you never called it. That's why it did not print.

        See, you opened method main in line 11 and directly closed it in line 12. Nothing in between. But if you want to print, then you have to insert "new t()" there.

        In line 13 the constuctor starts. It is executed if you call "new t()". Inside the constructor, in line 15, you call the constructor again! Endless-recursion will let it crash! So just delete line 15 and only call "fun()" in line 16 to make it work. Or just move line 15 and 16 unchanged between 11 and 12.

        Comment

        Working...