I have done a lot of google regarding this and tried many things and have never gotten through. So I have this variable in Class A and I want to print that variable in Class B but the value of the variable in Class A goes through a method before it is called.
public class TestSubject extends javax.swing.JFrame {
static String a;
private void testButtonActionPerformed(java.awt.event.ActionEvent evt) {
a = "hello"; }
}
Here I declare the variable and clicks a button to set the variable value to 'hello'. I tested if the variable did indeed get the value by having another button printing the variable 'a' in the same class.
public class TestSubject2 extends javax.swing.JFrame {
TestSubject test = new TestSubject();
private void okActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(test.a);
}
}
So here I try print the variable a from class 'TestSubject'.
So what I have tried:
I have tried to use both non-static and static.
I have tried to use a return method
class TestSubject { //purposely left the extend but you get what I mean
public String getString() {
return a; } }
Class TestSubject2 {
TestSubject test = new TestSubject();
private void okActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(test.getString());
}
}
However, if I were to explicitly give 'a' a value like:
static String a = "hello";
It would print out properly in the other class using the first method.
I made sure I click the buttons sequentially so the values are being inputted.
So what I want to know is how can I call a variable from another class.
Related
Need a variable to hold a value which will be assigned once and will be used by every method of a class
if I specify it as non static variable it is not holding the value
Class Test{
private String test;
public void method1(){
test = "String1";
}
public void method2(){
System.out.println(test.length());
}
}
Getting Null Pointer exception. the value of the test will be used in every method.
Could anyone help me, how to fix the issue.
The NullPointerException will be thrown whenever the test variable is null and you try to invoke methods on that variable. In your case, when you invoke method2() before method1(). That has nothing to do with global, local or whatever, as Long Vu already mentioned.
So first you should make sure, you don't access an uninitialized variable. Then, if you need a class with a single instance, which should be accessible application wide, you can implement this using the singleton pattern. For more about it, have a look at this Wikipedia page: https://en.wikipedia.org/wiki/Singleton_pattern
Maybe your problem is that you are creating multiple objects of class Test.
For example this should work:
Test test1=new Test();
test1.method1(); //call this first then other methods
test1.method2();
You should use this object "test1" as a parameter wherever you need it.
If you want to access the variable globally then create a Singletone class:
class Test{
private static Test single_instance = null;
private String test;
// private constructor restricted to this class itself
private Test(){
}
// static method to create instance of Singleton class
public static Test getInstance(){
if (single_instance == null)
single_instance = new Test();
return single_instance;
}
public void setTest(String value){
test = value;
}
public String getTest(){
return test;
}
public static void main(String args[]){
Test test = Test.getInstance();
test.setTest("String1");
test.getTest();
}
}
I'm trying to pass a string from my main activity to a separate class
that does not have a activity running.
I've looked into passing variables with intent and bundles but what i've read they use two activities
I've found a video of something close to what i'm trying to do but in reverse and can't get it to work. (https://www.youtube.com/watch?v=CSifkubnE-E)
Now the string changes so I can't use static
and my second.java has no context to pass to.
below is a basic representation of what i'd would like to do.
main.java
import second
public class Main extends Activity {
String mystring = "variable"
//mystring changes depending on the user
mystring = "userchangedvariable"
}
second.java
public class dosomething(){
String localvar;
localvar = mystring
}
To be clear as possible I want to pass a variable from the main.java to the second.java that has no context. I don't want to add the second.java class to my main.java, I want to keep them separate(some of the things I read say merge them). How can I do this?
I did not get the following statement.
Now the string changes so I can't use static
You can update the static values. You cannot update final values. Also, you need to somehow create a connection. You can create another class and share the static variables
class ThirdClass {
public static String sharedString;
}
class Main {
ThirdClass.sharedString = "somevalue";
}
class Second {
localVar = ThirdClass.sharedString;
}
You can do it in those ways:
class Activity {
onCreate() {
String stringToPass = "TEST";
Example example = new Example(stringToPass);
}
}
class Example {
private String stringToPass;
public Example(String stringToPass) {
this.stringToPass = stringToPass;
}
}
or
class Activity {
onCreate() {
String stringToPass = "TEST";
Example example = new Example();
example.setStringToPass(stringToPass);
}
}
class Example {
private String stringToPass;
public void setStringToPass(String stringToPass) {
this.stringToPass = stringToPass;
}
public Example() {
}
}
or
class Activity {
onCreate() {
String stringToPass = "TEST";
Example.stringToPass = stringToPass;
}
}
static class Example {
public static String stringToPass;
}
or (not the advised way)
class Activity {
onCreate() {
String stringToPass = "TEST";
Example example = new Example();
example.stringToPass = stringToPass;
}
}
class Example {
public String stringToPass;
public Example() {
}
}
If you create a new object and the string is required for creating -> great make it as a requirement in the constructor. (first version)
If you create a new object and the string is not required for creating -> great make a property (second version)
Third version is needed more rarely (you can set the string without having to create an object) and the fourth version should be avoided completely in Java.
In the main .java file, add the following:
second example = new second("variable");
This can then be referenced anywhere inside your main method. For example:
example.setString("variable);
Then, inside your second .java file, you'll need to add the following:
public class second
{
private String variable;
public void setString(String pass)
{
variable = pass
}
}
This way anything you pass to the example variable inside your main .java file
will be passed over to the setString method.
public void setAcc(String a)
{
m_acc.setText(a);
}
I want to get value of variable a is a separate variable outside this function.
The values of a is coming from another Controller Class.
Declare a variable outside of the method and change that variable inside the method.
private String acc;
public void setAcc(String a)
{
this.acc = a;
m_acc.setText(a);
}
...
System.out.println(acc); //prints the value of a
I update a variable (which is global in the class) in one method and I cannot seem to be able to then pass that updated variable into another method.
Any help would be appreciated, thank you.
Here's my shortened code:
public class Game{
private int randomIndexX;
protected String spawn(){
randomIndexX = randomGenerator.nextInt(10);
return null;
}
protected String test(){
System.out.println(this.randomIndexX);
return null;
}
}
public class Player extends Game{
protected String getNextAction(String command) {
switch(command){
case "test":
test();
break;
}
}
}
public static void main(String[] args) {
Game game = new Game();
Player player = new Player();
game.spawn();
player.getInputFromConsole();
}
EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test()
EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test().
So test() is instance method, which means you'll have to make an instance of Class Game in order to call that method, your randomIndexX is instance member so you need to think well what you want to do, IF randomIndexX is common for all the objects of Game class, you should declare it static as in:
private static in randomIndexX;
As it's value won't change depending on an object instance.
So in order to access that variable from outside of the class since it's private you declare a public method to retrieve that value (getter or also known as accessor):
public static int getRandomIndex(){
return randomIndexX;
}
So when in main, you don't even have to make an instance of the Game class to access value that's being held in randomIndexX, you just call the getter method like this:
System.out.println(Game.getRandomIndex());
The line above will print 0 to the console as 0 is default value for members of type int, now if you want to be able to change it, you just make a setter or mutator method in Game class as well:
public static void setRandomIndex(int n){
randomIndexX = n;
}
And there you go, you can now set and retrieve "randomIndexX" field from outside of the Game class.
For example, the code below will set value of randomIndexX to 5 and then print it in the console:
Game.setRandomIndex(5);
System.out.println(Game.getRandomIndex());
The first problem I can see is that you don't have a constructor.(Optional)
(If you don't make one the compiler makes what is called a "Default" constructor which is a constructor without any parameters. Its usually good practice to explicitly create a class constructor.
The second problem I can see is that you missing the end bracket.
Fix shown below.
public class Game
{
private int randomIndexX;
protected String spawn()
{
randomIndexX = 0;
return null;
}
protected String test()
{
System.out.println(randomIndexX);
return null;
}
}
You can construct it and trigger any methods you wish:
Game game = new Game();
game.spawn();
game.test()
Scenario is like this:
There is a field in database 'overAllCount' which contains some value.
I have to use this variable in many classes I am designing.
I want to fetch this 'overAllCount' in one class say 'OverAllCountClass' and use it in all subclasses with its class name like OverAllCountClass.overAllCount. Basically like a static variable.
How can I do it?
My solution is:
public Class OverAllCountClass {
public static int OverAllCount;
public OverAllCountClass(){
// Fetch overAllCount from database here and set its value
}
}
////////// Use it like this //////////////
public class Usecount {
public void abc(){
// BUT IT IS NOT POSSIBLE becuase OverAllCountClass is not yet initialize
int mycount = OverAllCountClass.overAllCount
}
}
How can I achieve this?
If your concern is, the static variable overAllCount, might not get initialized and if you want it to get initialized whenever the class OverAllCountClass first gets invoked, then you can use Static initializer blocks
public class OverAllCountClass {
public static int overAllCount;
static {
overAllCount = fetchOverAllCount();
}
}
A static initializer block is invoked first time a class gets loaded. And a class gets first loaded when JVM sees that its been used.
public class Usecount {
public void abc(){
//When JVM sees that OberAllCountClass is used here, it executes the static block of OverAllCountClass and by the time below statement is executed, overAllCount is initialized
int mycount = OverAllCountClass.overAllCount
}
}
public Class OverAllCountClass {
protected int overAllCount; //will allow you to use in subclass too
public OverAllCountClass(){
// Fetch overAllCount from database here and set its value
}
public int getOverAllCount(){
return overAllCount;
}
}
public class Usecount {
//pass the instance of overAllCountInstance to UseCount somehow using constructor or setter
private OverAllCountClass overAllCountInstance;
public void abc(){
int mycount = overAllCountInstance.getOverAllCount();
}
}
No need to use static over here. Use getter to get the count
Rather than having a public static variable which can be modified/abused by other classes. I would provide a specific API which can hide the implementation and do things like lazy-loading if needed:
public static final Value getValue(){
//evaluate private field
return value;
}
This API can be a static method or be a singleton scoped method, depending on use case.
Another option is to make OverAllCountClass a Singleton.
public class OverAllCountClass {
private static final OverAllCountClass instance = new OverAllCountClass();
private Integer overAllCount = null;
// make it non-instanciable outside by making the constructor private
private OverAllCountClass {
}
public static OverAllCountClass getInstance() {
return instance;
}
public int getOverAllCount() {
if (overAllCount = null) {
//get value from database and assign it
}
return overAllCount;
}
}
This has the benefit that to code that accesses OverAllCountClass it is transparent wether it's a Singleton or not. This makes swapping out the implementation easier.