how to pass a variable in method in java and modify inside the variable
Asked
Active
Viewed 81 times
-2
-
You're not modifying your A and B float. The X and Y are not the same value as A and B, you cannot modify those floats from inside the method! – LeoColman Dec 13 '17 at 15:59
-
Primitive types are passed by value in Java. You do not have a reference back to your A and B. – Kalenda Dec 13 '17 at 16:00
-
1@Kalenda All types are passed by value in Java, not just primitives. – azurefrog Dec 13 '17 at 16:25
-
@azurefrog You are certainly correct, Java always pass-by-value, but the value being passed is a reference. – Kalenda Dec 13 '17 at 17:09
1 Answers
1
Change your code like this
public class prueba {
private static void mod1(float x, float y) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number:");
x = sc.nextFloat();
System.out.println("Enter second number:");
y = sc.nextFloat();
System.out.println("A + B = " + (x+y));
}
public static void main(String[] args) {
float a = 0;
float b = 0;
mod1(a, b);
}
}

Ramesh sambu
- 3,577
- 2
- 24
- 39