1

I'm trying to learn Java and attempted an interview question from Google. The answer can be found here: https://www.geeksforgeeks.org/sort-array-converting-elements-squares/. When I copy paste that exact code into repl.it it tells me Main is missing, so I add main as you can see below, but then it tells me something is wrong with static. Could someone point me in the correct direction? I watched videos on what static is, but none have helped so far so turning to stack overflow. Many thanks.

It gives the following error:

javac -classpath .:/run_dir/junit-4.12.jar:target/dependency/* -d . Main.java
Main.java:5: error: Illegal static declaration in inner class Main.GoogleInterview
    public static void sortSquares(int arr[])
                       ^
  modifier 'static' is only allowed in constant variable declarations
Main.java:13: error: Illegal static declaration in inner class Main.GoogleInterview
    public static void main(String[] args)
                       ^
  modifier 'static' is only allowed in constant variable declarations
2 errors
exit status 1

Code:

import java.util.*;
import java.io.*;
class Main{
class GoogleInterview {
    public static void sortSquares(int arr[])
    {
        int n = arr.length;
        for (int i = 0; i < n; i++)
            arr[i] = arr[i] * arr[i];
        Arrays.sort(arr);
    }
  
    public static void main(String[] args)
    {
        //Insert array of numbers below
        int arr[] = { -3, 1, 0, 2, -482, 5 };
        //Insert array of numbers above
        
        int n = arr.length;
        sortSquares(arr);
        System.out.println("");
        System.out.println("After Sort ");
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
}
}
paulsm4
  • 114,292
  • 17
  • 138
  • 190
Oliver
  • 71
  • 4
  • 1
    Get rid of duplicate redundant "class Main", change your declaration to `public class GoogleInterview {...}`, and make sure your file is named "GoogleInterview.java". See this thread: https://stackoverflow.com/questions/1953530/why-does-java-prohibit-static-fields-in-inner-classes – paulsm4 Jun 01 '21 at 22:28
  • Or just remove `class GoogleInterview {` and the last `}`. – enzo Jun 01 '21 at 22:29
  • 1
    And don't listen to Enzo. "Main" is *horrible* class name (and all too common among naive users) ! But again: the central problem is having "static" in a nested class. The solution is to avoid nested classes unless you actually need them :) – paulsm4 Jun 01 '21 at 22:30

1 Answers1

1

The error has to do, in fact, with the static modifier.
Your code declared an inner class inside the Main class: that's the problem. A non-static inner class cannot declare static methods, due to its implicit relationship with an instantiation of its outer class.