Knowee
Questions
Features
Study Tools

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

Question

Code Example

class Test {
   public static void main(String args[]) {
       System.out.println(fun());
   }
   static int fun() {
       static int x= 0;
       return ++x;
   }
}
🧐 Not the exact question you are looking for?Go ask a question

Solution

The code you've written is in Java, but it contains an error. In Java, you cannot declare a variable as static inside a method. The static keyword in Java is used in the declaration of a class variable, which means it belongs to the class rather than any instance of the class.

Here's the corrected version of your code:

class Test {
    static int x= 0; // Declare static variable outside the method

    public static void main(String args[]) {
        System.out.println(fun());
    }

    static int fun() {
        return ++x; // Increment the static variable
    }
}

In this corrected version, the static variable x is declared outside the fun() method, but within the Test class. This means x is a class variable and it can be accessed and modified by the fun() method. The fun() method increments x by 1 each time it is called and then returns the new value of x. The main() method calls fun() and prints the returned value.

This problem has been solved

Similar Questions

public class Main { public static void main(String args[]) { System.out.print("Hello World "); System.out.println("Hello Know Program"); }}

rrect answerThe default value of a static integer variable of a class in Java is,Options0Garbage value1-1Null

The main method in java should ___________.Select one:a.return intb.be public staticc.take boolean[] as argumentd.be private static

Static methods and variables can be accessed without creating an instance of the class.Question 23Answera.Trueb.False

Which keyword must precede the main method in a Java program?*1 pointpublicmainvoidstatic

1/2

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.