-3
public static int f(String input) {

     public static Stack<Character> stack = new Stack<Character>();

        int n = 0;

        for (int i = 0; i < input.length(); i++) {

                if (input.charAt(i) == 'd')
                        stack.push('d');

                else if (input.charAt(i) == 'b') {

                        if (!stack.empty() && stack.pop() == 'd') n++;
                }
        }  

        return n;
}

i just want to know the significance of static keyword in object creation...just pasted the whole code here

azurefrog
  • 10,785
  • 7
  • 42
  • 56
abhinav
  • 3
  • 2
  • 4
    A syntax error? You can't declare a local variable static like that, it won't compile. – azurefrog Apr 22 '16 at 21:21
  • 1
    Are you sure you didn't reverse those first two lines somehow? – azurefrog Apr 22 '16 at 21:22
  • 2
    The `static` keyword means nothing to the *object creation* of `Stack`, even if you got that code compiling by flipping the first two lines. It means something to the scope of field `stack`, but has no impact whatsoever to the `new Stack()` call. – Andreas Apr 22 '16 at 21:25
  • thanks for the answers guys..and yeah first two lines needs to be flipped – abhinav Apr 23 '16 at 20:26

2 Answers2

0

As @azurefrog says, that won't work - I'm guessing you've copied and pasted the line

public static Stack<Character> stack = new Stack<Character>();

from the top of your class for illustrative purposes? If so, you've broken your example in doing so.

Assuming I'm correct and that declaration is from within your class, rather than within that static method, then the answer to your question would be that there will be only a single instance of the stack variable, regardless of the number of instances which you create of the class in which it resides: i.e. all instances which you create of your class will see/contain the same instance of stack, and anywhere it is addressed from outside (valid, given that it's public), should be referring to it as ClassName.stack, not instanceName.stack

ImperfectClone
  • 113
  • 1
  • 2
  • 8
0

What everyone else has said so far is all accurate, but I'll elaborate a bit on your question on what "the significance of static keyword in object creation" is.

Static variables last for the lifetime of the class (so essentially from the start till the end of your program). But in your code, you declare your stack variable inside of a method, so that variable is created and destroyed each time that method is run. Therefore it doesn't actually make any sense to be given the keyword static. These variables are meant to be shared among every instance of the class you create. So you should only create that static variable once when your program is run.

(There are ton of resources elsewhere explaining when/where to use static)

Here are a couple I found useful when learning:

Community
  • 1
  • 1
chickenwingpiccolo
  • 193
  • 1
  • 3
  • 13