Changing variable by method [duplicate] - java

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
Why am I getting an output equals 5? I was expecting 6, because after the "addthenumber(x);" line, the method is called, and what I am thinking is the method performs the calculation and 5 becomes 6. So sysout should print 6, but how is it 5?
public class CodeMomkeyPassingvalue
{
public static void main(String[] args)
{
int x = 5;
addthenumber(x);
System.out.println(x);
}
private static void addthenumber(int number)
{
number = number+1;
}
}
output:
5

Arguments to methods are passed by value, not by reference. That means that not the variable itself, but only the value of the variable is passed to the method.
The variable number inside the method addthenumber is not the same variable as the variable x in the main method. When you change the value of number, it does not have any effect on the variable x in main.

Below code
{
int x = 5; // declare x = 5 here
addthenumber(x); // calling function, passing 5
catch is here - Arguments are passed by value, not by reference. x itself is not passed, only the value of the x is passed to the method.
System.out.println(x); // printing same x value here, ie 5
}
private static void addthenumber(int number) {
number = number + 1; // 1 added to number locally, and is referencing inside method only.
}

Java follows the call by value paradigma, so the value is not changed in the calling function. If you would like to change the value you have to return it after adding 1;
public static void main(String[] args)
{
int x = 5;
x = addthenumber(x);
System.out.println(x);
}
private static int addthenumber(int number)
{
return number+1;
}

Related

The array value changed after calling static method with the array Java [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 2 years ago.
The value of array elements are getting changed while calling a static method with the parameter passing the same array as argument but primitive value does not get changed
Is it work differently in the case of while we pass data structure as method argument ?
Want to know why array element get changed after the method call with the array ..
I was expecting value 0 in the last syso statement instead of 999
public class TestStatic {
public static int square (int x)
{
x = x + 1;
return x * x;
}
public static int[] changeArr(int a[])
{
a[0] = 999;
return a;
}
public static void main(String[] args)
{
int a = 10;
System.out.println((square(a)));
System.out.println(a);
int arr[] = {0,0};
changeArr(arr);
System.out.println(arr[0]);
}
}
Actual Output:
121
10
999
I was expecting
121
10
0
In Java, method parameters are by reference, not by value, which means you pass the reference to the object, not a copy of the object. Note that primitives are passed by value.

Java variable scope in and outside loop [duplicate]

This question already has answers here:
Java variable may not have been initialized
(7 answers)
Why does the Java compiler not understand this variable is always initialized?
(3 answers)
Closed 2 years ago.
I wrote this code in an online java test recently. It was inside a method that was set to return an integer. I got an error message something like "variable a has no value assigned to it". I find this odd because the forloop must have access to the methods variable and the assignments inside of the loop must be registered right?
int a;
for(int i=1;i<5;i++){
a = i;}
return a;
I did assume that the method would return the integer 5.
This is only a question regarding scope of the variable a. I know that the code makes no sense.
You can try below code , that will help you. Initialisation is mandatory for any variable to return or hold any value.
class a{
public static void main(String[] args) {
System.out.println(test());
}
public static int test(){
int a = 0;
for(int i=1;i<5;i++){
a = i;}
return a;
}
}

How to return an Int from one method to another in java [duplicate]

This question already has an answer here:
Returning a value from one method to another method
(1 answer)
Closed 4 years ago.
public static void main(){
getNumber();
printNumber();
int x;
}
public static int getNumber(){
int x = 5;
return(x);
}
public static void printNumber(){
System.out.println(x);
}
I am a total beginner, sorry for such a simple question. The above fragment of code is what I tried.
public class Test {
public static void main(String[] args) {
int x = getNumber();
printNumber(x);
}
public static int getNumber() {
int x = 5;
return x;
}
public static void printNumber(int x) {
System.out.println(x);
}
}
First of all:
public static int getNumber(){
int x = 5;
return(x);
}
Creates another local variable x. So that assignment affects only the x that "belongs" to getNumber(). The static field x of your enclosing class stays at its initial value of 0.
But there you go:
public static void printNumber(){
x = getNumer();
System.out.println(x);
}
Of course, a first step for writing more reasonable code: you decide whether you want to have that "global" field that all methods of your class can use, or if you want to not do that.
Meaning: either you use that field, then your method just updates x, and the other method prints it. Or your class doesn't have that field, and your two methods work by getNumber() returning a value, and then printing that returned result.
Can you firstly explain, what you want to do by this code?
Let's go through your code:
I concider method printNumber() to be excess because It's just wrapper for System.out.println method, we can use it derectly in our code.
Method getNumber() could receive some paramater, for example getNumber(int a). With such improvement we would be able to call getNumber from our main method and pass to it variable that we define in main method. Than getNumber could perform some operation, forexample a * a and return this result.
Also main method of java programm must look like below.
public static void main(String[] args) {
int x = 5;
int resultOfGetNumber = getNumber(x);
System.out.println(resultOfGetNumber);
}
public static int getNumber(int a){
return(a * a);
}
So we define variable x in our main method and passes it to the getNumber method, which returns the square of received variable. Then in main method we assing result of getNumber method to the int variable resultOfGetNumber. Then we pass resultOfGetNumber to the System.out.println method, which prints this variable to the console.

Static recursive method in Java doesn't update variable value [duplicate]

This question already has answers here:
How do I pass a primitive data type by reference?
(8 answers)
Closed 4 years ago.
I have the following code
private static void modifyX(int x) {
if (x!=0) {
modifyX(--x);
}
}
I want the value of my variable to be updated after the recursive call, so I wrote the following code:
public static void main(String... args) {
int x = 5;
modifyX(x);
System.out.println("Modified value:\t" + x);
}
However, the value remains the same (5).
Why is my variable not updating?
You are not passing the same instance of the value 5. Instead, the JVM is creating a new int with a value of 5, and passing that to your method.
See this thread for more information.

How to accept a public static variable as parameter in Java [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
I have the following instantiated variable
public static int r1 = 10;
I have several of these variables r1 - r4, I want to write a method that will be able to take the variable r1 as a parameter of the method and increment it.
Pseudo code would look like :
r1 = r1 + 1;
My question is how can I take the variable as a parameter of one method instead of writing 4 different methods to accomplish this?
You can't, because Java does not let you pass variables of primitive types by reference.
You can put your variables into an array, and pass an array and an index:
public static int[] r = new int[4];
...
public static void modify(int[] array, int pos) {
array[pos]++;
}
...
modify(MyClass.r, 1); // instead of modify(MyClass.r1);
Alternative approach is to return the modified value to callers, and let them assign it back:
public static int modify(int orig) {
return orig+1;
}
...
MyClass.r1 = modify(MyClass.r1);

Categories