Unable to retrieve value of static variable in JAVA [duplicate] - java

This question already has answers here:
Why doesn't the main method run?
(3 answers)
Closed 5 years ago.
I want to access a static variable set in one Java class in another class. I am using the syntax properly I guess but I am getting null everytime.
Could someone help with this?
Class 1:
public class Test {
public static List<String> dbobj;
public static void main(String args[]) {
List<String> accnos= new ArrayList<String>();
accnos.add("1");
accnos.add("2");
accnos.add("3");
dbobj=accnos;
System.out.println("dbobj"+dbobj);
}
}
Class 2 :
public class Test2 {
public void main(String args[]) {
List<String> list1= Test.dbobj;
System.out.println("List value"+list1); **//COMING AS NULL**
}
}

You have two entry points (programs) which absolutely independent of each other.
When you are calling a Test.dbobj, the main method from the Test is not executed, therefore its initialisation dbobj=accnos; is not called.
It is a bit awkward, but you could call the Test.main(args); before printing to execute that init process.

When you're within the main method of Test2, the main of Test has not been called.
The static variable dbobj has therefore its initial value, being null.

First of all you can't have 2 main functions and expect it to run both, so the better way to do this would be using a static code block in Class1 like this
static {
List<String> accnos= new ArrayList<String>();
accnos.add("1");
accnos.add("2");
accnos.add("3");
dbobj=accnos;
System.out.println("dbobj"+dbobj);
}

Try this changes in your class Test2:
Test.main(args); // added
List<String> list1= Test.dbobj;
Problem is you are using static variable dbobj from class Test without initializing that given variable. As of now, dbobj is assigned value inside Test.main(), so likewise you need to invoke that method.

There is no code executed that initialized the dbobj list, when your invoke main method in Test2 class. Therefore it points to NULL.
The easiest fix is to initialize it right when it is declared :
public static List<String> dbobj list = new ArrayList<>() {
{ add("str1"); add("str2"); }
};
The other solution is to fix Test1 class as below:
public class Test {
public static List<String> dbobj;
public static void init() {
List<String> accnos = new ArrayList<>();
accnos.add("1");
accnos.add("2");
accnos.add("3");
dbobj=accnos;
System.out.println("dbobj"+dbobj);
}
}
public class Test2 {
public void main(String args[]) {
Test.init();
List<String> list1 = Test.dbobj;
System.out.println("List first value" + list1[0]); // should be OK
}
}

Related

How to access static block variables outside of class in java [duplicate]

This question already has answers here:
What is the scope of variables declared inside a static block in java?
(4 answers)
Closed 3 years ago.
I was working on some code in which I need to access the variable "hs" present in the static block of one class from another.
Note: Both the class are preset in different packages.
Code is as follow:
public class A{
static {
HashSet<String> hs = new HashSet<>();
}
}
I Googled about it but nothing found anything helpful.
Your help would be very appreciable.
EDIT: I am not allowed to make changes in this file still need to access it from the other file.
Why I need to do this cause I am doing unit testing by JUnit and there is nothing what this block is returning which I can put assertEquals() on. So the option I left with is to test the side-effects and this variable "hs" value is getting changed as a side-effect. That's why I need to access it from another file.
Declare it as public static inside the class and initialize it in static block
class A1{
public static HashSet<String> hs;
static {
hs= new HashSet<>();
}
}
Need create getter and setter for variable "hs".
Class 1:
public class Test {
public static HashSet<String> hs;
static {
hs = new HashSet<>();
hs.add("Test14");
hs.add("Test15");
hs.add("Test16");
}
public static HashSet<String> getHs() {
return hs;
}
public static void setHs(HashSet<String> hs) {
Test.hs = hs;
}
}
Class 2
If you need to use "hs" variable in without static method then:
public class Test2 {
public void test() {
Test ts = new Test();
ts.getHs();
}
}
If you need to use "hs" variable in with static method then:
public class Test2 {
public static void test() {
Test.getHs();
}
}

