Reputation: 3167
Is there anyone here who disagrees that:
JLabel lbl;
lbl = new JLabel ("a label");
is equivalent to:
JLabel lbl = new JLabel ("a label");
I guess not?
Mind you - this is related to the following question:
public class Test
extends JApplet
{
JLabel lbl;
lbl = new JLabel ("a label");
public void init()
{
}
}
This code (A) gives the following error:
Syntax error on token ";", , expected
However, this code (B) works perfectly:
public class Test
extends JApplet
{
JLabel lbl = new JLabel ("a label");
public void init()
{
}
}
Any idea why this happens? This may have to do with the init method. I'm still looking forward to see mathematical-precise explanations rather than interpretable theories. Thanks a lot. I'm new with applets. PS: I left out the package import (e.g. import javax.swing.*; ) for simplicity.
Upvotes: 1
Views: 235
Reputation: 7854
It has nothing to do with applet or init() method. You can have instructions only inside method body or blocks (lbl = new JLabel ("a label");
without declaration is an instruction)
Upvotes: 2
Reputation: 35829
It should be the same, IF it is used in a method:
public void setMethod() {
JLabel lbl;
lbl = new JLabel ("a label");
}
Upvotes: 2
Reputation: 691685
You can't have free instructions like these in the class body. The class body can contain methods, field declarations, constructors, inner classes declarations, static and instance initializer blocks, but not free instructions like this.
You could do
JLabel lbl;
{
lbl = new JLabel ("a label");
}
but it's ugly.
Upvotes: 2