I am a new learner of Java. I learned some of the Java core concepts. I got the identifier expected error when run my following code:
class Sekar {
public static int i,j,k;
i = 900;
static void max()
{
j = 100;
if(i>j)
{
k=i;
}
else {
k=j;
}
System.out.println("The maxmimum vale between"+i+"and"+j+"is :"+k);
}
public static void main(String[] args) {
max();
}
}
When I compile my code, I get the following error:
error: identifier expected
i = 900;
^
Can any one explain why this error happens here?
When I google about identifier expected error, I found that this error happens when variables are declared without datatype, but I declared that for all my variables i,j,k.
When I redeclare the data type again while setting value to "i" like int i = 900 it works. Why does it?
解决方案
i = 900;
This is a statement in Java, it can be inside Constructor or method, or initialization block.
In your case, you may move that inside the max() method
When I re declare the data type again while setting value to "i" like
int i = 900 it works. Why does it?
Here, you are declaring and assigning the value to the variable in the same time, same line.
Check here for more details and here about java statements, expressions
Statements
Statements are roughly equivalent to sentences in natural languages. A
statement forms a complete unit of execution. The following types of
expressions can be made into a statement by terminating the expression
with a semicolon (;).
Assignment expressions
Any use of ++ or --
Method invocations
Object creation expressions