I have two .java files and I want to access a variable of a method in one of the files and use it in another. However, I dont want to call the whole method and I dont want the method to return a value...I'll try to illustrate below

//file_A.java
class file_A{
//some code 
  void first_method(){
      int variable_a=2; //variable used in this method for several things
  }
}

//file_B.java
class file_B
{
//some code
  void second_method(){
      System.out.println("var"+variable_a);//ofcourse this does not work but Iam trying to do something like this
  }
}

I hope this helps to explain my problem

You can have the variable be "global". Here are 2 examples:

class ClassA {
public int variableA = 0;

public ClassA() {

}

public void method() {
   variableA = 2;
}
}
class ClassB {
public ClassB() {

}

public void methodB() {
  ClassA clA = new ClassA();
  clA.method();

  System.out.println(clA.variableA ):
}
}

If you have a variable declared in a method you cannot access it from outside that method because it is out of scope. You need to declare it inside the class. If you declare it "private" you will need a "get" method in order to return its value.
Now if you want to access it from another class you will need of course to create an instance of the class: "ClassA" and call the method that changes its value.

But things are different when you declare it static:

class ClassA {
public static int variableA = 0;

public static void method() {
   variableA = 2;
}
}
class ClassB {
public ClassB() {

}

public void methodB() {
  ClassA.method();

  System.out.println(ClassA.variableA):
}
}
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.