• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why compile error??????/

 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At ////////////////1 i am getting compile error saying illegal start of variable.

Static method can have static variable .......then why it is error???

ublic class testin
{
static public int aMethod()
{
static int i=0;//////////////////////1
i++;
return i;
}
public static void main (String args[])
{
testin test = new testin();
test.aMethod();
int j = test.aMethod();
System.out.println(j);
}
}
 
Henry Wong
author
Marshal
Pie
Posts: 21497
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static method can have static variable .......then why it is error???


Local variables are not allowed to be static in Java. These variables are private to the method, it really doesn't make sense for these variables to be static.

Henry
 
Jorge Restrepo
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since this is a class method you shoult use the class name rather than an instance:

testin.aMethod();
 
Jay Pawar
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karthik,
You had posted similar kinda question here check this. and you had realized that local variables cannot be declared static.
 
santosh kothapalli
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class TimDig
{static int i=0;
static public int aMethod()
{
i++;
return i;
}
public static void main (String args[])
{
TimDig test = new TimDig();
test.aMethod();
int j = test.aMethod();
System.out.println(j);
}
}

if you replace ur line one to class variable it compiles fine.
instance variable cannot be static.
 
Niranjan Deshpande
Ranch Hand
Posts: 1277
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
method local variables can be declared as 'final' or
'static final'

BURN THIS IN UR MIND. there r no exception to this statement

niranjan
 
Sasikanth Malladi
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The ONLY modifier allowed in front of a local variable is final.
Niranjan, note the above. You cannot have "static final" for a local variable.
Sashi
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic