Confused About How Foo and Bar Methods Work in Java?

0
0
Asked By CuriousCoder99 On

I'm struggling to grasp how the methods `foo` and `bar` work in this Java program. My study guide for the midterm includes this, and I'm really hoping someone can shed some light on it. Here's the code snippet:

```java
class Driver {
public static void main(String[] args) {
int a = bar(2);
int b = foo(a);
System.out.print(b);
}
static int foo(int a) {
a = bar(a) - 2;
return a;
}
static int bar(int a) {
System.out.print(a);
return a + 1;
}
}
```

What output can I expect from this program?

1 Answer

Answered By JavaNerd42 On

When you call `bar(2)`, it prints `2` and returns `3` because of `return a + 1;`. Then in `foo`, you call `bar(a)`, which means `bar(3)`, printing `3` and returning `4`. Finally, `foo` returns `4 - 2`, which equals `2`, so the output of the program is just `2`. Don't get too hung up on the names `foo` and `bar`, they are often used as generic placeholders in programming examples.

CuriousCoder99 -

Ah, thank you! That really clarifies things for me.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.