3

A very simple question for the experts, but for a beginner like me, it is just confusing. I thought I understood Static, but apparently I do not. This below is the entire class, and it says I need to make test static. But I don't want to. What can I do to fix this, and why is it happening in the first place? Thanks!

public class SubstringTest
{
    private String test;

    public static void main(String[] args)
    {
        test = "Penguin";
        System.out.println(test);
        System.out.println(test.substring(3));

    }

}
Evorlor
  • 7,263
  • 17
  • 70
  • 141
  • private static String test; – smk Feb 22 '13 at 02:54
  • main is a static method,. And you can access only static members inside a static method. – smk Feb 22 '13 at 02:55
  • possible duplicate of [Why main method is static in java](http://stackoverflow.com/questions/3181207/why-main-method-is-static-in-java) –  Feb 22 '13 at 02:57
  • http://stackoverflow.com/questions/11522026/public-static-void-main-access-non-static-variable –  Feb 22 '13 at 02:59

3 Answers3

9

main is static. test is not.

If you don't want to make test static, you have to create an instance of SubstringTest first.

SubstringTest st = new SubstringTest(); // create an instance
st.test = "test"; // this works
System.out.println(st.test); // also works

If test is static, you can do

SubstringTest.test = "test";

Or if the code you're writing is in the class SubstringTest and test is static:

test = "test";
tckmn
  • 57,719
  • 27
  • 114
  • 156
5

A static method cannot access non-static/instance variables, because a static method is never associated with any instance. A static method can’t directly invoke a non-static variable. But static method can access non-static variable by means of declaring instances and using them.

public class SubstringTest
{
private String test; // make it private static String test;

public static void main(String[] args)
{   // SubstringTest t = new SubstringTest(); Or change here.
    // t.test ="Penguin";
    test = "Penguin";
    System.out.println(test);
    System.out.println(test.substring(3));

}

}
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
4

You CANNOT access instance variables from a Static method.

Because a static method is called on a class instance and not to an object of a class. This means, that a static method is not able to access instance variables, because they are only instantiated in an object

Jayamohan
  • 12,734
  • 2
  • 27
  • 41