Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In the main method of my program I have a bunch of scanner input which I have passed into various methods using parameters.
In those various methods I have done calculations, creating new variables.
In my final method I need to add those new variables together, but the compiler will not recognize the new variables because they only exist in those other methods. How would I go about passing the new variables to my final method?
Instead of creating local variables create class variables.The scope of class variables is that they are global meaning you can access those variables anywhere in the class
Variables created in methods are local to methods and scope is restricted to methods only.
So go for instance members, which you can share among methods.
If you declare so, you don't need to pass them among methods, but you can access and update those members in methods.
Consider,
public static void main(String[] args) {
String i = "A";
anotherMethod();
}
You get a compiler error in the below method if you try to access i, because i is a local variable of the main method. You cannot access in other methods.
public static void anotherMethod() {
System.out.println(" " + i);
}
What you can do is, pass that variable to where you want.
public static void main(String[] args) {
String i = "A";
anotherMethod(i);
}
public static void anotherMethod(String param){
System.out.println(" " + param);
}
You can create a List and pass it to each method as parameter. At the end all you need is to iterate through the list and handle the results.
Create an object with new variables and the method returning their sum.
In your methods use this object for new variables calculation.
Then use the object method for getting sum of new variables
You could do something like this:
public void doStuff()
{
//Put the calculated result from the function in this variable
Integer calculatedStuff = calculateStuff();
//Do stuff...
}
public Integer calculateStuff()
{
//Define a variable to return
Integer result;
//Do calculate stuff...
result = (4+4) / 2;
//Return the result to the caller
return result;
}
You also could do this(You can then retrieve the variable calculatedStuff in any function in the class):
public class blabla {
private Integer calculatedStuff;
public void calculateStuff()
{
//Define a variable to return
Integer result;
//Do calculate stuff...
result = (4+4) / 2;
//Return the result to the caller
this.calculatedStuff = result;
}
}
But as everyone else suggest, I also higly recommend to do a basic Java tutorial.
Related
Preface
I'd like to saying two things:
I don't know how to phrase this question in a few words. So I can't find what I'm looking for when searching (on stackoverflow). Essentially, I apologize if this is a duplicate.
I've only been programming Java consistently for a month or so. So I apologize if I asked an obvious question.
Question
I would like to have a method with a parameter that holds (path to) an integer.
How is such a method implemented in Java code?
Restrictions
The parameter should be generic.
So, when there are multiple of that integer variables, the correct one can be used as argument to the method, when it is called (at runtime).
My Idea as Pseudo-Code
Here's the idea of what I want (in pseudo-code). The idea basically consist of 3 parts:
the method with parameter
the variables holding integer values
the calls of the method with concrete values
(A) Method
.
Following is the definition of my method named hey with generic parameter named pathToAnyInteger of type genericPathToInt:
class main {
method hey(genericPathToInt pathToAnyInteger) {
System.out.println(pathToAnyInteger);
}
}
(B) Multiple Integer Variables
Following are the multiple integer variables (e.g. A and B; each holding an integer):
class A {
myInt = 2;
}
class B {
myInt = 8;
}
(C) Method-calls at runtime
Following is my main-method that gets executed when the program runs. So at runtime the (1) previously defined method hey is called using (2) each of the variables that are holding the different integer values:
class declare {
main() {
hey("hey " + A.myInt);
hey("hey " + B.myInt);
}
}
Expected output
//output
hey 2
hey 8
Personal Remark
Again, sorry if this is a duplicate, and sorry if this is a stupid question. If you need further clarification, I'd be willing to help. Any help is appreciated. And hey, if you're going to be unkind (mostly insults, but implied tone too) in your answer, don't answer, even if you have the solution. Your help isn't wanted. Thanks! :)
Java (since Java 8) contains elements of functional programing which allows for something similiar to what you are looking for. Your hey method could look like this:
void hey(Supplier<Integer> integerSupplier) {
System.out.printl("Hey" + integerSupplier.get());
}
This method declares a parameter that can be "a method call that will return an Integer".
You can call this method and pass it a so called lambda expression, like this:
hey(() -> myObject.getInt());
Or, in some cases, you can use a so called method referrence like :
Hey(myObject::getInt)
In this case both would mean "call the hey method and when it needs an integer, call getInt to retrieve it". The lambda expression would also allow you to reference a field directly, but having fields exposed is considered a bad practise.
If i understood your question correctly, you need to use inheritance to achive what you are looking for.
let's start with creating a hierarchy:
class SuperInteger {
int val;
//additional attributes that you would need.
public SuperInteger(int val) {
this.val = val;
}
public void printValue() {
System.out.println("The Value is :"+this.value);
}
}
class SubIntA extends SuperInteger {
//this inherits "val" and you can add additional unique attributes/behavior to it
public SubIntA(int val) {
super(val);
}
#override
public void printValue() {
System.out.println("A Value is :"+this.value);
}
}
class SubIntB extends SuperInteger {
//this inherits "val" and you can add additional unique attributes/behavior to it
public SubIntB(int val) {
super(val);
}
#override
public void printValue() {
System.out.println("B Value is :"+this.value);
}
}
Now you method Signature can be accepting and parameter of type SuperInteger and while calling the method, you can be passing SubIntA/SuperInteger/SubIntB because Java Implicitly Upcasts for you.
so:
public void testMethod(SuperInteger abc) {
a.val = 3;
a.printValue();
}
can be called from main using:
public static void main(String args[]){
testMethod(new SubIntA(0));
testMethod(new SubIntB(1));
testMethod(new SuperInteger(2));
}
getting an Output like:
A Value is :3
B Value is :3
The Value is :3
Integers in Java are primitive types, which are passed by value. So you don't really pass the "path" to the integer, you pass the actual value. Objects, on the other hand, are passed by reference.
Your pseudo-code would work in Java with a few modifications. The code assumes all classes are in the same package, otherwise you would need to make everything public (or another access modifier depending on the use case).
// First letter of a class name should be uppercase
class MainClass {
// the method takes one parameter of type integer, who we will call inputInteger
// (method-scoped only)
static void hey(int inputInteger) {
System.out.println("hey " + inputInteger);
}
}
class A {
// instance variable
int myInt = 2;
}
class B {
// instance variable
int myInt = 8;
}
class Declare {
public static void main() {
// Instantiate instances of A and B classes
A aObject = new A();
B bObject = new B();
// call the static method
MainClass.hey(aObject.myInt);
MainClass.hey(bObject.myInt);
}
}
//output
hey 2
hey 8
This code first defines the class MainClass, which contains your method hey. I made the method static in order to be able to just call it as MainClass.hey(). If it was not static, you would need to instantiate a MainClass object in the Declare class and then call the method on that object. For example:
...
MainClass mainClassObject = new MainClass();
mainClassObject.hey(aObject.myInt);
...
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 4 years ago.
ok so i just found out that if you have a class with global variables you can call it in another class just by saying class.variable and now i'm very confused as to why getVariable and setVariable methods exist ever when they're already accessible
so let's say we have these two classes
public class MyClass {
public int num;
public String str;
public MyClass (int num, String str) {
this.num = num;
this.str = str;
}
public int getNum () {
return num;
}
public String getStr () {
return str;
}
}
public class test {
public static void main (String[] args) {
MyClass x = new MyClass (3, "string");
System.out.println(x.num);
System.out.println(x.str);
System.out.println(x.getNum());
System.out.println(x.getStr());
x.num = 4;
System.out.println(x.num);
}
}
Both ways, it accesses the same data from the object and outputs the same thing. Is one way better practice than the other or are there certain cases where one of the ways won't work?
Short answer: encapsulation.
A major benefit is to prevent other classes or modules, especially ones you don't write, from abusing the fields of the class you created.
Say for example you can an instance variable int which gets used as the denominator in one of your class methods. You know when you write your code to never assign this variable a value of 0, and you might even do some checking in the constructor. The problem is that some else might instantiate your class and later assign the instance variable a value of 0, thereby throwing an exception when they later invoke the method that uses this variable as a denominator (you cannot divide by 0).
Using a setter, you write code that guarantees the value of this variable will never be 0.
Another advantage is if you want to make instance variables read only after instantiating the class then you can make the variables private and define only getter methods and no setters.
I need to know how to call a variable from one method to another
Can anyone help me?
public static void number(){
number = 1;
}
public static void callNumber(){
/*How can I call number to this method???
*/
}
Actually, "call a variable from an other method" is not very explicit, since a variable in a method is either global (used in the method but naturally available in the entire program), or a local variable of the method.
And in this last situation it is impossible to get this value.
Then either you declare your variable externally and it is trivial, or you specifiy a type value to your method "number()":
public static int number() {
int number = ...;
return number;
}
and you call it:
public static void callNumber() {
int numberReturned = number();
// other things...
}
Note: your code number = 1; specifies that your variable is global...
The trick is to set "number" available either by the return of the method, or by specifying this variable global.
I don't know if I've answered your question, if not try to be more explicit.
Between static methods, variables can be shared by making them global,
or by sending them as parameters(noas described by #Gaétan Séchaud).
However, if those two methods has a continuos connection between them, and they handle some variables needed to be shared, it smells like a class is needed.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am "playing around" with Java, watching tutorials and trying to get the hang of it. For this question, I'm trying to figure out how I can take a variable from another class and use it in my main one, without making the initial variable public. Here is the code:
I am trying to get int x equal to 5 (as seen in the setNum() method), but when it prints it gives me 0.
Main Class:
package getVarTest;
public class Main {
public static void main (String[]args){
Vars varsObject = new Vars();
int x = varsObject.getNum();
System.out.println(x);
}
}
Variable Class:
package getVarTest;
public class Vars {
private int num;
public void setNum(int x){
this.num = 5;
}
public int getNum(){
return num;
}
}
So, as you can see I am trying to take the private int num and make the int x in the main class equal to it.
I am trying to get int x equal to 5 (as seen in the setNum() method) but when it prints it gives me 0.
To run the code in setNum you have to call it. If you don't call it, the default value is 0.
You never call varsObject.setNum();
Do NOT do that! setNum(num);//fix- until someone fixes your setter. Your getter should not call your setter with the uninitialized value ofnum(e.g.0`).
I suggest making a few small changes -
public static class Vars {
private int num = 5; // Default to 5.
public void setNum(int x) {
this.num = x; // actually "set" the value.
}
public int getNum() {
return num;
}
}
If the variable is public you can get it just by saying packageName.ClassName.variableName, but if it is private you will have to make a getter method inside the class that the variable is in. It will look something like this:
public int getVariableName() {
return variableName;
}
Then just call that method wherever you need it.
Your example is perfect: the field is private and it has a getter. This is the normal way to access a field.
If you need a direct access to an object field, use reflection. Using reflection to get a field's value is a hack and should be used in extreme cases such as using a library whose code you cannot change.
The code that you have is correct. To get a variable from another class you need to create an instance of the class if the variable is not static, and just call the explicit method to get access to that variable. If you put get and set method like the above is the same of declaring that variable public.
Put the method setNum private and inside the getNum assign the value that you want, you will have "get" access to the variable in that case
https://stackoverflow.com/a/572550/1165790
I want to use this feature in Java because the function that I'm designing is called rarely (but when it is called, it starts a recursive chain) and, therefore, I do not want to make the variable an instance field to waste memory each time the class is instantiated.
I also do not want to create an additional parameter, as I do not want to burden external calls to the function with implementation details.
I tried the static keyword, but Java says it's an illegal modifier. Is there a direct alternative? If not, what workaround is recommended?
I want it to have function scope, not class scope.
I want it to have function scope, not class scope.
Then you are out of luck. Java provides static (class scoped), instance and local variables. There is no Java equivalent to C's function-scoped static variables.
If the variable really needs to be static, then your only choice is to make it class scoped. That's all you've got.
On the other hand, if this is a working variable used in some recursive method call, then making it static is going to mean that your algorithm is not reentrant. For instance, if you try to run it on multiple threads it will fall apart because the threads will all try to use the same static ... and interfere with each other. In my opinion, the correct solution would be either to pass this state using a method parameter. (You could also use a so-called "thread local" variable, but they have some significant down-sides ... if you are worrying about overheads that are of the order of 200 bytes of storage!)
How are you going to keep a value between calls without "wasting memory"? And the memory consumed would be negligible.
If you need to store state, store state: Just use a static field.
Caution is advised when using static variables in multi-threaded applications: Make sure that you synchronise access to the static field, to cater for the method being called simultaneously from different threads. The simplest way is to add the synchronized keyword to a static method and have that method as the only code that uses the field. Given the method would be called infrequently, this approach would be perfectly acceptable.
Static variables are class level variables. If you define it outside of the method, it will behave exactly as you want it to.
See the documentation:
Understanding instance and Class Members
The code from that answer in Java...
public class MyClass {
static int sa = 10;
public static void foo() {
int a = 10;
a += 5;
sa += 5;
System.out.println("a = " + a + " sa = " + sa);
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
foo();
}
}
}
Output:
$ java MyClass
a = 15 sa = 15
a = 15 sa = 20
a = 15 sa = 25
a = 15 sa = 30
a = 15 sa = 35
a = 15 sa = 40
a = 15 sa = 45
a = 15 sa = 50
a = 15 sa = 55
a = 15 sa = 60
sa Only exists once in memory, all the instances of the class have access to it.
Probably you got your problem solved, but here is a little more details on static in Java. There can be static class, function or variable.
class myLoader{
static int x;
void foo(){
// do stuff
}
}
versus
class myLoader{
static void foo(){
int x;
// do stuff
}
}
In the first case, it is acting as a class variable. You do not have to "waste memory" this way. You can access it through myLoader.x
However, in the second case, the method itself is static and hence this itself belongs to the class. One cannot use any non-static members within this method.
Singleton design pattern would use a static keyword for instantiating the class only once.
In case you are using multi-threaded programming, be sure to not generate a race condition if your static variable is being accessed concurrently.
I agree with Bohemian it is unlikely memory will be an issue. Also, duplicate question: How do I create a static local variable in Java?
In response to your concern about adding an additional parameter to the method and exposing implementation details, would like to add that there is a way to achieve this without exposing the additional parameter. Add a separate private function, and have the public function encapsulate the recursive signature. I've seen this several times in functional languages, but it's certainly an option in Java as well.
You can do:
public int getResult(int parameter){
return recursiveImplementation(parameter, <initialState>)
}
private int recursiveImplementation(int parameter, State state){
//implement recursive logic
}
Though that probably won't deal with your concern about memory, since I don't think the java compiler considers tail-recursive optimizations.
The variables set up on the stack in the recursive call will be function (frame) local:
public class foo {
public void visiblefunc(int a, String b) {
set up other things;
return internalFunc(a, b, other things you don't want to expose);
}
private void internalFunc(int a, String b, other things you don't want to expose) {
int x; // a different instance in each call to internalFunc()
String bar; // a different instance in each call to internalFunc()
if(condition) {
internalFunc(a, b, other things);
}
}
}
Sometimes state can be preserved by simply passing it around. If required only internally for recursions, delegate to a private method that has the additional state parameter:
public void f() { // public API is clean
fIntern(0); // delegate to private method
}
private void fIntern(int state) {
...
// here, you can preserve state between
// recursive calls by passing it as argument
fIntern(state);
...
}
How about a small function-like class?
static final class FunctionClass {
private int state1; // whichever state(s) you want.
public void call() {
// do_works...
// modify state
}
public int getState1() {
return state1;
}
}
// usage:
FunctionClass functionObject = new FunctionClass();
functionObject.call(); // call1
int state1AfterCall1 = functionObject.getState1();
functionObject.call(); // call2
int state1AfterCall2 = functionObject.getState1();