Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Why aren't variables I modify inside myMethod are not modified outside that scope?
public class TestLoop {
public static void main(String[] args) {
myMethod(0, 3);
}
static void myMethod(int i, int j) {
System.out.println("i for:" + i + " j:" + j);
if (i == j)
return;
else {
myMethod(i + 1, j);
System.out.println("after myMethod Call for: i:" + i + " j: " + j);
}
System.out.println("outside i for: " + i);
}
}
Each time you call myMethod(i + 1, j), new local variables i and j are created on the stack and initialized to the values passed to them by the caller.
When each execution of myMethod() returns, the local variables i and j get out of scope. You return to the previous myMethod() execution, which has its own local variables i and j having their own values.
Finally, when the call stack returns to the original myMethod(0,3) call, that execution has local variables i and j with values 0 and 3.
The values of i and j never change. There are just multiple local variables named i and j, each one having a limited scope.
The JLS - Chapter 14. Blocks and Statements contains the answer for your question:
The break (§14.15), continue (§14.16), and return (§14.17) statements cause a transfer of control that may prevent normal completion of statements that contain them.
The control is returned back to the statement where the method was called from.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have created a simple recursive method like this:
public void rec(int a) {
if(a > 0) {
rec(a - 1);
System.out.println(a);
}
}
the output for this method is:
1
2
3
4
5
And that's just great but the question is why when I write the print command outside the if statement the output starts from 0 not 1?
public void rec(int a) {
if(a > 0) {
rec(a - 1);
}
System.out.println(a);
}
why when I write the print command outside the if statement the output starts from 0 not 1?
Because, in the first version, the if (a > 0) prevents the function from printing 0. How about we look at what is happening here by including both prints:
public void rec ( int a) {
if(a>0) {
rec(a-1);
System.out.println("Inside if: " + a);
}
System.out.println("After if: " + a);
}
In the code
public void rec(int a) {
if(a > 0) {
rec(a - 1);
System.out.println(a);
}
}
you recursively invoke the method rec() with "a" as the parameter value for the first method invocation and then "a-1" for all the subsequent method invocations.
The rec() method has if clause which only executes if the value of parameter "a" received is greater than 0.
if the value of "a" is 0 then the method simply does nothing and returns back to invoking point and prints the value of variable a in that method scope.
An important point is that the value of "a" in a method scope is not being altered only the parameter to the next method call is being altered (i.e a-1)
Let' say the initial method call is something like
rec(5) // <-- method invoked with a = 5
//method definition
public void rec(int a) { // <-- a = 5
if(a > 0) { // 5 > 0 ? True
rec(a - 1); // rec(5-1) ie rec(4) but a = 5 still
System.out.println(a); // <-- a = 5 in this method scope
}
}
To have a better idea you can read on scopes,methods and call Stacks.
This will give a better grasp on recursion as well.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
public static int countX(String str) {
if (str.length() == 0) {
return 0;
}
if (str.charAt(0) == 'x') {
return 1 + countX(str.substring(1));
} else {
return countX(str.substring(1));
}
}
Given an input String of "xxx", the method above shall return 3.
I understand the flow of the method, the line "return 1 + countX(str.substring(1));" adds one if an 'x' is found. What I don't understand is how does that return value carry over to the next iteration/recursion? I don't see the value of the increment stored anywhere.
Look at the line return 1 + countX(str.substring(1));
Now suppose that str was "xx", so the substring passed to the recursive call is "x".
So in that call, since the first character is 'x', it again executes
return 1 + countX(str.substring(1));
in the next recursive call, the substring is empty, so it returns zero to the previous call, which then returns (1+0) to its previous call, which returns ( 1 + (1 +0) ) to the initial call of the method, so the result for the String "xx" becomes 1+1+0 = 2.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Trying to call a method within a method.
public static void main(String[] args) {
int sq,cu=0;
//user input 1
sq=Integer.parseInt(JOptionPane.showInputDialog(
"Enter value to be squared"));
//user input 2
cu=Integer.parseInt(JOptionPane.showInputDialog(
"Enter value to be cubed"));
//results
JOptionPane.showMessageDialog(null, sqd(sq));
JOptionPane.showMessageDialog(null, cbd(cu));
}
public static String sqd(int sq){
int sqd=sq*sq;
//sq computation
return sq+" squared is "+sqd;
}
public static String cbd(int cu,int sqd){
int cbd;
cbd=sqd*cu;
//cu computation
return cu+" cubed is "+cbd;
} }
calling sqd value in cbd, but
JOptionPane.showMessageDialog(null, cbd(cu));
prevents me from doing so, it always gives me an error when I run it.
your cbd(int cu, int sqd) method needs 2 input parameters , you are calling it with only one parameter cbd(cu)
two choices :
1 - rewrite your cbd method with 1 parameter then you can call it using cbd(cu);
public static String cbd(int cu){
return cu + " cubed is " + (cu*cu*cu);
}
2 - write it's second parameter while you are using it :
cbd(cu,cu*cu);
Your cbd method, as it's currently defined, takes two arguments - cu and sqd. If you want to keep the way your main calls it, you need to rewrite it with just one argument:
public static String cbd(int cu){
int cbd = cu * cu * cu;
return cu + " cubed is " + cbd;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I know that primitive types called by value(a copy of value has been sent)
My code:
static int a = 5;
public static void main(String[] args) {
System.out.println("a= " + a);
setA();
System.out.println("a= " + a); //Why is not 5?
setA2(a);
System.out.println("a= " + a); //Why is not 7?
}
public static int getSeven() {
return 7;
}
public static void setA() {
a = 6;
}
public static void setA2(int n) {
n = getSeven();
}
Output:
a= 5
a= 6
a= 6
Why other two output is 6 again?
Why a is changed?
a is not an object!
The second output is 6 since you set it to 6 by the preceding row (function setA()). setA() is setting a primitive outside of the function but in the class, so this is also available in main().
The third output is 6 since you set the primitive n instead of a. It is a primitive so it has no reference to a anymore.
a is global variable.
setA() will set the value of a as 6. So every where the value of a will be six.
getSeven() is returning 7 but you are not capturing it. So a will remain as it is.
try it like this a=getSeven();
setA2(int n)is assigning n to 7 but not to a.
try it like this
public static void setA2(int n) {
a = getSeven();
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Using recursion how can i keep the local variable updated till a condition is met. I have an instance below that explains why question very well. The count variable is a local variable and very time the method goes through the count is set to 0. I cannot move the count outside the method it has to be local variable not static or anything else.. The desired output should be (3 6)
public static int returnInt(int b) {
int count = 0;
if (b == 6) {
System.out.println(count + " " + b);
}
b += 2;
count++;
return returnInt(b);
}
Pass count as an additional parameter to the method:
public static int returnInt(int b, int count) {
... do some stuff to b, print something, check whether end-condition has been met ...
return returnInt(b, count + 1);
}
Then, call returnInt with an extra argument of 0 to start things off.
You cannot. Local variable is local by definition. It exists only in scope of current execution of the method.
BUT you have the following solutions.
The best one is to pass it as a parameter of your method (exactly as you do with other parameter b.
public static int returnInt(int b) {
return returnInt(b, 0)
}
private static int returnInt(int b, int count) {
// your code here.
}
If (for some strange reason) you cannot change the method signature you can put this variable into ThreadLocal. In this case even if several threads execute your method simultaneously your code stays thread safe.
Moving this variable to class level is the worst solution cause it is not thread safe and breaks encapsulation.
This function will overflow your stack. You must provide a way out when using recursion. And as for the variable count, you are redefining it back to 0 every time; it cannot be initialized inside the recursive function. Try passing it to your function as a parameter, and also providing a way out for your function.
public static int returnInt(int b,int count) {
if (b == 6) {
System.out.println(count + " " + b);
return b;
}
b+=2;
count++;
return returnInt(b);
}
the 'return b' line can be your way out...and you don'y necessarily have to return b... return whatever you need.
public static int returnInt(int b) {
return returnInt(b, 0);
}
private static int returnInt(int b, int count) {
if (b == 6) {
System.out.println(count + " " + b);
// My guess is you should be returning something here???
// Actually, this shouldn't be your exit point from the recursion because depending on the starting value of b, since you are always adding 2, it might never equal 6, so again you would get a StackoverflowException.
}
b += 2;
count++;
return returnInt(b, count);
}
In general, create returnIntInner(int b, boxed count), move the bulk of the logic to that, and call that from a "thin" version of returnInt. To box count the "old style" way is to pass the count as an int[1] array, so that it can be returned -- I've not studied up on the new Java reference parm syntax. But since your code is tail-recursive and doesn't need to access count after the recursive call, you can simply pass count as a regular parameter.