public class Hello { System.out.println("x"); //Problem in this line Hello() { System.out.println("4456"); } public void mix() { System.out.println("7899"); } public static void main(String[ ] args) { Hello h = new Hello(); //h.mix();
} } -------------------------------- o/p:
Hello.java:4: <identifier> expected System.out.println("x"); ^ Hello.java:4: illegal start of type System.out.println("x"); ^ 2 errors ------------------------------------------ Why it is not printing "x" in the console?
You can't put any executable statements in a class body outside of any method or block. The only things you can have there are member variable declarations like
i want to give the SCJP certification pls tell me some easy tips so that i can do it efficiently........ i want to build my basics Pls gv some guideLines....
Om Joshi
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 35446
9
posted
0
om joshi, welcome to JavaRanch.
Please do not post unrelated questions to existing topics. That's called "hijacking", and is generally frowned upon. Start a new topic instead.
I am bit afraid of the sentence by Tim. Could you please explain the meaning of floating loose.. Thanks in advance. Sumit
Here is your code, annotated a little:
I have marked where each method starts and ends. The line in italics is NOT IN ANY METHOD. you cannot have an executable statement that is not contained inside a method - basically only variable delarations/initializations. if i asked you "When exactly would that line run?", what would you tell me? that line is not in any constructor, so it won't run when the object is created. there is no method call that would run it, so it won't no matter what method you call... the compiler thinks you put it in there by accident, or on the wrong line by mistake. it's kind of 'out there' where it doesn't belong.
Never ascribe to malice that which can be adequately explained by stupidity.
amit gupta
Greenhorn
Joined: Dec 29, 2006
Posts: 23
posted
0
Hi Fred,
The explaination is really good and I have understood the whole thing with logic behind the same.