Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

main method

  Asked By: Arland    Date: Oct 25    Category: Java    Views: 955

This code, why the output is
y is 6
a is 9
x is 6

instead of

x is 6
y is 6
a is 9

I thought the main method should execute first so x should be the first to
print out???

public class Q1a {
public static void main(String[] args) {
int x = 6;
int y = 3;
int z = foo(x,y);
System.out.println("x is " + x);
public static int foo(int y, int a) {
a = a + y;
System.out.println("y is " + y);
System.out.println(" a is "+a);
return a;




3 Answers Found

Answer #1    Answered By: Paul Brooks     Answered On: Oct 25

the output  is
y is 6
a is 9
x is 6
is correct .
u got a method  call before printing the value of x,so first it goes into the
method calla nd perform the necessary operation,in the method foo(int,int) u got
two println  statements for y and a so first it prints them first and then it
prints the value of x,hope u got.

Answer #2    Answered By: Sheryl Morgan     Answered On: Oct 25

That is true

Because the first function is main, right?

But in your main  function you called other function foo(x,y)

And in your foo function you have print the result for y and a

So x is shown the last

Check it again and you will find out.

Answer #3    Answered By: Brian Ross     Answered On: Oct 25

You infact call the second method  before the main  method ends.

So you are right the main method fires first, but if you call something
else from the main method it will run the called bits from the main method.

int z = foo(x,y);

System.out.println("x is " + x);

To find the value of Z, it must run the method foo(x,y). It can't go on
untill it has the answer for the variable z.

However if you where to do something like ...

public static  void main(String[] args) {

int x = 6;

int y = 3;

int z;

System.out.println("x is " + x);

z = foo(x, y);

Your out put would be right.

The reson for this is that you are finding the actual value for z after
you printout the results of x.

Didn't find what you were looking for? Find more on main method Or get search suggestion and latest updates.