Hello and welcome to our community! Is this your first visit?
Register
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
    Sep 2008
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    I have a basic doubt - Java

    Hi,

    I executed this program without Object and with Object.
    With object my answer is 200,202, but I'm not using object ref. I guess,
    It should be 18,19. What is the reason ?

    // This is my program

    package com.test;

    public class TestOne {

    private static int a=10;
    private static int b;

    static{
    if(a ==10){
    a=18;
    b=19;
    }else{
    b=222;
    }
    }

    public TestOne(){
    a =200;
    b =202 ;
    }

    public static void main(String[] args) {
    TestOne t = new TestOne();
    System.out.println(TestOne.a); // Calling without object REF.
    System.out.println(TestOne.b);
    }
    }

  • #2
    Senior Coder shyam's Avatar
    Join Date
    Jul 2005
    Posts
    1,563
    Thanks
    2
    Thanked 163 Times in 160 Posts
    because you are calling the constructor which is re-initializing the values

    Code:
    public static void main(String[] args) {
    System.out.println(TestOne.a); // Calling without object REF.
    System.out.println(TestOne.b);
    }
    should give you the expected result
    You never have to change anything you got up in the middle of the night to write. -- Saul Bellow


  •  

    Posting Permissions

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