Forum

Number Of Page View:100,000+/Months
LOGIN |New User

Reply

What is output of following code


package r4r.co.in.core.java;

public class HelloWorld {
	 int i = 0;

	public static void main(String args[]) {
	
		System.out.println(i);
		new HelloWorld();
		
		
	}

	static {
	int i;
		i = 10;
		System.out.println(i);
	}
}

The above program give an error in compilation, like a non-static field can be referenced from a static context. The problem lies in the variable i in print statement inside the main()  method. The variable i can only be accessed through the object reference.

REPLY :
Here int i=0; is an instance variable and public static void main(String args[]) is static method .Static methods can access only static variable or static method directly .But we can assess none- static variables by creating object of class.

REPLY :
Example 

 public class TestR4R{
	 int i=0;
	 public static void main(String a[]){
		 new TestR4R().i=10;
	 }
}