Anonymous Code Blocks in Java

Anonymous code blocks in Java

They restrict variable scope.

public void foo()
{
{
int i = 10;
}
System.out.println(i); // Won't compile.
}

In practice, though, if you find yourself using such a code block that's probably a sign that you want to refactor that block out to a method.

Anonymous code block in anonymous class Java

 { foo(); }

is called instance initializer.

why?

As per java tutorial

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

code block without any method signature

That block called as instance initialization block. When the object is created in Java, there is an order to initialize the object.

  1. Set fields to default initial values (0, false, null)
  2. Call the constructor for the object (but don't execute the body of the constructor yet)
  3. Invoke the constructor of the superclass
  4. Initialize fields using initializers and initialization blocks
  5. Execute the body of the constructor

For more details, look here and JLS 8.6

If it's valid syntax then what is the use of it?

Instant initializers used to initialize the instance variables. You can use the instance initializer when declaring an anonymous class.

An instance initializer declared in a class is executed when an
instance of the class is created (§15.9), as specified in §8.8.7.1.

Static variable in an anonymous block in java

Directly within class, a block is an instance initializer block. You can't declare static variables in an instance initializer block. Simply remove it from the block:

public class A {
static int a=1;
}

Instance initializer blocks are called when instances are created, prior to the code in any instance constructors. So it makes sense you can't declare members there (static or otherwise). They're code, as though inside a constructor. Example:

import java.util.Random;

public class Example {
private String name;
private int x;
private int y;

{ // This is the
this.x = new Random().nextInt(); // instance
this.y = this.x * 2; // initializer
} // block

public Example() {
this.name = null;
}

public Example(String name) {
this.name = name;
}
}

In the above, regardless of which constructor is used, the first thing that happens is the code in the instance initializer block, followed by the code in the constructor that was used.

There are also static initializer blocks, which do the same thing for static stuff when the class is loaded. They start with the keyword static, more in the link above.

What is the reason to use these anonymous block to call super class method in this code?

Let's say you could insert it into your updateItem-Method but then it would get called every time the item is updated.

This might not be a big Problem with setPrefWidth as nothing changes but imagine you have something like firstInitialize();which is not supposed to be called more than once.

Therefore you can use the Initializer Block. Otherwise you would have to add a variable like bool isInitialized where you check first, if the variable is true and in case it's not, you performe your Action.

You can also have a look at: Initializing Fields

Anonymous code blocks in Groovy

You can use anonymous code blocks in Groovy but the syntax is ambiguous between those and closures. If you try to run this you actually get this error:

Ambiguous expression could be either a
parameterless closure expression or an
isolated open code block; solution:
Add an explicit closure parameter
list, e.g. {it -> ...}, or force it to
be treated as an open block by giving
it a label, e.g. L:{...} at line: 1,
column: 1

Following the suggestion, you can use a label and it will allow you to use the anonymous code block. Rewriting your Java code in Groovy:

l: {
int i = 0
println i
}
int i = 10
println i

Anonymous block acting like static block

{
System.out.println("inside static...");
}

... is not a static block, it's an instance block.

static {
System.out.println("inside static...");
}

... would be a static block.

Anonymous code blocks in Java

They restrict variable scope.

public void foo()
{
{
int i = 10;
}
System.out.println(i); // Won't compile.
}

In practice, though, if you find yourself using such a code block that's probably a sign that you want to refactor that block out to a method.

print plsql variable value from anonymous block to Java

The question linked to from a comment shows an example of what you need to do, but you seem to be struggling to translate that to your situation.

Your anonymous block doesn't (and can't) return a result set, so it shouldn't be executed as a query, and shouldn't be a prepared statement; you need to have a callable statement instead:

 CallableStatement statement = null;
try {
statement = connection.prepareStatement("\n" +
...

Then you either need to assign the value of your PL/SQL variable to a bind variable placeholder:

 ...
" l_console_message := p_temp_table_name||' created.'; " + "\n" +
" ? := l_console_message; " + "\n" +
" end if; " + "\n" +
...

or don't have l_console_message at all (so it doesn't even need to be declared), just assign the string directly to a bind variable placeholder:

 ...
" ? := p_temp_table_name||' created.'; " + "\n" +
" end if; " + "\n" +
...

Either way the dbms_output call isn't useful here. (It is actually possibly you retrieve the dbms_output buffer from Java, but it's a lot more work).

Then you need to declare an OUT bind variable to receive the string, and call the statement with execute() rather than executeQuery():

    statement.registerOutParameter(1, Types.VARCHAR);
statement.execute();

Then you can retrieve the string value that has been put in to the bind variable; e.g. to print it straight to console:

    System.out.println(statement.getString(1));

The ResultSet, rs and loop have gone completely.



Related Topics



Leave a reply



Submit