I don't really understand the purpose of brackets enclosing code

112
July 25, 2021, at 08:30 AM

I'm just playing with integer arrays and find that the following won't compile with multiple errors:

   public class GetData{
   int[]       arr = new int[5];
   arr[0] = 30;
                    }

But if I add some brackets around the code it compiles:

   public class GetData{
   {
   int[]       arr = new int[5];
   arr[0] = 30;
   }                    }

Probably there is something fundamental that I'm not understanding. I don't why the first code section won't compile.

Answer 1

A class can't just contain code. It can only contain:

  • Classes (so-called inner classes)
  • Semi-colons. These don't do anything, but class Foo { ;;; } compiles.
  • methods.
  • field declarations.
  • Initializers.
  • Constructors.

And of course comments, which can appear anywhere.

Crucially, int[] arr = new int[5]; is a field declaration and therefore legal: It declares a field named arr, of type int[], with an initializing expression.

arr[0] = 30; on the other hand, is an assignment expression, which is code. Which isn't legal here. You need to shove that in a method or constructor or some such.

{} inside a class is an exotic java construct, rarely used: The instance initializer. It's very similar to a constructor.

That explains why your second snippet does compile: The first batch of brackets defines 'these are the brackets that surround the content of this class definition', and the brackets inside of that define: "This brackets code which is an instance initializer". arr[0] = 30; is legal in them, but this isn't java code you'd ordinarily put out there, this stuff should go in a method:

public class GetData /* not a good name! */ {
    public void doStuff() {
        int[] arr = new int[5];
        arr[0] = 30;
    }
}

Compiles just fine.

Rent Charter Buses Company
READ ALSO
I need to obtain the greater of the two counts obtained by calculating rows with particular words in them

I need to obtain the greater of the two counts obtained by calculating rows with particular words in them

From a table named 'review', I want to find the maximum count among the two conditions

106
How to correctly merge multiple csv files in Python

How to correctly merge multiple csv files in Python

How can I correctly merge multiple csv files with, in most cases, different column names between each file? I have tried usingconcat() in the following code:

199
Embed svg in safari doesn't able to call the click event in safari browser

Embed svg in safari doesn't able to call the click event in safari browser

Embed svg in safari doesn't able to call the click event in safari browser

135
React socket io client emitting twice to node server

React socket io client emitting twice to node server

I am making a react app with node as backendThey communicate using socket-io

168