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
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.
No, actually, you must declare your con2 field static:
private static java.sql.Connection con2 = null;
Edit: Correction, that won't be enough actually, you will get the same problem because your getConnection2Url method is also not static. A better solution may be to instead do the following change:
public static void main (String[] args) {
new testconnect().run();
}
public void run() {
con2 = java.sql.DriverManager.getConnection(getConnectionUrl2());
}
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.
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.
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();
}
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.
Related
I am coming from a C++ background, so I am used to the main function not being able to access private data members of an instance.
However, the case with Java is different as main is a part of the public class, and can thus access the private data.
Why is it that a static method is given access to private data even though it does not belong to the calling instance? Is there any way I can avoid this from happening?
Here's a little snippet to explain what I mean:
public class Main
{
private int x = 5;
public static void main(String[] args) {
Main ob = new Main();
System.out.println(ob.x);
}
}
I want x to be inaccessible from main and that I have to use an accessor method for the same.
There is no way to protect "a class from itself". Private means that the current class (and only the current class) can access the field.
If you had a private field that no method could access, you could never read or update its value and thus render it unneccessary. By declaring a field private, you prohibit anybody outside your current class to access the field.
Read about visibility here: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
If I am not wrong, how many ever same Strings are created, only in only place it is stored by using String interning. If so, what is the use of making a Sting static if it is already being stored in only one place in memory which is nothing but acting as if it was a static variable. Thanks.
Static Strings can be accessed outside the class without creating the class's variable. Example of this is:
public class Stuff {
public static final String foo = "foo";
}
Here is an example of calling the variable foo (while still retaining it's contents of foo):
public class Application {
public static void main(String[] args) {
System.out.println(Stuff.foo);
}
}
As mentioned, I did not have to initialize Stuff in Application.
If you want to access it staticly outside of a class without initializing the class, then you make it static
You may want a class to access that String value but you do not want to initialize the class which holds the String. This is useful if one class is using the String but not using the rest of the class that holds the String.
I tried to access a variable in the main class from another class. I don't know if it's possible but I need those variables. If there is a way please show me. This is the simple example.
public class A(){
public static String status;
public static void main(String [] args){
Scanner s = new Scanner(System.in);
System.out.println("Deadlock or no deadlock (y/n)");
status = s.nextline();
......
}
Then I want to use this variable "status" in another class which implements a runnable (thread). If status is "y" then a particular block of codes (if/else) inside the run methon will executes.
Anyone point me how do I call the main class so I can access the variable status from my the runner class. Thanks.
The field status in class A is public and static, so you can call it from wherever you like.
public class B {
public void myMethod() {
System.out.println("A's status is " + A.status);
}
}
A point on terminology: A here is a class, which represents an object. main happens to be a method within that class A. So you'd say that status belongs to A, not to main.
No java is pass by value not pass by reference. You could follow the example I'm linking and see if that helps though.link You could make it static and it would be usable that way but any operations on it would change when ever you perform any on it hence static.
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
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.
No, actually, you must declare your con2 field static:
private static java.sql.Connection con2 = null;
Edit: Correction, that won't be enough actually, you will get the same problem because your getConnection2Url method is also not static. A better solution may be to instead do the following change:
public static void main (String[] args) {
new testconnect().run();
}
public void run() {
con2 = java.sql.DriverManager.getConnection(getConnectionUrl2());
}
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.
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.
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();
}
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.
I'm trying to initialize a static class, with an argument, and then run some more static code in that class.
I'm aware of the static block, but it seems it can't take any arguments.
Is there a way to pass arguments to a static constructor?
If not, what is the recommended technique to initialize a Static class using an argument?
Edit:
A static class to my understanding is a class which cannot be instantiated (in c# they're called static classes, if Java has a different term for them, sorry for not being aware of it) - it's accessed through it's class name rather than an object name.
What I'm trying to achieve (very simplified) is a class which receives a dictionary as String, parses it, and has methods manipulate it like GetRandomEntry.
Here's an elaborated snippet of my code:
public class QuestionsRepository {
private static Map<String,String[]> easyDefinitions = new HashMap<String,String[]>();
//...
staticĀ
{
// need to receive and parse dictionary here
}
//...
Taking the relevant parts of a code snippet is never easy, hope i have chosen wisely (:
Another detail that may be relevant - I'm a c# programmer, usually. Just Started learning Java lately.
Thanks.
I think you would need to initialize the static fields of the class according to some input. You can do it in the following way by calling the static method of another class:
class ClassToInitialize {
static {
staticField = ParamPassClass.getParameter();
}
private static String staticField;
ClassToInitialize() {
System.out.println("This is the parameter: " + staticField);
}
}
class ParamPassClass {
private static String parameter;
static String getParameter() {
return parameter;
}
static void setParameter(String parameter) {
ParamPassClass.parameter = parameter;
}
}
class Main {
public static void main(String args[]) {
ParamPassClass.setParameter("Test param");
new ClassToInitialize();
}
}
Java doesn't have static constructors. It only has static initializers and static initializers do not take any arguments. It is executed when the class is first loaded, and there is no way to call it yourself.
You either need to use actual objects, or add some way of configuring the class (eg through a static method).
you should mention the member class with a static qualifier, otherwise there is no such a thing as a static class
Here you can find the explanation of using the word 'static' in this context.
Now you should just call its constructor and pass all the arguments you want,
the only restriction that you have on a static member class is that it can't refer the non-static fields of its outer class, it resembles a static methods on class that can't refer the non-static fields of class.
I didn't understand why do you mention a static initialization block here, could you please clarify a little?
Be aware also that in java there is no such a thing as static constructor....
Hope this helps
You can have a static method public static void setUp(Arg1 arg1, Arg2 arg2...) which sets up all your static fields and invoke it when your program starts.
You have to make sure this method will be called only once [or only when you want to reset these fields]
It is not possible to pass arguments directly to the static initializes (JLS:static initializers).
It would be nice if you could share more information about your goals.
You could use an enum to initialize a singleton with a string parameter like this
import java.util.*;
class Data {
static Map<String,String[]> easyDefinitions = new HashMap<String,String[]>();
}
public enum QuestionsRepository
{
repository("primary=red,green,blue;secondary=cyan,yellow,magenta");
QuestionsRepository(String dictionary) {
String[] rules = dictionary.split(";");
for (String rule:rules) {
String[] keyValuePair = rule.split("=",2);
Data.easyDefinitions.put(keyValuePair[0],keyValuePair[1].split(","));
}
}
}