What is the purpose of the {} outside of any methods? [duplicate] - java

This question already has answers here:
Why is this Java code in curly braces ({}) outside of a method?
(3 answers)
Java empty block scope
(3 answers)
Closed 9 years ago.
I accidently made a pair of {} outside of all method and worked.
public static void main(String[] args) {
System.out.println("ddd");
}
{
System.out.println("ttt");
}
Of course if you run this code the result is "ddd" and it writes "ttt" only if I create a new instance of it.
And if I make it static {System.out.println("ttt");} it works as designed and the result is "ttt" then "ddd"
Is there any practical use of this? Why would anyone use it with contructor or without a written constructor?
My impressions are: it seems working, but smells like bad and strange practice. Am I right?

{} define the scope of a module or block of code (like a method, static block, class, etc.)
And every module should have a name of something to identify it from other modules.
In your case, simply putting {} means you are creating a block of code but not naming, hence it gives error. But putting {} inside a method will work fine.
But when you put static keyword before it, you are making a static block that has got special meaning in java. it means that everything inside static block will be executed when your class gets loaded first time.
See this link for initializer blocks from Java Tutorials website

Is there any practical use of this?
There is one "idiom" that makes use of instance initializer blocks:
Map mymap = new HashMap() {{put("a", 1); put("b", 2);}};
This is a concise way to create a map that is initialized with a given set of entries. And when you break it down, it is declaring and instantiating an anonymous subclass of HashMap which uses an instance initializer block to populate the new map.
My impressions are: it seems working, but smells like bad and strange practice.
That's a subjective statement. The only rational argument I can think of for initializer blocks being bad / strange is that people don't use them. And that argument smells of circular logic.

Its all about Initializer blocks
Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
{
// will execute when intialization
}
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

These are called initializer blocks. They are called along with all constructor. So any constructor call will invoke this code.
A static block is called only when class is loaded.

Normally, you have to put the 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:
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
Source: here

It may be unfamiliar, but it is not bad per se. It's an initializer block that is executed on construction. See here for a more detailed explanation that includes static initialization blocks also.

Related

Processing - Return type for method is missing [duplicate]

