+ 1

About return values

It seems like this code should print 1 because the function call rec(f); passes the value 1, it seems like it would ignore what's in variable i and have it replaced with the value of variable f. But it prints 0 instead. public class Program { public static void main(String[] args) { int f=1; int i=0; rec(f); System.out.println(i); } public static int rec(int i){ return i; } }

15th Oct 2022, 1:31 PM
Natanael
3 odpowiedzi
+ 2
rec(f) returns f but you are not catching return value. To catch it, store in a variable like i = rec(f); Or print returned value by System.out.print( rec(f));
15th Oct 2022, 1:41 PM
Jayakrishna 🇮🇳
15th Oct 2022, 1:40 PM
Just Some Random Guy
Just Some Random Guy - avatar
+ 1
Thank you so much, I like both styles but this here seems very interesting, I've never seen it done like this: //"System.out.println(rec(f));" // but I forgot about doing it this // way: // i = rec(f); public class Program { public static void main(String[] args) { int f=1; int i=0; rec(f); //You need to initialize the returned value in i System.out.println(rec(f)); } public static int rec(int i){ return i; } }
15th Oct 2022, 2:30 PM
Natanael