I am getting ready for a java certification exam and I have seen code LIKE this in one of the practice tests:
class Foo { int x = 1; public static void main(String [] args) { int x = 2; Foo f = new Foo(); f.whatever(); } { x += x; } // <-- what's up with this? void whatever() { ++x; System.out.println(x); } }
My question is ... Is it valid to write code in curly braces outside a method? What are the effects of these (if any)?
It's called an initializer block and is invoked every time an instance of the class is created. The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
In a Java program, everything is subordinate to the top line — the line with class in it. To indicate that everything else in the code is subordinate to this class line, you use curly braces. Everything else in the code goes inside these curly braces. \
String n = s. replaceAll("/{", " "); String n = s. replaceAll("'{'", " ");
String h = "{hiren:}"; h=h. replaceAll(":\\}", ":\"\"}"); Otherwise, you can use String#replace with no regular expression nor escaping needed. String h = "{hiren:}"; h=h.
What Do Curly Braces Do in Java? Curly brackets or braces in Java are used to delimit blocks of code inside a program. That is it determines the limits or boundaries of the code. They are most commonly used with structured control flow constructs such as if/else, while/for loops, and subroutines (methods).
For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block. What is Source Code and What Does it Do?
Curly braces play a big role in code structure within popular programming languages such as Java, C++ and more. Here's how to properly line up code with curly brackets. At their core, all programming languages share similarities.
However, experienced developers prefer a 'same-line' approach, which means the curly bracket goes on the same line of code that initiates the new code block. Popular Java IDEs such as Eclipse, NetBeans and IntelliJ use this same-line approach as the default setting for code formatters.
Borrowed from here -
Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods. Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
{ // whatever code is needed for initialization goes here }
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
You may also wanna look at the discussions here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With