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 13 of 13

Thread: related to static! need help

  1. #1
    Junior Member
    Join Date
    Jul 2011
    Posts
    28
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default related to static! need help

    Hello,
    Below is my code for Stack implementation.

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package doubt1;
     
    /**
     *
     * @author Rohan <Rohan at Home Workstation>
     */
    import java.io.*;
     
    class Stack3 {
     
        int stack[];
        int tos;
     
        void push(int ele1) {
            stack[++tos] = ele1;
        }
     
        int pop() {
     
            int ele2 = stack[tos];
            tos--;
            return ele2;
        }
     
        void contents() {
            if (tos == -1) {
                System.out.println("Stack empty");
            } else {
                System.out.println("Contents of stack are");
                for (int i = tos; i >= 0; i--) {
     
                    System.out.println(stack[i]);
                }
            }
        }
     
        Stack3() {
            stack = new int[10];
            tos = -1;
        }
    }
     
    public class Doubt1 {
     
        public static void main(String args[]) throws java.io.IOException {
            Stack3 stackcopy = new Stack3();
     
     
     
            String choice = null;
            int getchoice;
            char menucontinue = 't';
            do {
                System.out.println("---Stack Menu---");
                System.out.println("");
                System.out.println("1:Push");
                System.out.println("2:Pop");
                System.out.println("3:Contents of Stack");
                System.out.println("4:Exit");
                System.out.println("");
                BufferedReader is = new BufferedReader(
                        new InputStreamReader(System.in));
                System.out.println("Enter your choice");
                choice = is.readLine();
                getchoice = Integer.parseInt(choice);
     
                switch (getchoice) {
                    case 1:
                        if (stackcopy.tos == 9) {
                            System.out.println("Stack full");
                        } else {
                            String pushele = null;
                            int ele;
                            BufferedReader is1 = new BufferedReader(
                                    new InputStreamReader(System.in));
                            System.out.println("Enter element to be inserted");
                            pushele = is1.readLine();
                            ele = Integer.parseInt(pushele);
                            stackcopy.push(ele);                   }
                        break;
                    case 2:
                        if (stackcopy.tos == -1) {
                            System.out.println("Stack Empty");
                        } else {
                            int popele;
                            popele = stackcopy.pop();
                            System.out.println("Element poped is " + popele);
                        }
                        break;
     
                    case 3:
                        stackcopy.contents();
                        break;
     
                    case 4:
                        menucontinue = 'f';
                        break;
     
                    default:
                        System.out.println("Enter valid choice");
                        break;
                }
     
     
            } while (menucontinue == 't');
     
        }
    }
    Its working fine without errors and exception.

    I have created an instance of class Stack3.But how is my static main() method able to access non static variables,and pass it topush(int ele1) method of Stack3 class. By definition and Java Language specification "a static method cannot access
    non-static data


    But again if i try to pass non static variable to a class method in main() in another program
    package doubt2;
    import java.io.*;
    /**
     *
     * @author Rohan <Rohan at Home Workstation>
     */
    class D{
    void call(){}
    void fill(int g){}
    }
    public class Doubt2 {
    int k=9;
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) throws java.io.IOException {
            // TODO code application logic here
            D d = new D();        
            d.call();
            d.fill(k);
     
        }
    }
    Its giving the required error...
    i.e non static variable cannot be referenced from a static context.

    What is the problem or where am i going wrong in understanding the concepts of static? Kindly help me.Getting too confused


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: related to static! need help

    Its giving the required error...
    Please post the full text of the error message. It contains useful information in fixing the problem.
    Like the line number and the text of the source.

  3. #3
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: related to static! need help

    A static method cannot access a non-static members directly. However, if you have an instance of an object you can access non-static members through that object (you can create instances from static or non-static methods).

    So in your second example you would need to create an instance of Doubt2 first, and then access k through that instance object:

    Doubt2 temp = new Doubt2();
    d.fill(temp.k); // still inside of the static method main, but we're accessing k through the instance variable temp
    d.fill(k); // error, we don't have any instance to access k with

    Your Doubt1 class is doing a similar thing, it's creating an instance of the Stack3 class and accessing the non-static members that way.

    An analogy might be to consider a Car class. Before you instantiate a Car object, you can't access its non-static members, for example Car.drive(), or Car.num_wheels (think: there isn't actually a Car yet, how do you drive something you don't have?). However, as soon as you instantiate (create) a Car, say my_car, it makes sense to do something like my_car.drive(), or my_car.num_wheels.
    Last edited by helloworld922; December 15th, 2011 at 01:02 PM.

  4. #4
    Junior Member
    Join Date
    Jul 2011
    Posts
    28
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: related to static! need help

    Quote Originally Posted by helloworld922 View Post
    A static method cannot access a non-static members directly. However, if you have an instance of an object you can access non-static members through that object (you can create instances from static or non-static methods).

    So in your second example you would need to create an instance of Doubt2 first, and then access k through that instance object:

    Doubt2 temp = new Doubt2();
    d.fill(temp.k); // still inside of the static method main, but we're accessing k through the instance variable temp
    d.fill(k); // error, we don't have any instance to access k with

    Your Doubt1 class is doing a similar thing, it's creating an instance of the Stack3 class and accessing the non-static members that way.

    An analogy might be to consider a Car class. Before you instantiate a Car object, you can't access its non-static members, for example Car.drive(), or Car.num_wheels (think: there isn't actually a Car yet, how do you drive something you don't have?). However, as soon as you instantiate (create) a Car, say my_car, it makes sense to do something like my_car.drive(), or my_car.num_wheels.
    Hey....For my first program, to access Stack3 class i have created an object called stackcopy and accessing an nonstatic method push(int ele) from main() of Doubt1 class.And in my second program Doubt2 (please go through the code) I have already created an object called d to access non static method call() and fill(int g). I can assure you one thing,There is no difference between creating object and calling an non static method from static method main() in either of the two programs.The problem is passing an nonstatic variable to a non static method
    from static method main(). First program is allowing it and second one according to JLS is giving error.Either first
    one is wrong or the second one according to JLS. SO having a great dilemma.
    Need help on that please
    Last edited by rohan22; December 15th, 2011 at 11:09 PM.

  5. #5
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: related to static! need help

    The problem is passing an nonstatic variable to a non static method
    from static method main().
    Static blocks or methods are executed before everything else in your program and non static variables take memory when they are called, so does the static. Well, let's have an example;
    Let's say we have a method X which is static and one more method Y that is non static.
    There are four variables, a,b,c,d of some primitive data type.
    According to the rules, X will take memory very first while a,b,c,d didn't even called yet so when you will try to access a,b,c,d (any of them) how do you think that it will let you access them. As they have no space in the memory yet.


    Moreover, as said by Norm, post your error message so that we could have a look into that and could help you more appropriately.

  6. #6
    Junior Member
    Join Date
    Jul 2011
    Posts
    28
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: related to static! need help

    I think i am very close to solving it.Just tell me one thing.Now(below i have written a short code about
    the scenario) suppose if i have a static method X(). And in that if i declare a variable called int i.Now
    is int i implicitly static even though i have not declared it as static int i.If "Yes" then it solves
    my problem.
    Here is a code snippet.

    static void X(){
    int i;                // is int i implicitly static if declared in a static method?
    }

    Or in the above code if int i is not static implicitly......... is it that static methods can actually have nonstatic
    variables along with static variables?
    Last edited by rohan22; December 16th, 2011 at 01:32 AM.

  7. #7
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: related to static! need help

    Quote Originally Posted by rohan22 View Post
    I think i am very close to solving it.Just tell me one thing.Now(below i have written a short code about
    the scenario) suppose if i have a static method X(). And in that if i declare a variable called int i.Now
    is int i implicitly static even though i have not declared it as static int i.If "Yes" then it solves
    my problem.
    Here is a code snippet.

    static void X(){
    int i;                // is int i implicitly static if declared in a static method?
    }

    Or in the above code if int i is not static implicitly......... is it that static methods can actually have nonstatic
    variables along with static variables?
    NO!!!!
    And did you try it?

  8. #8
    Junior Member
    Join Date
    Jul 2011
    Posts
    28
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: related to static! need help

    Quote Originally Posted by Mr.777 View Post
    NO!!!!
    And did you try it?
    Yes I have tried and its working Fine.Try the below code:


    class D {
    int k;
     
     void fill(int g) {
            k = g;
            System.out.println("k is " + k);
        }
    }
     
    public class Temp {
     
        public static void main(String[] args) {
            int m = 9;
            D d = new D();
     
     
            System.out.println("m is " +m);
            d.fill(m);
        }
    }
    Last edited by rohan22; December 16th, 2011 at 01:45 AM.

  9. #9
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: related to static! need help

    Quote Originally Posted by rohan22 View Post
    Yes I have tried and its working Fine.Try the below code:


    class D {
    int k;
     
     void fill(int g) {
            k = g;
            System.out.println("k is " + k);
        }
    }
     
    public class Temp {
     
        public static void main(String[] args) {
            int m = 9;
            D d = new D();
     
     
            System.out.println("m is " +m);
            d.fill(m);
        }
    }
    Do you think m is static? NO!!!
    m is being passed as argument to fill() of Class D and class D doesn't even know m. Your concept about static is wrong. This method you have tried is called value passing to the methods. Nothing else. m is not static.
    suppose if i have a static method X(). And in that if i declare a variable called int i.Now
    is int i implicitly static even though i have not declared it as static int i
    This was your question, so i replied NO and i can never be implicitly static.

  10. #10
    Junior Member
    Join Date
    Jul 2011
    Posts
    28
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: related to static! need help

    Quote Originally Posted by Mr.777 View Post
    Do you think m is static? NO!!!
    m is being passed as argument to fill() of Class D and class D doesn't even know m. Your concept about static is wrong. This method you have tried is called value passing to the methods. Nothing else. m is not static.

    This was your question, so i replied NO and i can never be implicitly static.
    Yes i got to know that m is int and not static int in netbeans debugger when i review the contents of m.

    Or in the above code if int i is not static implicitly......... is it that static methods can actually have nonstatic
    variables along with static variables?
    But my question was can static methods have non static variables also.And yes i can conclude that it can have.
    Am i right?

  11. #11
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: related to static! need help

    Yes. They can have non static variables.

  12. #12
    Junior Member
    Join Date
    Jul 2011
    Posts
    28
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: related to static! need help

    Quote Originally Posted by Mr.777 View Post
    Yes. They can have non static variables.
    Cool............ thanks.....

  13. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: related to static! need help

    Is there confusion here between local variables which all methods can have (m is local)
    and static class variables?
    Method can not define local static variables.

Similar Threads

  1. Replies: 9
    Last Post: November 5th, 2011, 10:22 AM
  2. Troubles with toString and static and non-static
    By BadgerWatch in forum What's Wrong With My Code?
    Replies: 7
    Last Post: October 3rd, 2011, 05:04 AM
  3. [SOLVED] non static variable this cant be referenced from a static context
    By chronoz13 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: June 20th, 2011, 06:13 PM
  4. non-static method cannot be referenced from a static context
    By Kaltonse in forum What's Wrong With My Code?
    Replies: 2
    Last Post: December 21st, 2010, 07:51 PM
  5. Replies: 10
    Last Post: September 6th, 2010, 04:48 PM