Reputation: 23
I have two versions of codes.
Launcher.java
class Launcher {
public static void main(String[] args) {
LuckyNumber game;
game = new LuckyNumber();
game.start();
}
}
Player.java
class Player {
int randomNumber = 0;
public void roll(){
randomNumber = (int) (Math.random() * 10);
}
}
LuckyNumber.java
class Launcher {
public static void main(String[] args) {
LuckyNumber game;
game = new LuckyNumber();
game.start();
}
}
Launcher.java
class Launcher {
public static void main(String[] args) {
LuckyNumber game;
game = new LuckyNumber();
game.start();
}
}
Player.java
class Player {
int randomNumber;
randomNumber = 0;
public void roll(){
randomNumber = (int) (Math.random() * 10);
}
}
LuckyNumber.java
class Launcher {
public static void main(String[] args) {
LuckyNumber game;
game = new LuckyNumber();
game.start();
}
}
The first version of the code compiles without problems, but the second version of the code can not compile, and compiler shows the following errors:
.\Player.java:4: error: <identifier> expected
randomNumber = 0;
^
.\Player.java:4: error: cannot find symbol
randomNumber = 0;
^
symbol: class randomNumber
location: class Player
2 errors
So question is why:
int variable;
variable = 0;
isn't the same as:
int variable = 0;
And what's the difference?
Upvotes: 0
Views: 1010
Reputation: 4054
A class in Java can have members.
class Player {
int variable = 0; // this defines a member variable within the class Player
}
But you can not put code/expressions in a class declarations body. This can only be in methods or the constructor or during the initializing of variables.
int variable;
variable = 0; // this is an expression and should be within the constructor, a method or the initialiser of the variable.
Upvotes: 0
Reputation: 164164
This is a declaration:
int variable;
and this is a declaration with initialization:
int variable = 0;
They're both valid at the class level and inside a method.
However for an already declared variable, this:
variable = 0;
is considered to be executable code and it is valid only inside a method and not at the class level.
In an IDE like IneliJ, if you write:
int variable;
variable = 0;
the ide will prompt you to merge the 2 lines to this:
int variable = 0;
because it is the same.
Upvotes: 0
Reputation: 1338
It's the same untill you write your code outside of method. You can't do like this:
class Player {
int randomNumber;
randomNumber = 0;
It will cause Java syntaxis error. You should read about Java properties.
Upvotes: 0
Reputation: 15714
The two are the same, but only when they are in a method.
In your case, initializating variables without declaring them is invalid outside of a method.
Upvotes: 3