compiler error

Hello, I just have this question. say if i have a java program like this. class a{ int x; public static void main(String ar[]) { int y; System.out.print(x); System.out.print(y); } } This gives only one error saying it is not possible to refer non-static variable inside a static method. But if you change the print lines like this. class a{ int x; public static void main(String ar[]) { int y; System.out.print(y); System.out.print(x); } } It gives 2 errors saying non static refernece and variable y not initialized. Could you please explain the difference. Thank you

Let's start by understanding the difference between variable x and variable y: Variable x: As you can see, x belongs to a class. They are called instance variables. Instance variables are initialized with their default value. So, in this case, the value of x will be 0 (because it's an int). If you'd declared a boolean instance variable, then their default value would be false. So, instance variables are always initialized with their default value, if you do not specify any. Variable y: y belongs to the main() method. variables that belong to method are called local variables (they have many names, but IMO local variables is the most commonly used one). Local variables are not initialized by default. So, if you try to use them without being initialized by you, the compiler will complain. Notice that the compiler will not raise any error if you don't use a local variable that has not been initialized by you. It'll only complain if it is reachable in you code. In the second example, you're using variable y to print its value, but if you ommit that line, you won't get that error (because you're declaring variable y but you're not using it in your method) hope this helps [ October 05, 2003: Message edited by: Andres Gonzalez ]

I'm not going to be a Rock Star. I'm going to be a LEGEND! --Freddie Mercury

Ransika deSilva
Ranch Hand

Joined: Feb 18, 2003
Posts: 524

posted Oct 05, 2003 03:24:00

0

I am cleared with the concept. What I want to know is why do they give only on error when you compile the first program and two errors when you compile the second code. why the difference?.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus