To change the value of a variable in Java, you can simply assign a new value to it using the assignment operator =. For example, consider the following code:
int x = 10; int y = 20; x = y; // x now has the value 20 y = 30; // y now has the value 30Source:www.lautturi.com
In this example, the value of x is changed from 10 to 20, and the value of y is changed from 20 to 30.
You can also use compound assignment operators to modify the value of a variable. These operators perform an operation and assignment in a single statement. For example, the following code increments the value of x by 5:
int x = 10; x += 5; // x now has the value 15
Other compound assignment operators include -=, *=, and /=.
It's also possible to change the value of a variable by calling a method that modifies its value. For example, consider the following code:
public class Main {
public static void main(String[] args) {
int x = 10;
System.out.println(x); // prints 10
modify(x);
System.out.println(x); // prints 20
}
public static void modify(int x) {
x = 20;
}
}
In this example, the value of x is changed to 20 by the modify method. However, this change only affects the local variable x within the method. The value of the x variable in the main method is not changed.