Hello,

I am getting "non-static variable friends cannot be referenced from a static context" error msg when I complie this program. If I create TreeSet inside the Names method body there is no errors when compiling and it works but that is not how I want it work. Could someone be kind enough to help me out here. Creating TreeSet must remain as private instance variable. Thanks in advance and here is my code. I hope I have formatted the thread correctly this time round.

public class Test
{
  private Set<String> friends = new TreeSet<String>(); //if I bring this in the body of Names method the code will work

  public static void Names()
   {
      
     String[] name1 = { "Amy", "Jose", "Jeremy", "Alice", "Patrick" };
   
   
     for (int i = 0; i < name1.length; i++)
     {
       friends.add(name1[i]); // it's here where there error is occuring
     }
	 System.out.println(friends);
   }
}

The friends variable only exists when there is an instance of the Test class created using new. The Names() method exists outside of any instance of the Test class.
Either create an instance of the Test class and use object.variable syntax to access the variable
Or remove static from Names() definition
Or make friends static.

how I want it work.

Can you explain how you want it to work?

commented: thanks +1

thanks NormR1 - solved

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.