javamethodsreturn

Confusing return statment


Trying to pass x from method to another, then sum it before printing it in main. The program works perfectly, but 8th line is confusing me. I need a brief breakdown of this code, which I obtained after following the IDE's errors warnings

1 package tttt;
2
3 public class Class {
4
5   public static int test() {
6
7       int x = 1;
8       return test2(x);
9
10  }
11
12  public static int test2(int a) {
13       a += 2;
14       return a;
15
16  }
17 }
package tttt;

public class fff {

    public static void main(String[] args) {
    
    
        System.out.println(Class.test());
    }

}

Solution

  • i left the comments in your code. You can return links on data structures (List, Queue, Map) or literals like Numbers.

    1  package tttt;
    2
    3  public class Class {
    4
    5    // The main method named 'test'
    6    public static int test() {
    7
    8        // Declare and initialize a variable 'x' with the value 1
    9        int x = 1;
    10
    11       // Call the method 'test2' with the argument 'x' and return its result
    12       return test2(x);
    13
    14   }
    15
    16   // Another method named 'test2' with an integer parameter 'a'
    17   public static int test2(int a) {
    18       // Increment the parameter 'a' by 2
    19       a += 2;
    20
    21       // Return the modified value of 'a'
    22       return a;
    23
    24   }
    25 }
    

    All differences arise when you pass the value of a variable that is an array; the variable's value becomes a reference to the original array. If you modify it in another method as an argument, you will alter the original array.

    class Main {
        public static void main(String[] args) {
            int[] d = Class.test();
            
            for (int i : d){
                    System.out.println(i); /// 1, 2, 10
            }
        }
    }
    
    class Class {
        public static int[] test() {
            int[] x = {1, 2, 3};
            test2(x);
            return x;
        }
    
        public static void test2(int[] a) {
            a[2] = 10;
        }
    }