Is this valid Java code? My teacher claims it is, but I'm really not so sure [duplicate]
Asked Answered
A

1

8

Granted he didn't show us actual code here, just mentioned it, I found it extremely bizarre.

For example, according to what he said this is valid Java:

public class Person
{
    String Name;
    int Age;

    {
        //These two braces just chilling together - VALID? :O
    }
}
Afterguard answered 11/5, 2010 at 16:39 Comment(3)
Sure - Give it a try. It is valid in most languages. Well, most that I have developed in. Just to make sure I tried it in the code I have open right now.Carp
Why can't you compile it for yourself?Tallage
Fire up eclipse (or any other IDE) and type it out yourself - the IDE won't complain.Laminitis
R
16

Yes - it's the instance initializer. You can also use it along with anonymous subclasses for Double-Brace Initialization.

Rase answered 11/5, 2010 at 16:40 Comment(4)
Not with a semi-colon in between. The { } are just a scope definition.Beaune
Nope, not when it's floating around in the class body like that - it's an empty instance initializer. Inside methods, then yes, it's a scope definition.Rase
@vfilby: No, if it's a block within a class but not within a method or constructor, it's an instance initializer.Roose
My bad, didn't look closely enough at the example. Thanks guys.Beaune

© 2022 - 2024 — McMap. All rights reserved.