Knowee
Questions
Features
Study Tools

class Main {    public static void main(String args[]) {           System.out.println(fun());    }     int fun() {        return 20;    } }Run Time Error200Compiler Error

Question

class Main {    public static void main(String args[]) {           System.out.println(fun());    }     int fun() {        return 20;    } }Run Time Error200Compiler Error

🧐 Not the exact question you are looking for?Go ask a question

Solution

This code will result in a Compiler Error. The reason is that the method fun() is an instance method, but it is being called from a static context, specifically the main method. In Java, a static method can't access an instance method directly.

To fix this, you could either make the fun method static like so:

class Main {    
    public static void main(String args[]) {           
        System.out.println(fun());    
    }     
    static int fun() {        
        return 20;    
    } 
}

Or you could create an instance of the Main class and call the fun method on that instance:

class Main {    
    public static void main(String args[]) {  
        Main main = new Main();         
        System.out.println(main.fun());    
    }     
    int fun() {        
        return 20;    
    } 
}

Both of these solutions will print out 20 when run.

This problem has been solved

Similar Questions

class Test {   public static void main(String args[]) {       System.out.println(fun());   }   static int fun() {       static int x= 0;       return ++x;   }}

The following code contains one compilation error, find it?public class Test { Test() { } // line 1 static void Test() { this(); } // line 2 public static void main(String[] args) { // line 3 Test(); // line 4 }}

What is the output of the following Java program?class Main { public static void main(String args[]) { final int i; i = 20; i = 30; System.out.println(i); }}OptionsCompiler Error30Garbage value0

What is the output of the following code?public class Solution { static int x = 10; public static void main(String args[]) { System.out.println(x); } }Options: Pick one correct answer from below100Compilation errorRuntime error

What will be the output of the following code snippet?public class MyClass {    static int value = 10;      public void printValue() {        System.out.println(value);    }        public static void main(String[] args) {        MyClass obj = new MyClass();        obj.printValue();    }}Question 4Answera.0b.10c.Compilation errord.Runtime exception

1/3

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.