Java Programming - Declarations and Access Control - Discussion

5. 

What will be the output of the program?

public class Test 
{
    public int aMethod()
    {
        static int i = 0;
        i++;
        return i;
    }
    public static void main(String args[])
    {
        Test test = new Test();
        test.aMethod();
        int j = test.aMethod();
        System.out.println(j);
    }
}

[A]. 0
[B]. 1
[C]. 2
[D]. Compilation fails.

Answer: Option D

Explanation:

Compilation failed because static was an illegal start of expression - method variables do not have a modifier (they are always considered local).


Dinu said: (Jul 19, 2010)  
This not the correct explanation yaar

Kapil said: (Dec 30, 2010)  
Static variables can only be declared as Global Variables (not local).

Manish said: (Jul 3, 2011)  
We can only have final variable as local.

Raju said: (Aug 5, 2011)  
The integer value returned is not obtained in any variable.

Is it not an error?

Snk said: (Feb 20, 2012)  
We can only have final variable as local.

Manish said: (Jul 26, 2012)  
We can not create object of static method.

Sonam said: (Sep 5, 2012)  
Local variables can be final only.
No other modifier is allowed.Also it is not necessary that if a method is returning something we have to hold it.It is fine without that also.

Bhargavi said: (Feb 11, 2013)  
Static variables cannot be instantiated and it could be accessed only by class-name.

Prabhakar said: (Jul 1, 2013)  
We can't declare the static variable inside the non static method.

Because of (static variable are referring method area and instance variable referred heap area). And local variable must be final.

Vinodkumar said: (Dec 12, 2014)  
When we use static it binds with class but there we are using static inside of non-static method so it won't bind with class because we got compilation error.

Archana said: (Jan 21, 2015)  
We cannot access non-static methods in static method.

Anurag Tiwari(Djanurag) said: (Feb 8, 2015)  
We can not declare static variable in to the methods, run this program by method must be declare static.

public static int aMethod()
{
static int i = 0;
i++;
return i;
}

**Important Notes: Memory of static variable is declare in Compile Time not Run time, Memory of entire Method variables are declare in run time because it's local variable not Static variable.

Vimmi said: (Aug 10, 2015)  
There are so many answers here but the correct is Static variables cannot be local variable in java.

Beauti Bharti said: (Jul 19, 2016)  
Hi, can anybody please tell what does mean of a static variable, which cannot be a local variable.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.