java just curly braces

后端 未结 5 1255
一整个雨季
一整个雨季 2020-12-29 05:21

I was reading a book and there were a few example with programs that has just curly braces

for example

 public static void main(String args[]){
             


        
5条回答
  •  心在旅途
    2020-12-29 06:04

    Be careful, it is NOT ALWAYS an initialisation block as others have suggested. In your case it is a variable scoping mechanism called a Code Block or block.

    If it is outside of a method, then it is!

    Example

    public class MyClass {
    
       {
          // this is an initialisation block
       }
    
    }
    

    However, if it is inside a method, it is NOT! In this case (which is the case in your example), it is a code block. Anything initialised inside the curly braces is not visible outside

    Example

    public static void main(String args[]){
    
         {
              String myString = "you can't see me!";
         }
         System.out.println(myString); // this will not compile because myString is not visible.
     }
    

提交回复
热议问题