How to acces the value of an ArrayList of another class? [duplicate]

This question already has an answer here:
Why won't my public void Constructor {} compile?
(1 answer)
Closed 5 years ago.
i have one class with an arrayList, and i create a method (getList) that will return its value.
ArrayList<String> data = new ArrayList<>();
public void Tes2(){
data.add("aku");
data.add("sudah");
data.add("mandi");
}
public ArrayList getList(){
return data;
}
then i have another class that will call the arrayList from the previous class.
public static void main(String[] args) {
Tes2 ambil = new Tes2();
ambil.getList();
System.out.println(ambil.getList()+" ");
}
but when i compile the code, there's nothing is printed. i don't know what is wrong, it's like my arraylist is empty. how can i do it right?
Either remove the void in the constructor or change it to some other name (eg Loadlist) so that it becomes a method. Then from your main class you can call ambit.Loadlist() to load the list and then you can write ambil.getList ()

Are these two method calls the same? [duplicate]

This question already has an answer here:
What are the advantages of an anonymous object?
(1 answer)
Closed 6 years ago.
Code blocks number 1.
public class SomeClass {
public static void main(String [] args) {
SomeClass foo = new SomeClass();
foo.SomeMethod();
}
public void SomeMethod() {
}
}
Code blocks number 2.
public class SomeClass {
public static void main(String [] args) {
new SomeClass().SomeMethod();
}
public void SomeMethod() {
}
}
Are this two code blocks(number 1 and 2) the same? I'm confused over the different syntax during calling the method. I appreciate if someone could explain it for me.
Yes, they are functionally the same. With code block 2, however, you have no way of accessing the SomeClass object you created in the future lifespan of the program.
Yes they are same. In first case the object reference is just stored in a reference variable for future usage .
In second case the reference is not stored.

Calling method in main method

