I don’t know if the question can be called rhetorical, but that’s the point. Can anyone explain all the subtleties associated with curly brackets - {} (if there are any, of course)

I have an idea that if , for , methods, classes and other things use curly braces as if to define their field of influence, and in fact, when we write if { // код } , we mean that this block will be intended if'u located with him.

I am interested in, are there any features of blocks that do not have such anchoring?

For example, I cannot write sysout("bla"); outside the method sysout("bla"); (that is, right inside the class), but when I enclose the operator in a {} block {} problem disappears - magic. Why is that?

Somewhere I saw some information about this, for example, that in classes there are certain static initialization blocks and so on, like:

 static { // Чудо-код } Заранее благодарю; 
 // Или может еще как то так... 

Why scolds here:

 public class Main { System.out.println("a"); public static void main(String[] args) { } } 

but not here

 public class Main { { System.out.println("a"); } public static void main(String[] args) { } } 

The code in the block is perceived as what? What are the dramatic differences?

  • Read, did not understand - Herrgott
  • The curly brackets themselves are just a construct that can mean different things depending on the context. From your question now it is not at all clear what exactly interests you. Static initialization really exists and is performed at the time of loading the class, allowing you to do any work at this moment (this, however, is not strongly recommended, but sometimes it is not appropriate to define a constant otherwise). - etki
  • "... which can mean different things depending on the context ..." - here it is, what different things? what context? I want to know in detail about such things - DuckImMud

2 answers 2

The class structure in Java can include a field initialization block, a static initialization block, a non-static initialization block for a class object, methods and class constructors (as a special case of methods).

The syntax of the language assumes that the scope of each operator (beginning and end) should be indicated by curly brackets. The top level is usually denoted by the class operator and its scope may include field initialization, static and non-static initialization block, constructors, and methods. Borders (beginning and end) of constructors, methods and initialization blocks must also be indicated by curly brackets. In addition, curly braces can combine several statements into a separate executable block (including one statement, oddly enough :)).

The executable code in this structure can only be in the body of a method (constructor, as a special case of a method) or a block of static (non-static for an object) initialization and launched for execution by the name of this method (in the case of a block of static (non-static) initialization - at the time of creating the class ).

Thus, in the structure of the form:

 public class Program { { System.out.println("a"); } } 

We define a non-static initialization block. The output of the value "a" will be performed each time this instance of the class (object) is created.

 public class Main { public static void main(String[] args) { Program p = new Program(); } } 

Print "a" to the console. It should be noted that if you define a non-static initialization block in the program entry class (which contains the main() method), then this block will not be executed, since an instance of this class is not created and this block must be defined as static .

If the curly brackets are omitted, then an error occurs, because in the class structure, without separate selection into the code block with curly brackets, only initialization of the class fields can be performed:

 public class Program { int SomeValue; } 

More about the types of initialization in the classroom.

Well, the answer to your question : In the first case, a syntax error is obtained, since language operators cannot exist outside the code block defined by curly brackets, in the second case you define a non-static initialization block. There is no magic here.

    In braces are placed:

    Body interface or class:

     interface MyInterface { //Тело интерфейса } class MyClass { //Тело класса } 

    Body Method:

     public void myMethod(...) { //Тело метода } 

    Conditional Operator Body:

     if(...) { //Тело условного оператора "if" } switch (...) { case 1: //... break; case 2: //... break; default: //... break; } 

    Cycle body:

     for(int i=0; i<10; i++) { //Тело цикла "for" } while(...) { //Тело цикла "while" } do { //Тело цикла "do ... while" } while (...); 

    The set of elements to initialize the array:

     int[] myArr = {0, 2, 4, 6, 8}; 

    Static initialization block (executed when the class is first loaded):

     class MyClass { static { //Блок статической инициализации } } 

    Block of non-static initialization (performed after working out any constructor of this class):

     class MyClass { { //Блок НЕстатической инициализации } } 
    • one
      and also a synchronized block and it is simply not forbidden to limit the scope anywhere by the block { ... } - Nofate
    • For sure. Brilliant) - Flippy