If I try to assign a value to a variable in a class, but outside a method I get an error.
class one{
Integer b;
b=Integer.valueOf(2);
}
but, if I initialize it during the creation, it works.
class one{
Integer b=Integer.valueOf(2);
}
Inside a method, it works in both cases.
you need to do
class one{
Integer b;
{
b=Integer.valueOf(2);
}
}
as statements have to appear in a block of code.
In this case, the block is an initailiser block which is added to every constructor (or the default constructor in this case) It is run after any call to super() and before the main block of code in any constructor.
BTW: You can have a static initialiser block with static { } which is called when the class is initialised.
e.g.
class one{
static final Integer b;
static {
b=Integer.valueOf(2);
}
}
Because the assignments are statements and statements are allowed only inside blocks of code(methods, constructors, static initializers, etc.)
Outside of these only declarations are allowed.
This :
class one{
Integer b=Integer.valueOf(2);
}
is a declaration with an initializer. That's why is accepted
A more general answer would be that the class body is about declarations, not statements. There is special provision for statements occuring in class body, but they have to be marked explicitly as either class initializers or instance initializers.
In Java, when defining a class, you can define variables with default values and add methods. Any executable code (such as assignments) MUST be contained in a method.
This is the way java works, you cannot add non-declaration code (sorry i don't know the correct term) inside the class, that code should be inside methods.
I think terminology-wise, couple of other answers are slightly off. Declarations are also statements. In fact, they are called "declaration statements", which are one of the three kinds of statements. An assignment statement is one form of "expression statement" and can be used only in constructs such as methods, constructors, and initializers. Check out the Statements section in this Oracle's tutorial link.
Methods have the responsibility to perform mutations on the member variables. If the member variable needs to be initialized, java provides a way to do it during construction, class definition (latter case). But the mutation cannot be performed during definition.(former case). It is usually done at the method level.
Objects are meant to hold the state, while methods are meant to operate on that state.

Non-Static initializer blocks - do I have a bit more control?

I am still on a learning curve in Java. To understand a bit more of initializer blocks I created a small test class:
public class Script {
{
Gadgets.log("anonymous 1");
}
public Script() {
Gadgets.log("constructor");
}
{
Gadgets.log("anonymous 2");
}
}
When I create an instance, I get this log:
Script: anonymous 1
Script: anonymous 2
Script: constructor
This tells me, both initializer blocks run BEFORE the constructor, in the order they appear in the source code (same as static initializers).
What I want to know is: Do I have a little more control over this behavior?
Because Java Documentation says (source):
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.
So what exactly does "copies initializer blocks into every constructor" mean? According to my log, it seems, they are copied at the beginning of each constructor. Is this right?
Sharing such blocks between multiple constructors would also make perfectly sense, if they were copied to the END of each constructor (that's what I expected in my anonymous 2).
Is there a way to control those blocks a bit more or is my only option the "classic" way of writing a named method that gets called in every constructor if I want to do common tasks at the end of each constructor?
A constructor executes in the following order:
super() call, implicit or explicit.
Variable initializers and initializer blocks, in the order they appear in the source code.
Remainder of the constructor.
This is specified in the JLS and cannot be altered.
If a this() call is present it replaces (1) and (2).

what does static { // some code } mean? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Static Initialization Blocks
What does the following mean in java?
static {
WritableComparator.define(IntPair.class, new Comparator());
}
That means static initialization block which will be executed on class load.
If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.
It means that the code within that block will run once, when the type is loaded, before any constructors are called, but after any field initialisers are run.
Note that you cannot set any instance fields in the static block. There is no concept of this in there, just as in any other static methods.

Static Block in Java [duplicate]

This question already has answers here:
What is the difference between a static and a non-static initialization code block
(9 answers)
Closed 8 years ago.
I was looking over some code the other day and I came across:
static {
...
}
Coming from C++, I had no idea why that was there. Its not an error because the code compiled fine. What is this "static" block of code?
It's a static initializer. It's executed when the class is loaded (or initialized, to be precise, but you usually don't notice the difference).
It can be thought of as a "class constructor".
Note that there are also instance initializers, which look the same, except that they don't have the static keyword. Those are run in addition to the code in the constructor when a new instance of the object is created.
It is a static initializer. It's executed when the class is loaded and a good place to put initialization of static variables.
From http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
If you have a class with a static look-up map it could look like this
class MyClass {
static Map<Double, String> labels;
static {
labels = new HashMap<Double, String>();
labels.put(5.5, "five and a half");
labels.put(7.1, "seven point 1");
}
//...
}
It's useful since the above static field could not have been initialized using labels = .... It needs to call the put-method somehow.
It's a block of code which is executed when the class gets loaded by a classloader. It is meant to do initialization of static members of the class.
It is also possible to write non-static initializers, which look even stranger:
public class Foo {
{
// This code will be executed before every constructor
// but after the call to super()
}
Foo() {
}
}
Static block can be used to show that a program can run without main function also.
//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
static
{
System.out.println("Welcome to Java");
System.exit(0);
}
}
A static block executes once in the life cycle of any program,
another property of static block is that it executes before the main method.
Static blocks are used for initializaing the code and will be executed when JVM loads the class.Refer to the below link which gives the detailed explanation.
http://www.jusfortechies.com/java/core-java/static-blocks.php
yes, static block is used for initialize the code and it will load at the time JVM start for execution.
static block is used in previous versions of java but in latest version it doesn't work.

Why is accessing a static method from a non-static method bad?

Netbeans tells me it's bad to access a static method from a non static method. Why is this bad?
"Accessing static method getInstance" is the warning:
import java.util.Calendar;
public class Clock
{
// Instance fields
private Calendar time;
/**
* Constructor. Starts the clock at the current operating system time
*/
public Clock()
{
System.out.println(getSystemTime());
}
private String getSystemTime()
{
return this.time.getInstance().get(Calendar.HOUR)+":"+
this.time.getInstance().get(Calendar.MINUTE);
}
}
You're probably accessing the static method from an instance instead of directly. Try using Calendar.getInstance() instead:
private String getSystemTime()
{
return Calendar.getInstance().get(Calendar.HOUR)+":"+
Calendar.getInstance().get(Calendar.MINUTE);
}
What do you mean by "return a static method"? It's fine to call a static method from an instance method in my view - depending on the circumstances, of course. Could you post some code which Netbeans complains about?
One thing I could imagine is if you only use static methods from an instance method, without using any of the data of the instance. Sometimes that's what's required to implement an interface or override a method from a base class, but if you're not overriding anything and you're not using any instance variables, it's nice to make the method static to show that it really doesn't depend on a particular instance.
EDIT: With the edited question, this makes a lot of sense. IMO it's a deficiency in Java that allows it in the first place. It can make for very misleading code. My favourite example (which means old-timers may well have seen me post it before :) is with Thread.sleep. What does it look like this code does?
Thread t = new Thread(someRunnable);
t.start();
t.sleep(1000);
To my mind, it looks like the new thread is asked to sleep - similar to a call to suspend. But no - you can only ask the currently executing thread to sleep, which is why Thread.sleep is a static method. The above code is legal Java, and will make the currently executing thread sleep for a second while the newly created thread (probably) runs... not at all what the code looks like at first glance.
Do you have the order reversed? If so, it makes sense that you cannot access a non-static method from a static method. If not, I'd like to know why this is bad as well!
A non-static method can not be referenced from a static context. Static methods can be referenced from a non-static context.
Is it a Netbeans error or warning ? Can you post code that is causing it ?
It's just fine to call time.getInstance(). The compiler will look at the type of the variable, Calendar in this case, and call the method there. It ends up being compiled exactly as Calendar.getInstance(). Note that the actual value of time does not contribute to this, i.e. it can even be null and it doesn't matter.
It's this indirection and difference from regular methods that is frowned upon. It's best to express it directly as Calendar.getInstance().
why just not explain simple:
if you call nonstatic method,
1) you create new instance with a=new Class();
2) then call method a.method;
if you call static method:
1) you call it Class.method;
You can do it with static method just because it is independent within its class and have all it needs for calling. If it depends on some other info (as constructor) you dont declare it static, it will fail.
In java all static member variables will be loaded into memory first,
then all static members will be loaded,
after that non-static variables and member functions will be loaded into memory,
after that static main block will be executed.......
so it was giving the error that a non..............

Categories