• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

I cant believe my eyes?

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class TestClass
{
int val=5;
public static void main(String args[])
{
if( val > 4 )
{ System.out.println( "Test A" );
}
else if( val > 9 )
{ System.out.println( "Test B" );
}
else System.out.println( "Test C" );
}
}
I had thought the code would compile clearly ,but the compiler complain that :Can't make a static reference to nonstatic variable val in class TestClass.would you please give me a reason for the result.

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hii..
Static methods can't access instance variables(non static member variables).In the above code "val" is not static..and trying to access "val" from main method which is a static method will give a compiler error.
chin
 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
relax and view the questions carefully u will see the reasons urself
 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi
u can access val thro a object of TestClass only inside a static method like
TestClass obj = new TestClass()
obj.val
hope this clarifies
 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public static void main (String args[]) method is static method and execute and execute first when class is loaded ..... in that situation class doesn't get value of variable val ......
for solution of this problem either u can make val variable is a static our create a object of class in to main method then
Object Name.variable name

 
Yeast devil! Back to the oven that baked you! And take this tiny ad too:
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic