Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect result after addition within a function

Tags:

java

I have a java program that does not return the correct answer and I cannot figure out why. here's the code:

public class hello {
    public static void main(String[] args) {
        int a =5;
        doubleNumbers(a);
        System.out.println(" 5 doubled is:"+a);
    }

    private static void doubleNumbers(int a) {
        a = 5*2;
    }
}

It is my first java program after helloWorld.

like image 429
Johnny D Avatar asked Jul 04 '26 12:07

Johnny D


2 Answers

Java is pass-by-value, which means that the variables passed to a function are not changed outside of it.

As this is homework I will not show you the solution, but just tell you to return the value of the calculation.

like image 150
MByD Avatar answered Jul 06 '26 00:07

MByD


you're not returning anything from your method

change it to

 private static int doubleNumbers(int a) { 
return a * 2; 
 } 
like image 44
Chris Avatar answered Jul 06 '26 01:07

Chris