0

I am trying to learn java. currently learning about types of variables. i have written a small program defining instance,local,static variables and trying to print the same from with in the main method. but i am getting error saying "non static variable i cannot be referenced from static context. Below is my program

public class variable{
  int i=5;
  static int j=10;
  public static void main(String[] args){
    int k=15;
    System.out.println(i);
    System.out.println(j);
    System.out.println(k);
  }
}

Please let me know whats wrong with the program

f1sh
  • 11,489
  • 3
  • 25
  • 51
shaiksha
  • 993
  • 5
  • 17
  • 35
  • Please format your code with correct indentation. Not for this question, but in your IDE. Having good formatting helps you to see problems far easier. – f1sh Jul 21 '16 at 09:11
  • as i am a beginner i am using notepad to write the code instead of any tool. – shaiksha Jul 21 '16 at 09:12
  • You can not call non-static variables in static methods as "i" is a non-static variable & used in static main method – Arjit Jul 21 '16 at 09:14
  • @user1861033 - You've asked 29 questions before this. You should know that your code should be properly formatted (by now) :) – TheLostMind Jul 21 '16 at 09:14
  • @user1861033 i strongly recommend you to use an IDE such as eclipse. It might seem complex at first, but it gives you a lot of help while developing. – f1sh Jul 21 '16 at 09:14

3 Answers3

4

You need to create a instance of variable and access i

variable v = new variable();

// then access v.i

BTW use Camelcase for you class name.

Beniton Fernando
  • 1,533
  • 1
  • 14
  • 21
0

Options:

Make a new instance of your class so you can reach i. In fact it is maybe not the best option, because you should make it private, and add a getter method... :)

OR

You could change int i to static int i, because of the static main method.

+1 : it is better to have classnames camescased... :)

Leah
  • 458
  • 3
  • 15
0

int i should be static becasue static context cant refer to the non-static variable

Hetali
  • 1
  • 2