Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: Why the" int i" is getting the value 0

  1. #1
    Junior Member
    Join Date
    Sep 2014
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Red face Why the" int i" is getting the value 0

    Hi All,
    I wrote the following code:

     
    public class Question_9 {
    int i;
     
    Question_9(int i){
    i=i;
    System.out.println(i);
     
    }
     
    public static void main(String[] args) {
     
    Question_9 Q9= new Question_9(7);
    System.out.println(Q9.i);
     
    }
     
    }

    It gives the output as 0 not 7, can someone explain me why?
    Last edited by Shiraz; September 28th, 2014 at 05:34 AM.


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 697 Times in 679 Posts

    Default Re: Why the" int i" is getting the value 0

    Welcome to the forum! Please read this topic to learn how to post code in code or highlight tags and other useful info for new members.

    Please post your code correctly using code or highlight tags per the above link.

  3. #3
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Why the" int i" is getting the value 0

    The value 0 is the default value for integer variables in java. Since you never set the value of your private member variable i it stays at its default value.
    What you do in the constructor is set the value of your parameteter i to the value of the parameter i, a no-op.

Similar Threads

  1. Replies: 4
    Last Post: July 18th, 2014, 02:04 AM
  2. Replies: 1
    Last Post: July 16th, 2014, 04:16 AM
  3. Replies: 2
    Last Post: May 22nd, 2014, 01:17 PM
  4. Replies: 2
    Last Post: June 22nd, 2013, 10:30 AM
  5. "possible loss of precision, found double, required int" HELP
    By kkatchh in forum Loops & Control Statements
    Replies: 3
    Last Post: November 6th, 2011, 10:50 AM