What will be the value printed out?public class MethodExample { public static int square(int num) { num = num * num; return num; } public static void main(String[] args) { int num; num = 7; square(num); System.out.print(num); }}
Question
What will be the value printed out?public class MethodExample { public static int square(int num) { num = num * num; return num; } public static void main(String[] args) { int num; num = 7; square(num); System.out.print(num); }}
Solution
The value printed out will be 7.
Here's why:
- The
mainmethod declares an integer variablenumand assigns it the value 7. - The
squaremethod is called withnumas an argument. This method squares the input (in this case, 7*7=49) and returns the result. However, the returned result is not stored or used in any way. - The
System.out.print(num);statement prints the current value ofnum, which is still 7 because thesquaremethod does not change the value ofnumin themainmethod. Thesquaremethod only changes the value of its own localnumvariable, not thenumvariable in themainmethod.
So, the output of the program will be 7.
Similar Questions
Analyze the following code: public class Test { public static void main(String[] args) { int n = 2; square(n); } void square(int n) { System.out.print(n + " square is " + n * n); }}The program has a compile error because method square(int n) does not return a value.The program has a compile error because method square(int n) is not declared static.The program runs fine.The program prints2 square is 4
What is the output of the following code?public class Solution { public static void main(String args[]) { int x = 7--2; System.out.println(x); }}
Find the output:class PrintNumber { public static void main(String args[]) { System.out.println(print()); } int print() { return 30; }}
What is the output of the following code?public class Test { public static void main(String args[]) { int x = 10; System.out.print(x + " "); } static { int x = 20; System.out.print(x + " "); }}Options: Pick one correct answer from below10 2020 1010 1020 20
What is the output of the above program?class Num { Num(double x ){ System.out.println( x ) ; } }public class Test extends Num { public static void main(String[] args){ Num num = new Num( 2 ) ; } }02.0Compile time error None of the above
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.