I want this code to generate a random number between one and five and then, using that number, chose a symbol out of my arraylist and print it. Whenever I try to call the printSymbol() method it tells me to change it and the arraylist to static. When I do it gives me two errors on the method call line in my main method and the line where it says that String y = list.get(x); I want to know how to make it so I can call this method and get it to print String y for me.
import java.util.*;
import java.lang.Math;
public class study {
public static void main(String[] args) {
printSymbol();
}
ArrayList<String> list = new ArrayList<String>();
public void addSymbols(){
list.add("あ");
list.add("い");
list.add("う");
list.add("え");
list.add("お");
}
public String printSymbol(){
int x=(int) Math.floor(Math.random()*5)+1;
String y = list.get(x);
return y;
}
}
You're messing up by mixing static and non-static contexts.
The printSymbol() method is part of the class study. (Use Study instead, that's the proper convention. For more information on these conventions, look here).
The main method is in a static context. This means that you need to make an object of the class Study and then call the printSymbol method on that object.
public static void main(String[] args)
{
Study study = new Study(); // create a new object of the class Study
study.printSymbol(); // call the printSymbol method on this object
}
You could also make the printSymbol() method and the ArrayList static, but that is bad practice in Java, which is an object oriented language.
Your main method is static, which means it can be called without creating an object. Main methods always have to be static, because on startup of the program you don't have an object yet.
The thing about static methods is, you can only access other static members from it unless you create an object you work with.
You have two possible solutions:
Make the other members static, which I wouldn't recommend as you are already using a field, or use an object:
public static void main(String[] args) {
study myObject = new study();
study.printSymbol();
}
import java.util.*;
import java.lang.Math;
public class study {
public static void main(String[] args) {
study newStudy = new study();
newStudy.addSymbols();
newStudy.printSymbol();
}
ArrayList<String> list = new ArrayList<String>();
public void addSymbols(){
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
}
public String printSymbol(){
int x=(int) Math.floor(Math.random()*4)+1;
String y = list.get(x);
return y;
}
}
Your random was also wrong, its needs to be Math.random()*4.
I just replaced your symbols with ASCII for my machine to understand.
Like every one suggested, avoid static method and create an object then call your methods.
And dont forget to add the symbols to the arraylist, you can do it in the constructor or in the main method after creating the object and before calling printSymbol()
public static void main(String[] args) {
new study().printSymbol();
}
public study() {
// add symbols to the array list
addSymbols();
}
Or
public static void main(String[] args) {
study s = new study();
// add symbols to the array list
s.addSymbols();
s.printSymbol();
}
Also by convention Classnames should start with an upser case letter.
main is a static method and from it you may either call static methods, or you have to create an instance of the class and call instance methods of it. Also in your case list is an instance variable and thus it can not be accessed from static methods.
I believe the best option for you is to do something like:
public static void main(String[] args) {
study s = new study();
s.printSymbol();
}
Also please use capital names for classes.
public `static` String printSymbol(){
public `static` void addSymbols(){
The main method is in static context, so all other method its calling needs to be as well.

Can not make static reference to non static method? [duplicate]

This question already has answers here:
Static Classes In Java
(14 answers)
Closed 3 years ago.
So, in short. I have two classes.
package rpg;
public class Engine {
public void main(String args[]) {
Start.gameStart();
System.out.println(menuResult);
}
}
and
package rpg;
public class Start {
int menuResult = 3;
public int gameStart()
{
return menuResult;
}
public int getMenuResult()
{
return Start.menuResult;
}
}
It keeps throwing up the error 'Cannot make static reference to non-static method gameStart()'.
I'm sure I'm missing something simple, but can't find it.
Thanks!
You need to create instance of Start class and call gameStart() method on that instance because gameStart() is instance method not static method.
public void main(String args[]) {
new Start().gameStart();
..................
}
Only static methods can be accessed by using class name as perfix.
public int gameStart() <--- Instance method not static method
call it on instance
Start start = new Start();
start.gameStart();
So finally your classes should look like below
public static void main(String args[]) {
Start start = new Start();
start.gameStart();
System.out.println(start.getMenuResult());
}
public class Start {
private int menuResult = 3;
public int gameStart() {
return this.menuResult;//Don't know why there are two methods
}
public int getMenuResult() {
return this.menuResult;
}
}
first of all the main method should be
public static void main(String args[]) {
}
I assume you can have multiple games, and hence you should be able to start multiple instances so you should create a non static class that can be created and then actions performed against.
to answer your original question, you need to have a static variable that have static getters and setters..
public class Start {
private static int menuResult = 3;
public static int gameStart()
{
return menuResult;
}
public static int getMenuResult()
{
return Start.menuResult;
}
If you need the method to be static, just add the keyword static in the function definition. That would get rid of the error. But if you want to keep the class Start the way it is, then you should create an instance of Start in the main function and then call the method. Hope that helps!
you are trying to invoke a method on its class name. you should be creating a new object and invoke its method
public void main(String args[]) {
new Start().gameStart();
System.out.println(menuResult);
}
Start.gameStart() refers to a method which would be public static int gameStart() because Start is the class and not an instance of the object.
If you declare a method on an object, you need to apply it to instance of the object and not its class.
When to use static or instanciated methods ?
instanciated : whenever you need to apply the method to the object you're in. example : mycake.cook();
static : when the actions you do inside your method have nothing to do with an object in particular. example : Cake.throwThemAll();
mycake is an instance of a Cake, declared this way : Cake mycake = new Cake();
Cake is the class representing the object.
You should, i guess, have a read at some object oriented programmation course if you still have a doubt about objects, classes and instances.
While Other answers are Correct , that remains the Question that Why you Can't access Instance
method Directly from Class name , In Java all static (methods , fields) bind with Class Name and when Class Is Loading to the Memory (Stack) all static members are Loading to the Stack , and this time Instance Method is not visible to Class. instance Method will Load into Heap portion in the memory and can only be access by Object references .

Categories