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
Question
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
Solution
The program has a compile error because method square(int n) is not declared static. In Java, a static method belongs to the class rather than the object of a class. The main method is static and cannot call the non-static method square(int n) directly. To fix this, you should declare the square method as static.
Similar Questions
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); }}
What is the result of the following program?1: public class Squares {2: public static long square(int x) {3: long y = x * (long) x;4: x = -1;5: return y;6: }7: public static void main(String[] args) {8: int value = 9;9: long result = square(value);10: System.out.println(value);11: } }*A. -1B. 9C. 81D. Compiler error on line 9.E. Compiler error on a different line.
class Test { public static void main(String args[]) { System.out.println(fun()); } static int fun() { static int x= 0; return ++x; }}
class Sample{ private double num = 100; private int square(int a){ return a*a; }} public class Test{ public static void main(String args[]){ Sample obj = new Sample(); System.out.println(obj.num); System.out.println(obj.square(10)); } }Select one:a.Compile time errorb.100c.Run time errord.Executes but no output
Given1. public class Program{2. static int x = 20;3. public static void main(String args[]){4. Program pr = new Program();5. pr.x = 5;6. int y = x/pr.x;7. System.out.print("y = ");8. System.out.print(y);9. }10. }What will be the result?*y = 2Compilation fails due to an error on line 8.y = 1y = 4Compilation fails due to an error on line 6.
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.