Hi, can we declare non static variables in static methods?if so plz explain by an example?

Questions by ikprasanth   answers by ikprasanth

Showing Answers 1 - 12 of 12 Answers

shiva

  • Oct 9th, 2006
 

      hello please send reasonable answer for this question.

  Was this answer useful?  Yes

Pradipkumar

  • Oct 12th, 2006
 

Yes,

You can declare the non static variables in static methods because its being locally created when the method has been invoked.

good e.g is

public static void main(String args[]){

int i;

}

Rajesh

  • Oct 12th, 2006
 

No...

     Basically , static variables are essentially Class variable.So when you declare any variable inside non-static or static methid,it will become a Local variable (neither static not non-static) to that method.

  Was this answer useful?  Yes

hi mr pradip kumar, according to u if we declare a non static variable inside a static method it is possible.Did u check the output whether the program is executing or not by printing i? plz check that and reply.oru please execute the below program. becoz I am getting main thread exception. Plz dont think otherwise.

class test

{

public static void main(String args[])

{

int i=0;

System.out.println(i);

}

}

  Was this answer useful?  Yes

Abhishek(Sharad)

  • Oct 17th, 2006
 

Hi friends,

                  You can declare any type of variables in Static methods it doesn't matter it is static or not but you can't give any reference of non-static variable in static methos. If you'll do like this then compiler will give message like "non-static variable can not be referenced from a static context". You can try this code:

class Test1

{

int i;

public static void main(String args[])

{

i=10;

System.out.println("Value of i:" + i);

}

}

//            You can send any pros related to java on sharadmrg@yahoo.com

                      Regards,

//                    Abhishek(Sharad)

  Was this answer useful?  Yes

prabhaker

  • Oct 18th, 2006
 

Hi prasanth i couldn't undersatand you why the above code doesn't work?
Just You declared a variable inside the main method,tht should act as local.

So tht code should work and will give the o/p as 0; 

  Was this answer useful?  Yes

Seema

  • Feb 2nd, 2007
 

declaration of i is outside static method, so it is giving error "can not make static reference to non static field" if it is declared inside then it will print 10.

  Was this answer useful?  Yes

yes, we can declare and they would be local to the block.

Here is an example.....
class Test
{
    public static void main(String[] args)
    {
        int i = 0;
        System.out.println("i --->"+i);
    }
}

vinny

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions