[java] java : non-static variable cannot be referenced from a static context Error

The following code is generating an error on the variable con2 saying "non-static variable con2 cannot be referenced from a static context Error." I Googled for a resolution and they are suggesting the variable isn't initalized yet to make the methods available. Am I initializing this incorrectly? I also tried changing things to public but that didn't help either.

import java.io.*;
import java.net.*;

import java.sql.*;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import net.sourceforge.jtds.jdbcx.JtdsDataSource;
import net.sourceforge.jtds.jdbc.Driver;

class testconnect { 

     private java.sql.Connection con2 = null;

     private final String url2 = "jdbc:jtds:sqlserver://";
     private final String serverName= "SQL01";
     private final String portNumber = "2677";
     private final String databaseName= "App";
     private final String userName = "bob";
     private final String password = "boob";
     private final String selectMethod = "cursor";  

     private String getConnectionUrl2(){
        System.out.println("initalizing jtds");
          //String returnVal = url+serverName+":"+portNumber+";databaseName="+databaseName+";user="+userName+";password="+password+";instance="+instance+";";
          String returnVal = url2+serverName+":"+portNumber+"/"+databaseName+";user="+userName+";password="+password;
          System.out.println("url2: " + returnVal);
          return returnVal;
     }

     public static void main (String[] args) { 
         con2 = java.sql.DriverManager.getConnection(getConnectionUrl2());

     } 

} //end class 

This question is related to java jtds

The answer is


Java has two kind of Variables

a)
Class Level (Static) :
They are one per Class.Say you have Student Class and defined name as static variable.Now no matter how many student object you create all will have same name.

Object Level :
They belong to per Object.If name is non-static ,then all student can have different name.

b)
Class Level :
This variables are initialized on Class load.So even if no student object is created you can still access and use static name variable.

Object Level: They will get initialized when you create a new object ,say by new();

C)
Your Problem : Your class is Just loaded in JVM and you have called its main (static) method : Legally allowed.

Now from that you want to call an Object varibale : Where is the object ??

You have to create a Object and then only you can access Object level varibales.


You probably want to add "static" to the declaration of con2.

In Java, things (both variables and methods) can be properties of the class (which means they're shared by all objects of that type), or they can be properties of the object (a different one in each object of the same class). The keyword "static" is used to indicate that something is a property of the class.

"Static" stuff exists all the time. The other stuff only exists after you've created an object, and even then each individual object has its own copy of the thing. And the flip side of this is key in this case: static stuff can't access non-static stuff, because it doesn't know which object to look in. If you pass it an object reference, it can do stuff like "thingie.con2", but simply saying "con2" is not allowed, because you haven't said which object's con2 is meant.


The simplest change would be something like this:

public static void main (String[] args) throws Exception {
  testconnect obj = new testconnect();
  obj.con2 = DriverManager.getConnection(obj.getConnectionUrl2());
  obj.con2.close();
}

Your main() method is static, but it is referencing two non-static members: con2 and getConnectionUrl2(). You need to do one of three things:

1) Make con2 and getConnectionUrl2() static.

2) Inside main(), create an instance of class testconnect and access con2 and getConnectionUrl2() off of that.

3) Break out a different class to hold con2 and getConnectionUrl2() so that testconnect only has main in it. It will still need to instantiate the different class and call the methods off that.

Option #3 is the best option. #1 is the worst.

But, you cannot access non-static members from within a static method.


This is an interesting question, i just want to give another angle by adding a little more info.You can understand why an exception is thrown if you see how static methods operate. These methods can manipulate either static data, local data or data that is sent to it as a parameter.why? because static method can be accessed by any object, from anywhere. So, there can be security issues posed or there can be leaks of information if it can use instance variables.Hence the compiler has to throw such a case out of consideration.