Menu
Topics Index
...
`

Methods Output502


If you need explanation Read this topic

If you need Answer Take test on this topic

Methods Output502
What will be the output of the following program.
class MethodsTest
{
    public static void main(String s[])
    {
        int a = 34;
        int b = 56;
        sum(a, b);
        System.out.println("c = " + c);
    }
    
    public static int sum(int a, int b)
    {
        System.out.println("a = " + a + " b = " + b);
        int c = a + b
        return c;
    }
}

A. a = 34 b = 56
c = 90
B. a = 56 b = 34
c = 90
C. c = 90
D. Compilation Error
Topic: Java Methods - Parameter Passing And Scope

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

d

Posted by Phan Sovan Narith    2014-11-21 12:31:06


Ans is D...here we create local variables named with a and b..and these local variables assigned with the values 34 and 56..here we cant use local variables without initilization...if we use lyk that than it iwll give an error..here we initilized so no problem...and the scope of these local variables is that in this method only we cant use these local variables in another method...if we use lyk that than compiler will give an error...
but we can pass these variables to any method....
here have method sum() we pass these 2 variables this is call by value..

here we have another methos as sum() which is static so that these we can call these method without using the obejct...as the main() static method so that we can call these directly from one static method to another static method can call directly...

in this method 1st we are printing the values of a and b..next we create the variable c and stored the sum of the a+b in c next we are returning the c

here in main() we are try to print the c which is created in the sum() the scope of that c local variable is till that method only we cant use that variable out side that method...so here compiler will raise an error saying could not find c...if we have variable in main() as c than this program wil work..but we dont have variable so that compiler will give error.

Posted by Uday Kumar    2014-11-21 12:57:45


© meritcampus 2019

All Rights Reserved.

Open In App