0

So I am new to java and was trying to learn about simple data structure and wrote a program in bluej to pop in a stack. However after compiling and executing the program the output is different each time.

The code is as follows:

class popstack
{
    static int arr[]={31,45,64,100};

   public static void main()
    {
     int top=0;
     int i=top;
     System.out.println(arr[top]);
     while(i<3){
         arr[i]=arr[i+1];
         arr[i+1]=0;
         i=i+1;
         
     }
     
      for(int j=0;j<4;j++)
        {
            System.out.print(arr[j]+",");
        }
    }
}

Expected Output: 1st execution :

31
45,64,100,0,

2nd execution :

31
45,64,100,0,

Output: 1st execution :

31
45,64,100,0,

2nd execution :

45
64,100,0,0,

Shouldn't the outputs be same since i am always initializing the array?

EDIT: The issue was fixed when i added the paramter string[] args to the main method.

1
  • 1
    This works fine running it in Eclipse. Possibly something to do with the way you are running it in BlueJ. Commented Mar 17 at 14:23

1 Answer 1

1

For some reason your IDE is not starting a new execution the second time but calling the main() method again while still in the previously executing JVM. Since each execution modifies the values of the array arr you are seeing the second time the values modified from the first execution.

If the JVM finished a new execution would create a fresh JVM process and the values in memory would be carried over from the old one. That is the expected result when executing from the command line for example.

Sign up to request clarification or add additional context in comments.

2 Comments

"For some reason" I suppose it has something to do with the main method being defined without parameters.
Oh ok. I added the string [ ] args parameter and now it works. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.