-2

I'm new to java programming and Stackoverflow and I had a question. I'm trying to display text assigned to variables and when I try to run the program is says that non-static variables can't be referenced from static content. Here's my code:

public class VariableTesting {

    String firstName = "Tom"; //String first, last, 
    char middleInitial = 'B';
    String lastName = firstName;

    public static void main(String[] args) {
        variable();
    }   

    public static void variable(){
        System.out.println(lastName + "," + firstName + "," + middleInitial);
    } 
}

I appreciate any and all help. Thanks

takendarkk
  • 3,347
  • 8
  • 25
  • 37
  • Search for error messages: http://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static?lq=1 – user2864740 Sep 08 '14 at 23:00
  • 3
    That's because non-static variables can't be referenced from a static context. – Hot Licks Sep 08 '14 at 23:00
  • An "instance" variable is associated with an "instance" of the class. Ie, if you do `VariableTesting me = new VariableTesting();`, then `me` is a reference to an instance of the class. Then you can do, eg, `System.out.println(me.lastName);`. – Hot Licks Sep 08 '14 at 23:03

2 Answers2

2

firstName, middleInitial and lastName are instance variables. Therefore you can't access them from a static method, unless it is done via a reference to an instance of the VariableTesting class.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

Since you can't have two object that are differently oriented together (static and non static) you have to either make the variable static or make the method non-static.

PsyCode
  • 644
  • 5
  • 14